import { useState } from "react";
import { Settings, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, TextArea, Toggle, SaveBar } from "./ui";
import { useSiteSettings } from "@/hooks/useSiteSettings";

type GeneralState = {
  siteName: string;
  tagline: string;
  description: string;
  seoTitle: string;
  seoDescription: string;
  seoKeywords: string;
  ogImage: string;
  metaTitle: string;
  metaDesc: string;
  metaKeywords: string;
  address: string;
  phone: string;
  whatsapp: string;
  supportEmail: string;
  hours: string;
  social: { facebook: string; x: string; linkedin: string; instagram: string; youtube: string };
  footerText: string;
  copyright: string;
  maintenance: boolean;
  maintenanceMessage: string;
  analyticsId: string;
};

const DEFAULTS: GeneralState = {
  siteName: "DoItEasy",
  tagline: "Dedicated With Confidence.",
  description: "Enterprise-grade cloud, hosting, and managed IT solutions.",
  seoTitle: "DoItEasy — Cloud Hosting, VPS & Managed IT in the Gulf",
  seoDescription: "DoItEasy delivers NVMe-powered cloud servers, dedicated hardware and managed IT services across Saudi Arabia, Kuwait and Egypt.",
  seoKeywords: "cloud hosting, VPS, dedicated servers, managed IT, Saudi Arabia",
  ogImage: "",
  metaTitle: "DoItEasy — Cloud Hosting, VPS & Managed IT in the Gulf",
  metaDesc: "DoItEasy delivers NVMe-powered cloud servers, dedicated hardware and managed IT services across Saudi Arabia, Kuwait and Egypt.",
  metaKeywords: "cloud hosting, VPS, dedicated servers, managed IT, Saudi Arabia",
  address: "Riyadh, Kingdom of Saudi Arabia",
  phone: "+966 11 000 0000",
  whatsapp: "+966 55 000 0000",
  supportEmail: "support@doiteasy.net",
  hours: "24 / 7",
  social: {
    facebook: "https://facebook.com/doiteasy",
    x: "https://x.com/doiteasy",
    linkedin: "https://linkedin.com/company/doiteasy",
    instagram: "https://instagram.com/doiteasy",
    youtube: "https://youtube.com/@doiteasy",
  },
  footerText: "Trusted by 10,000+ businesses across the Gulf.",
  copyright: `© ${new Date().getFullYear()} DoItEasy. All rights reserved.`,
  maintenance: false,
  maintenanceMessage: "We'll be back shortly — performing scheduled maintenance.",
  analyticsId: "",
};

export default function CmsGeneral() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<GeneralState>("general", DEFAULTS);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

  const notify = (ok: boolean, msg: string) => {
    setToast({ ok, msg });
    setTimeout(() => setToast(null), 3500);
  };

  const update = <K extends keyof GeneralState>(k: K, v: GeneralState[K]) =>
    setState({ ...state, [k]: v });

  const updateSocial = (k: keyof GeneralState["social"], v: string) =>
    setState({ ...state, social: { ...state.social, [k]: v } });

  const handleSave = async () => {
    // Keep seo* aliased to meta* so both shapes stay in sync
    const merged = {
      ...state,
      seoTitle: state.metaTitle || state.seoTitle,
      seoDescription: state.metaDesc || state.seoDescription,
      seoKeywords: state.metaKeywords || state.seoKeywords,
    };
    setState(merged);
    const r = await save(merged);
    if (r.ok) notify(true, "General settings saved.");
    else notify(false, r.error || "Save failed.");
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<Settings className="w-6 h-6" />}
        title="General Settings"
        description="Site identity, SEO, contact details, and maintenance mode. Changes go live immediately after save."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">
          Loading saved settings…
        </div>
      )}
      {toast && (
        <div className={`mb-4 p-3 rounded-lg text-sm flex items-center gap-2 ${toast.ok ? "bg-emerald-50 border border-emerald-200 text-emerald-800" : "bg-red-50 border border-red-200 text-red-800"}`}>
          {toast.ok ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <SectionCard title="Site Identity">
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="Site Name" required><TextInput value={state.siteName} onChange={(e) => update("siteName", e.target.value)} /></Field>
          <Field label="Tagline"><TextInput value={state.tagline} onChange={(e) => update("tagline", e.target.value)} /></Field>
        </div>
        <Field label="Site Description"><TextArea rows={2} value={state.description} onChange={(e) => update("description", e.target.value)} /></Field>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="SEO Metadata" description="Applied to <head> site-wide via the Site Settings provider.">
        <Field label="Meta Title" hint={`${state.metaTitle.length}/60`}>
          <TextInput value={state.metaTitle} onChange={(e) => update("metaTitle", e.target.value)} />
        </Field>
        <Field label="Meta Description" hint={`${state.metaDesc.length}/160`}>
          <TextArea rows={3} value={state.metaDesc} onChange={(e) => update("metaDesc", e.target.value)} />
        </Field>
        <Field label="Keywords (comma-separated)">
          <TextInput value={state.metaKeywords} onChange={(e) => update("metaKeywords", e.target.value)} />
        </Field>
        <Field label="OG Image URL" hint="Image shown when your site is shared on social media">
          <TextInput value={state.ogImage} onChange={(e) => update("ogImage", e.target.value)} placeholder="https://…" />
        </Field>
        <Field label="Google Analytics ID" hint="Optional">
          <TextInput value={state.analyticsId} onChange={(e) => update("analyticsId", e.target.value)} placeholder="G-XXXXXXXXXX" />
        </Field>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Contact Information">
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="Address"><TextInput value={state.address} onChange={(e) => update("address", e.target.value)} /></Field>
          <Field label="Phone"><TextInput value={state.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
          <Field label="WhatsApp"><TextInput value={state.whatsapp} onChange={(e) => update("whatsapp", e.target.value)} /></Field>
          <Field label="Support Email"><TextInput type="email" value={state.supportEmail} onChange={(e) => update("supportEmail", e.target.value)} /></Field>
          <Field label="Business Hours"><TextInput value={state.hours} onChange={(e) => update("hours", e.target.value)} /></Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Social Media">
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="Facebook"><TextInput value={state.social.facebook} onChange={(e) => updateSocial("facebook", e.target.value)} /></Field>
          <Field label="X (Twitter)"><TextInput value={state.social.x} onChange={(e) => updateSocial("x", e.target.value)} /></Field>
          <Field label="LinkedIn"><TextInput value={state.social.linkedin} onChange={(e) => updateSocial("linkedin", e.target.value)} /></Field>
          <Field label="Instagram"><TextInput value={state.social.instagram} onChange={(e) => updateSocial("instagram", e.target.value)} /></Field>
          <Field label="YouTube"><TextInput value={state.social.youtube} onChange={(e) => updateSocial("youtube", e.target.value)} /></Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Footer">
        <Field label="Footer Text"><TextArea rows={2} value={state.footerText} onChange={(e) => update("footerText", e.target.value)} /></Field>
        <Field label="Copyright"><TextInput value={state.copyright} onChange={(e) => update("copyright", e.target.value)} /></Field>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Maintenance Mode" description="When enabled, the site displays a holding page to visitors.">
        <Toggle label="Enable maintenance mode" checked={state.maintenance} onChange={(v) => update("maintenance", v)} />
        <Field label="Maintenance message">
          <TextArea rows={3} value={state.maintenanceMessage} onChange={(e) => update("maintenanceMessage", e.target.value)} />
        </Field>
      </SectionCard>

      <SaveBar onSave={handleSave} onReset={() => setState(DEFAULTS)} saving={saving} />
    </CmsLayout>
  );
}