"use client";

import { useEffect, useState, ReactNode } from "react";
import { AnimatePresence, motion } from "framer-motion";
import {
  AlertCircle,
  CheckCircle2,
  Info,
  ShieldQuestion,
  FileText,
  Lock,
  Mail,
  Plus,
  Trash2,
  Languages,
} from "lucide-react";
import { PageHeader } from "@/components/ui/PageHeader";
import { Button } from "@/components/ui/Button";
import { TextField, TextAreaField } from "@/components/ui/Field";
import { Skeleton } from "@/components/ui/Skeleton";
import { useAuth } from "@/lib/auth/auth-provider";
import {
  CmsKey,
  CmsPage,
  AboutContent,
  FaqContent,
  LegalContent,
  ContactContent,
  EMPTY_CMS_CONTENT,
  fetchAllCmsPages,
  saveCmsPage,
} from "@/lib/data/cms";
import { cn } from "@/lib/cn";

const TABS: { key: CmsKey; label: string; icon: typeof Info }[] = [
  { key: "about", label: "About SharedNet", icon: Info },
  { key: "faq", label: "FAQ", icon: ShieldQuestion },
  { key: "terms", label: "Terms of Service", icon: FileText },
  { key: "privacy", label: "Privacy Policy", icon: Lock },
  { key: "contact", label: "Contact Us", icon: Mail },
];

