import { useState } from "react";
import { LogIn, Eye, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, TextArea, Select, Toggle, SaveBar } from "./ui";
import { LoginBranding, LOGIN_DEFAULTS, LoginLayout } from "./useBranding";
import { useSiteSettings, useSiteSettingsRead } from "@/hooks/useSiteSettings";
import { Link } from "react-router-dom";

const LAYOUTS: { id: LoginLayout; name: string; desc: string }[] = [
  { id: "split", name: "Split Screen", desc: "Branded hero panel + form on right. Premium SaaS default." },
  { id: "classic", name: "Classic Card", desc: "Centered floating card on a brand-gradient background." },
  { id: "minimal", name: "Minimal", desc: "White background, logo top-left, form only. Clean and fast." },
  { id: "glass", name: "Glass Overlay", desc: "Background video or image with a frosted-glass card on top." },
];

function LayoutThumb({ id, active, primary, accent }: { id: LoginLayout; active: boolean; primary: string; accent: string }) {
  const base = `h-20 w-full rounded-lg border-2 overflow-hidden transition ${active ? "" : "opacity-70 hover:opacity-100"}`;
  const borderColor = active ? primary : "#e2e8f0";
  if (id === "split") {
    return (
      <div className={base} style={{ borderColor }}>
        <div className="flex h-full">
          <div className="w-1/2" style={{ backgroundColor: primary }} />
          <div className="w-1/2 bg-white flex flex-col justify-center p-2 gap-1">
            <div className="h-1.5 w-3/4 bg-slate-200 rounded" />
            <div className="h-1.5 w-1/2 bg-slate-200 rounded" />
            <div className="h-2 w-2/3 rounded mt-1" style={{ backgroundColor: accent }} />
          </div>
        </div>
      </div>
    );
  }
  if (id === "classic") {
    return (
      <div className={base} style={{ borderColor, background: `linear-gradient(135deg, ${primary}, ${primary}80)` }}>
        <div className="h-full flex items-center justify-center">
          <div className="bg-white rounded-md p-2 w-3/4 h-3/4 shadow">
            <div className="h-1.5 w-1/2 bg-slate-200 rounded mb-1" />
            <div className="h-1.5 w-3/4 bg-slate-200 rounded mb-1" />
            <div className="h-2 w-full rounded" style={{ backgroundColor: accent }} />
          </div>
        </div>
      </div>
    );
  }
  if (id === "minimal") {
    return (
      <div className={base + " bg-white"} style={{ borderColor }}>
        <div className="h-full flex flex-col p-2">
          <div className="h-1.5 w-6 bg-slate-300 rounded" />
          <div className="flex-1 flex flex-col justify-center gap-1">
            <div className="h-1.5 w-3/4 bg-slate-200 rounded" />
            <div className="h-1.5 w-1/2 bg-slate-200 rounded" />
            <div className="h-2 w-2/3 rounded mt-1" style={{ backgroundColor: accent }} />
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className={base} style={{ borderColor, background: `linear-gradient(135deg, ${primary}, #334155)` }}>
      <div className="h-full flex items-center justify-center">
        <div className="bg-white/30 backdrop-blur rounded-md p-2 w-3/4 h-3/4 border border-white/40">
          <div className="h-1.5 w-1/2 bg-white/60 rounded mb-1" />
          <div className="h-1.5 w-3/4 bg-white/60 rounded mb-1" />
          <div className="h-2 w-full rounded" style={{ backgroundColor: accent }} />
        </div>
      </div>
    </div>
  );
}

export default function CmsLoginPage() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<LoginBranding>("login_page", LOGIN_DEFAULTS);
  const brand = useSiteSettingsRead<{ primary: string; accent: string }>("branding", { primary: "#0b6e3e", accent: "#f5c400" });
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

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

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

  const handleSave = async () => {
    const r = await save();
    if (r.ok) notify(true, "Login page settings saved.");
    else notify(false, r.error || "Save failed.");
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<LogIn className="w-6 h-6" />}
        title="Login & Auth Pages"
        description="Choose a layout and customize the branded login experience."
      />

      {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="Login Layout"
        description="Pick one of 4 pre-built layouts. The same layout applies to the Register page for consistency."
        actions={
          <Link to="/login" target="_blank" className="px-3 py-1.5 rounded-lg border border-slate-300 text-xs font-semibold inline-flex items-center gap-1 hover:bg-slate-50">
            <Eye className="w-3.5 h-3.5" /> Preview
          </Link>
        }
      >
        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-3">
          {LAYOUTS.map((l) => {
            const active = state.layout === l.id;
            return (
              <button
                key={l.id}
                onClick={() => update("layout", l.id)}
                className={`text-left rounded-xl border-2 p-3 transition ${active ? "shadow-md" : "hover:border-slate-400"}`}
                style={{ borderColor: active ? brand.primary : "#e2e8f0", backgroundColor: active ? `${brand.primary}0d` : "white" }}
              >
                <LayoutThumb id={l.id} active={active} primary={brand.primary} accent={brand.accent} />
                <div className="mt-2 flex items-center gap-2">
                  <span className="text-sm font-bold text-slate-900">{l.name}</span>
                  {active && <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full text-white" style={{ backgroundColor: brand.primary }}>Selected</span>}
                </div>
                <p className="text-[11px] text-slate-500 mt-0.5">{l.desc}</p>
              </button>
            );
          })}
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Welcome Content" description="Text shown on the branded panel of the login/register pages.">
        <Field label="Welcome Title"><TextInput value={state.welcomeTitle} onChange={(e) => update("welcomeTitle", e.target.value)} /></Field>
        <Field label="Welcome Subtitle"><TextArea rows={2} value={state.welcomeSubtitle} onChange={(e) => update("welcomeSubtitle", e.target.value)} /></Field>
        <Field label="Primary CTA Label"><TextInput value={state.ctaLabel} onChange={(e) => update("ctaLabel", e.target.value)} /></Field>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Background Media" description="Used by the Split and Glass layouts.">
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="Background Image URL" hint="Used by Split layout"><TextInput value={state.backgroundUrl} onChange={(e) => update("backgroundUrl", e.target.value)} placeholder="/assets/images/bg.jpg" /></Field>
          <Field label="Background Video URL" hint="Used by Glass layout (optional)"><TextInput value={state.backgroundVideoUrl} onChange={(e) => update("backgroundVideoUrl", e.target.value)} placeholder="/assets/video.mp4" /></Field>
        </div>
        {state.backgroundUrl && (
          <div className="mt-3 rounded-xl overflow-hidden border border-slate-200 h-40 bg-slate-100">
            <img src={state.backgroundUrl} alt="bg" className="w-full h-full object-cover" onError={(e) => ((e.target as HTMLImageElement).style.display = "none")} />
          </div>
        )}
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Form Options">
        <Toggle label="Show Social Login (Google / Microsoft)" checked={state.showSocialLogin} onChange={(v) => update("showSocialLogin", v)} />
        <Toggle label="Show 'Remember Me'" checked={state.showRememberMe} onChange={(v) => update("showRememberMe", v)} />
        <Toggle label="Show 'Forgot Password'" checked={state.showForgotPassword} onChange={(v) => update("showForgotPassword", v)} />
      </SectionCard>

      <Select className="hidden" defaultValue="x"><option value="x">x</option></Select>

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