import { useState } from "react";
import { UserPlus, Plus, Trash2, Check, X, Search, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select, Toggle, SaveBar, Badge } from "./ui";
import { RegistrationConfig, REGISTRATION_DEFAULTS, PendingRegistration, DEFAULT_PENDING } from "./useBranding";
import { useSiteSettings } from "@/hooks/useSiteSettings";

type PendingState = { items: PendingRegistration[] };

export default function CmsRegistration() {
  const { value: cfg, setValue: setCfg, save: saveCfg, loading, saving } = useSiteSettings<RegistrationConfig>("registration", REGISTRATION_DEFAULTS);
  const { value: pendingBox, setValue: setPendingBox, save: savePendingBox } = useSiteSettings<PendingState>("pending_registrations", { items: DEFAULT_PENDING });
  const pending = pendingBox.items ?? [];

  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);
  const [newAllow, setNewAllow] = useState("");
  const [newBlock, setNewBlock] = useState("");
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<"all" | "pending" | "approved" | "rejected">("all");

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

  const update = <K extends keyof RegistrationConfig>(k: K, v: RegistrationConfig[K]) =>
    setCfg({ ...cfg, [k]: v });

  const handleSaveCfg = async () => {
    const r = await saveCfg();
    if (r.ok) notify(true, "Registration policy saved.");
    else notify(false, r.error || "Save failed.");
  };

  const savePending = async (next: PendingRegistration[]) => {
    const blob = { items: next };
    setPendingBox(blob);
    await savePendingBox(blob);
  };

  const setStatus = (id: string, status: PendingRegistration["status"]) => {
    savePending(pending.map((p) => (p.id === id ? { ...p, status } : p)));
  };
  const removeReg = (id: string) => savePending(pending.filter((p) => p.id !== id));

  const filtered = pending.filter((p) => {
    const matchSearch = (p.name + p.email + p.company + p.country + p.plan).toLowerCase().includes(search.toLowerCase());
    const matchFilter = filter === "all" || p.status === filter;
    return matchSearch && matchFilter;
  });

  const counts = {
    pending: pending.filter((p) => p.status === "pending").length,
    approved: pending.filter((p) => p.status === "approved").length,
    rejected: pending.filter((p) => p.status === "rejected").length,
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<UserPlus className="w-6 h-6" />}
        title="Registration"
        description="Control how new users sign up and review pending accounts."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">
          Loading saved policy…
        </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="Registration Status">
        <Toggle label="Accept new registrations" description="When off, the /register page shows a closed notice." checked={cfg.open} onChange={(v) => update("open", v)} />
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Required Fields" description="Choose which information applicants must provide.">
        <Toggle label="Phone number" checked={cfg.requirePhone} onChange={(v) => update("requirePhone", v)} />
        <Toggle label="Company name" checked={cfg.requireCompany} onChange={(v) => update("requireCompany", v)} />
        <Toggle label="Country" checked={cfg.requireCountry} onChange={(v) => update("requireCountry", v)} />
        <Toggle label="Plan selection" description="Users must choose a pricing plan during signup." checked={cfg.requirePlanSelection} onChange={(v) => update("requirePlanSelection", v)} />
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Verification & Security">
        <Toggle label="Require email verification" checked={cfg.requireEmailVerify} onChange={(v) => update("requireEmailVerify", v)} />
        <Toggle label="Show CAPTCHA on signup" checked={cfg.requireCaptcha} onChange={(v) => update("requireCaptcha", v)} />
        <div className="grid md:grid-cols-2 gap-5 pt-2">
          <Field label="Default role for new users">
            <Select value={cfg.defaultRole} onChange={(e) => update("defaultRole", e.target.value as RegistrationConfig["defaultRole"])}>
              <option value="client">client</option>
              <option value="support">support</option>
              <option value="billing">billing</option>
            </Select>
          </Field>
          <Field label="Approval workflow">
            <Select value={cfg.approval} onChange={(e) => update("approval", e.target.value as RegistrationConfig["approval"])}>
              <option value="auto">Auto-approve (instant access)</option>
              <option value="manual">Manual approval by admin</option>
            </Select>
          </Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Email Domain Rules" description="Optionally restrict which email domains can register.">
        <div className="grid md:grid-cols-2 gap-5">
          <div>
            <div className="text-sm font-semibold text-slate-800 mb-2">Allowed Domains</div>
            <div className="text-[11px] text-slate-500 mb-2">If empty, all domains are allowed (unless blocked below).</div>
            <div className="flex gap-2 mb-2">
              <TextInput placeholder="e.g. company.com" value={newAllow} onChange={(e) => setNewAllow(e.target.value)} />
              <button
                onClick={() => { if (newAllow.trim()) { update("allowedDomains", [...cfg.allowedDomains, newAllow.trim()]); setNewAllow(""); } }}
                className="px-3 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#0a8048] inline-flex items-center gap-1"
              ><Plus className="w-4 h-4" />Add</button>
            </div>
            <div className="space-y-1">
              {cfg.allowedDomains.length === 0 && <div className="text-xs text-slate-500">No domain restrictions.</div>}
              {cfg.allowedDomains.map((d) => (
                <div key={d} className="flex items-center justify-between bg-emerald-50 border border-emerald-200 rounded-lg px-3 py-2 text-sm">
                  <span className="font-mono">{d}</span>
                  <button onClick={() => update("allowedDomains", cfg.allowedDomains.filter((x) => x !== d))} className="text-emerald-400 hover:text-red-600"><Trash2 className="w-4 h-4" /></button>
                </div>
              ))}
            </div>
          </div>
          <div>
            <div className="text-sm font-semibold text-slate-800 mb-2">Blocked Domains</div>
            <div className="text-[11px] text-slate-500 mb-2">Disposable email services, competitors, etc.</div>
            <div className="flex gap-2 mb-2">
              <TextInput placeholder="e.g. mailinator.com" value={newBlock} onChange={(e) => setNewBlock(e.target.value)} />
              <button
                onClick={() => { if (newBlock.trim()) { update("blockedDomains", [...cfg.blockedDomains, newBlock.trim()]); setNewBlock(""); } }}
                className="px-3 rounded-lg bg-red-600 text-white text-sm font-semibold hover:bg-red-700 inline-flex items-center gap-1"
              ><Plus className="w-4 h-4" />Add</button>
            </div>
            <div className="space-y-1">
              {cfg.blockedDomains.length === 0 && <div className="text-xs text-slate-500">No blocked domains.</div>}
              {cfg.blockedDomains.map((d) => (
                <div key={d} className="flex items-center justify-between bg-red-50 border border-red-200 rounded-lg px-3 py-2 text-sm">
                  <span className="font-mono">{d}</span>
                  <button onClick={() => update("blockedDomains", cfg.blockedDomains.filter((x) => x !== d))} className="text-red-400 hover:text-red-700"><Trash2 className="w-4 h-4" /></button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Legal & Messaging">
        <Field label="Terms of Service URL"><TextInput value={cfg.termsUrl} onChange={(e) => update("termsUrl", e.target.value)} /></Field>
        <Field label="Welcome message (sent after approval)"><TextInput value={cfg.welcomeMessage} onChange={(e) => update("welcomeMessage", e.target.value)} /></Field>
      </SectionCard>

      <SaveBar onSave={handleSaveCfg} onReset={() => setCfg(REGISTRATION_DEFAULTS)} saving={saving} />

      <div className="h-10" />
      <SectionCard
        title="Pending Registrations"
        description={`${counts.pending} pending · ${counts.approved} approved · ${counts.rejected} rejected`}
      >
        <div className="flex flex-wrap items-center gap-3 mb-3">
          <div className="relative flex-1 min-w-[200px]">
            <Search className="w-4 h-4 absolute left-3 top-3 text-slate-400" />
            <TextInput placeholder="Search name, email, plan…" value={search} onChange={(e) => setSearch(e.target.value)} className="!pl-9" />
          </div>
          <Select value={filter} onChange={(e) => setFilter(e.target.value as typeof filter)} className="!w-auto">
            <option value="all">All statuses</option>
            <option value="pending">Pending</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
          </Select>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[720px]">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-slate-500 border-b border-slate-200">
                <th className="py-2 pr-3">Applicant</th>
                <th className="py-2 pr-3">Company / Country</th>
                <th className="py-2 pr-3">Plan</th>
                <th className="py-2 pr-3">Status</th>
                <th className="py-2 pr-3">Submitted</th>
                <th className="py-2 pr-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p) => (
                <tr key={p.id} className="border-b border-slate-100 hover:bg-slate-50">
                  <td className="py-3 pr-3">
                    <div className="font-semibold text-slate-900">{p.name}</div>
                    <div className="text-xs text-slate-500">{p.email}</div>
                  </td>
                  <td className="py-3 pr-3 text-slate-700">
                    <div>{p.company}</div>
                    <div className="text-xs text-slate-500">{p.country}</div>
                  </td>
                  <td className="py-3 pr-3 text-slate-700">{p.plan}</td>
                  <td className="py-3 pr-3">
                    <Badge tone={p.status === "approved" ? "green" : p.status === "rejected" ? "red" : "yellow"}>
                      {p.status}
                    </Badge>
                  </td>
                  <td className="py-3 pr-3 text-xs text-slate-500">{p.submittedAt}</td>
                  <td className="py-3 pr-3 text-right">
                    <div className="inline-flex items-center gap-1">
                      {p.status !== "approved" && (
                        <button onClick={() => setStatus(p.id, "approved")} className="px-2 py-1 rounded border border-emerald-300 text-emerald-700 text-xs font-semibold hover:bg-emerald-50 inline-flex items-center gap-1">
                          <Check className="w-3 h-3" /> Approve
                        </button>
                      )}
                      {p.status !== "rejected" && (
                        <button onClick={() => setStatus(p.id, "rejected")} className="px-2 py-1 rounded border border-red-300 text-red-700 text-xs font-semibold hover:bg-red-50 inline-flex items-center gap-1">
                          <X className="w-3 h-3" /> Reject
                        </button>
                      )}
                      <button onClick={() => removeReg(p.id)} className="p-1.5 rounded text-slate-400 hover:text-red-600 hover:bg-red-50">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={6} className="py-8 text-center text-slate-500">No registrations match your filters.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </CmsLayout>
  );
}