export default function CmsManagementPage() {
  const { user } = useAuth();
  const [pages, setPages] = useState<CmsPage[] | null>(null);
  const [activeKey, setActiveKey] = useState<CmsKey>("about");
  const [contentLang, setContentLang] = useState<"en" | "ur">("en");
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    fetchAllCmsPages()
      .then(setPages)
      .catch((err) => setError(err instanceof Error ? err.message : "Couldn't load website content."));
  }, []);

  const active = pages?.find((p) => p.key === activeKey) ?? null;

  function updateActive(updater: (page: CmsPage) => CmsPage) {
    setPages((prev) => prev && prev.map((p) => (p.key === activeKey ? updater(p) : p)));
  }

  // The English content and the Urdu translation share the exact same
  // shape per page (AboutContent, FaqContent, ...), so the same editor
  // components below work for either — this just decides which field on
  // CmsPage a given editor's onChange writes to.
  function updateContent(content: unknown) {
    if (contentLang === "en") {
      updateActive((p) => ({ ...p, content } as CmsPage));
    } else {
      updateActive((p) => ({ ...p, contentUr: content } as CmsPage));
    }
  }

  async function handleSave() {
    if (!active || !user) return;
    setSaving(true);
    setError(null);
    try {
      await saveCmsPage(active);
      setSaved(true);
      setTimeout(() => setSaved(false), 2200);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't save this page.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="relative">
      <PageHeader
        title="Website Content"
        subtitle="Edit the About, FAQ, Terms, Privacy, and Contact pages customers see — changes appear in the app immediately, no code or app update needed"
      />

      <div className="mb-5 flex gap-1.5 overflow-x-auto">
        {TABS.map((tab) => (
          <button
            key={tab.key}
            onClick={() => {
              setActiveKey(tab.key);
              setContentLang("en");
            }}
            className={cn(
              "flex shrink-0 items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium transition-colors",
              activeKey === tab.key
                ? "bg-gold text-ink font-semibold"
                : "panel !shadow-none text-muted hover:text-ink dark:hover:text-paper"
            )}
          >
            <tab.icon size={14} /> {tab.label}
          </button>
        ))}
      </div>

      {error && (
        <div className="mb-4 flex items-center gap-2 rounded-xl bg-danger/10 px-4 py-3 text-sm text-danger">
          <AlertCircle size={16} /> {error}
        </div>
      )}

      <div className="panel p-5">
        {!pages || !active ? (
          <div className="flex flex-col gap-4">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-24 w-full" />
            <Skeleton className="h-24 w-full" />
          </div>
        ) : (
          <>
            <TextField
              label="Page Title"
              value={active.title}
              onChange={(e) => updateActive((p) => ({ ...p, title: e.target.value }))}
            />

            <div className="mt-5 flex items-center gap-2 border-b border-black/[0.06] pb-3 dark:border-white/[0.06]">
              <Languages size={14} className="text-muted" />
              <div className="flex gap-1.5">
                {(
                  [
                    { id: "en" as const, label: "English" },
                    { id: "ur" as const, label: "اردو (optional)" },
                  ]
                ).map((opt) => (
                  <button
                    key={opt.id}
                    onClick={() => setContentLang(opt.id)}
                    className={cn(
                      "rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",
                      contentLang === opt.id
                        ? "bg-gold text-ink"
                        : "text-muted hover:bg-black/[0.03] dark:hover:bg-white/[0.05]"
                    )}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>
            {contentLang === "ur" && (
              <p className="mb-4 mt-3 text-xs text-muted">
                Paste the Urdu translation of this page below. Customers who've selected اردو will
                see this instead of the English version above — anyone still on English is
                unaffected, and if this is left blank they'll see the English content instead.
              </p>
            )}

            <div className="mt-4">
              {active.key === "about" && (
                <AboutEditor
                  content={
                    (contentLang === "en" ? active.content : active.contentUr) ??
                    (EMPTY_CMS_CONTENT.about as AboutContent)
                  }
                  onChange={updateContent}
                />
              )}
              {active.key === "faq" && (
                <FaqEditor
                  content={
                    (contentLang === "en" ? active.content : active.contentUr) ??
                    (EMPTY_CMS_CONTENT.faq as FaqContent)
                  }
                  onChange={updateContent}
                />
              )}
              {(active.key === "terms" || active.key === "privacy") && (
                <LegalEditor
                  content={
                    (contentLang === "en" ? active.content : active.contentUr) ??
                    (EMPTY_CMS_CONTENT[active.key] as LegalContent)
                  }
                  onChange={updateContent}
                />
              )}
              {active.key === "contact" && (
                <ContactEditor
                  content={
                    (contentLang === "en" ? active.content : active.contentUr) ??
                    (EMPTY_CMS_CONTENT.contact as ContactContent)
                  }
                  onChange={updateContent}
                />
              )}
            </div>
          </>
        )}
      </div>

      <div className="mt-6 flex justify-end">
        <Button onClick={handleSave} disabled={saving || !active}>
          {saving ? "Saving…" : "Save Page"}
        </Button>
      </div>

      <AnimatePresence>
        {saved && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className="pointer-events-none fixed bottom-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-2xl bg-success px-4 py-3 text-sm font-semibold text-white shadow-lg"
          >
            <CheckCircle2 size={16} strokeWidth={2.5} />
            Page saved — live in the app now
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function SectionLabel({ children }: { children: string }) {
  return <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">{children}</p>;
}

function RemovableRow({ onRemove, children }: { onRemove: () => void; children: ReactNode }) {
  return (
    <div className="flex items-start gap-2 rounded-xl border border-black/[0.06] p-3.5 dark:border-white/[0.06]">
      <div className="flex-1 flex flex-col gap-3">{children}</div>
      <button
        onClick={onRemove}
        title="Remove"
        className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted hover:bg-danger/10 hover:text-danger"
      >
        <Trash2 size={14} />
      </button>
    </div>
  );
}

function AboutEditor({
  content,
  onChange,
}: {
  content: AboutContent;
  onChange: (c: AboutContent) => void;
}) {
  return (
    <div className="flex flex-col gap-5">
      <TextAreaField
        label="Intro Paragraph"
        rows={3}
        value={content.intro}
        onChange={(e) => onChange({ ...content, intro: e.target.value })}
      />
      <div>
        <SectionLabel>How It Works — Steps</SectionLabel>
        <div className="flex flex-col gap-3">
          {content.steps.map((step, i) => (
            <RemovableRow
              key={i}
              onRemove={() => onChange({ ...content, steps: content.steps.filter((_, j) => j !== i) })}
            >
              <TextField
                label={`Step ${i + 1} Title`}
                value={step.title}
                onChange={(e) => {
                  const steps = [...content.steps];
                  steps[i] = { ...steps[i], title: e.target.value };
                  onChange({ ...content, steps });
                }}
              />
              <TextAreaField
                label="Description"
                rows={2}
                value={step.desc}
                onChange={(e) => {
                  const steps = [...content.steps];
                  steps[i] = { ...steps[i], desc: e.target.value };
                  onChange({ ...content, steps });
                }}
              />
            </RemovableRow>
          ))}
        </div>
        <button
          onClick={() => onChange({ ...content, steps: [...content.steps, { title: "", desc: "" }] })}
          className="mt-3 flex items-center gap-1.5 text-sm font-semibold text-gold-dim dark:text-gold-bright"
        >
          <Plus size={14} /> Add Step
        </button>
      </div>
    </div>
  );
}

function FaqEditor({ content, onChange }: { content: FaqContent; onChange: (c: FaqContent) => void }) {
  return (
    <div>
      <SectionLabel>Questions &amp; Answers</SectionLabel>
      <div className="flex flex-col gap-3">
        {content.items.map((item, i) => (
          <RemovableRow
            key={i}
            onRemove={() => onChange({ items: content.items.filter((_, j) => j !== i) })}
          >
            <TextField
              label="Question"
              value={item.question}
              onChange={(e) => {
                const items = [...content.items];
                items[i] = { ...items[i], question: e.target.value };
                onChange({ items });
              }}
            />
            <TextAreaField
              label="Answer"
              rows={2}
              value={item.answer}
              onChange={(e) => {
                const items = [...content.items];
                items[i] = { ...items[i], answer: e.target.value };
                onChange({ items });
              }}
            />
          </RemovableRow>
        ))}
      </div>
      <button
        onClick={() => onChange({ items: [...content.items, { question: "", answer: "" }] })}
        className="mt-3 flex items-center gap-1.5 text-sm font-semibold text-gold-dim dark:text-gold-bright"
      >
        <Plus size={14} /> Add Question
      </button>
    </div>
  );
}

function LegalEditor({
  content,
  onChange,
}: {
  content: LegalContent;
  onChange: (c: LegalContent) => void;
}) {
  return (
    <div className="flex flex-col gap-5">
      <TextAreaField
        label="Draft Notice (optional — shown as a banner, e.g. while this is still a placeholder)"
        rows={2}
        value={content.notice}
        onChange={(e) => onChange({ ...content, notice: e.target.value })}
      />
      <TextField
        label="Last Updated Line"
        placeholder="e.g. Last updated: 1 July 2026"
        value={content.lastUpdated}
        onChange={(e) => onChange({ ...content, lastUpdated: e.target.value })}
      />
      <div>
        <SectionLabel>Sections</SectionLabel>
        <div className="flex flex-col gap-3">
          {content.sections.map((section, i) => (
            <RemovableRow
              key={i}
              onRemove={() =>
                onChange({ ...content, sections: content.sections.filter((_, j) => j !== i) })
              }
            >
              <TextField
                label="Section Title"
                value={section.title}
                onChange={(e) => {
                  const sections = [...content.sections];
                  sections[i] = { ...sections[i], title: e.target.value };
                  onChange({ ...content, sections });
                }}
              />
              <TextAreaField
                label="Body"
                rows={3}
                value={section.body}
                onChange={(e) => {
                  const sections = [...content.sections];
                  sections[i] = { ...sections[i], body: e.target.value };
                  onChange({ ...content, sections });
                }}
              />
            </RemovableRow>
          ))}
        </div>
        <button
          onClick={() =>
            onChange({ ...content, sections: [...content.sections, { title: "", body: "" }] })
          }
          className="mt-3 flex items-center gap-1.5 text-sm font-semibold text-gold-dim dark:text-gold-bright"
        >
          <Plus size={14} /> Add Section
        </button>
      </div>
    </div>
  );
}

function ContactEditor({
  content,
  onChange,
}: {
  content: ContactContent;
  onChange: (c: ContactContent) => void;
}) {
  return (
    <div className="flex flex-col gap-3">
      <TextAreaField
        label="Intro Text"
        rows={3}
        value={content.body}
        onChange={(e) => onChange({ body: e.target.value })}
      />
      <p className="text-xs text-muted">
        The WhatsApp number, phone, and email shown on this page come from{" "}
        <span className="font-medium">Settings → App Settings</span>, not from here — edit them
        there so the Help page and Contact page always match.
      </p>
    </div>
  );
}
