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

type SecurityState = {
  mfaRequired: boolean;
  mfaSms: boolean;
  mfaEmail: boolean;
  mfaGoogle: boolean;
  mfaMicrosoft: boolean;
  passMin: number;
  passUpper: boolean;
  passNumber: boolean;
  passSymbol: boolean;
  passExpiryDays: number;
  sessionTimeoutMin: number;
  maxLoginAttempts: number;
  lockoutMin: number;
  ipWhitelist: string[];
  ipBlacklist: string[];
};

const DEFAULTS: SecurityState = {
  mfaRequired: true,
  mfaSms: true,
  mfaEmail: true,
  mfaGoogle: true,
  mfaMicrosoft: true,
  passMin: 10,
  passUpper: true,
  passNumber: true,
  passSymbol: true,
  passExpiryDays: 90,
  sessionTimeoutMin: 30,
  maxLoginAttempts: 5,
  lockoutMin: 15,
  ipWhitelist: [],
  ipBlacklist: ["203.0.113.45"],
};

const MOCK_AUDIT = [
  { who: "admin@doiteasy.net", what: "Changed SMTP password", when: "2h ago", ip: "41.65.12.9" },
  { who: "support@doiteasy.net", what: "Added user 'omar.k'", when: "5h ago", ip: "41.65.12.3" },
  { who: "admin@doiteasy.net", what: "Enabled MFA policy", when: "Yesterday", ip: "41.65.12.9" },
  { who: "system", what: "Automatic backup completed", when: "Yesterday", ip: "—" },
];

export default function CmsSecurity() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<SecurityState>("security", DEFAULTS);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);
  const [newIp, setNewIp] = useState("");
  const [newBlackIp, setNewBlackIp] = useState("");

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

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

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

  return (
    <CmsLayout>
      <PageHeader
        icon={<ShieldCheck className="w-6 h-6" />}
        title="Security"
        description="Protect accounts with MFA, password policy, and access controls."
      />

      {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="Multi-Factor Authentication" description="Enable the methods your users can choose for login verification.">
        <Toggle label="Require MFA for all admin accounts" description="Users without MFA will be forced to enroll on next login." checked={state.mfaRequired} onChange={(v) => update("mfaRequired", v)} />
        <Toggle label="SMS OTP" description="Send one-time codes by SMS. Requires SMS gateway." checked={state.mfaSms} onChange={(v) => update("mfaSms", v)} />
        <Toggle label="Email OTP" description="Send one-time codes to the user's email." checked={state.mfaEmail} onChange={(v) => update("mfaEmail", v)} />
        <Toggle label="Google Authenticator" description="TOTP-based app authentication." checked={state.mfaGoogle} onChange={(v) => update("mfaGoogle", v)} />
        <Toggle label="Microsoft Authenticator" description="TOTP / push-based app authentication." checked={state.mfaMicrosoft} onChange={(v) => update("mfaMicrosoft", v)} />
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Password Policy" description="Rules enforced at signup and on password change.">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Minimum Length">
            <TextInput type="number" min={6} max={64} value={state.passMin} onChange={(e) => update("passMin", Number(e.target.value))} />
          </Field>
          <Field label="Expiry (days)" hint="0 = never">
            <TextInput type="number" min={0} max={365} value={state.passExpiryDays} onChange={(e) => update("passExpiryDays", Number(e.target.value))} />
          </Field>
          <div />
        </div>
        <Toggle label="Require uppercase letter" checked={state.passUpper} onChange={(v) => update("passUpper", v)} />
        <Toggle label="Require number" checked={state.passNumber} onChange={(v) => update("passNumber", v)} />
        <Toggle label="Require symbol (!@#$…)" checked={state.passSymbol} onChange={(v) => update("passSymbol", v)} />
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Sessions & Lockouts">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Session timeout (min)">
            <TextInput type="number" min={5} max={1440} value={state.sessionTimeoutMin} onChange={(e) => update("sessionTimeoutMin", Number(e.target.value))} />
          </Field>
          <Field label="Max login attempts">
            <TextInput type="number" min={3} max={20} value={state.maxLoginAttempts} onChange={(e) => update("maxLoginAttempts", Number(e.target.value))} />
          </Field>
          <Field label="Lockout duration (min)">
            <TextInput type="number" min={1} max={120} value={state.lockoutMin} onChange={(e) => update("lockoutMin", Number(e.target.value))} />
          </Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="IP Access Control" description="Restrict or block specific IPs for admin access.">
        <div className="grid md:grid-cols-2 gap-5">
          <div>
            <div className="text-sm font-semibold text-slate-800 mb-2">Whitelist</div>
            <div className="flex gap-2 mb-2">
              <TextInput placeholder="e.g. 192.168.1.0/24" value={newIp} onChange={(e) => setNewIp(e.target.value)} />
              <button
                onClick={() => { if (newIp.trim()) { update("ipWhitelist", [...state.ipWhitelist, newIp.trim()]); setNewIp(""); } }}
                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">
              {state.ipWhitelist.length === 0 && <div className="text-xs text-slate-500">No whitelisted IPs.</div>}
              {state.ipWhitelist.map((ip) => (
                <div key={ip} className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm">
                  <span className="font-mono">{ip}</span>
                  <button onClick={() => update("ipWhitelist", state.ipWhitelist.filter((x) => x !== ip))} className="text-slate-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">Blacklist</div>
            <div className="flex gap-2 mb-2">
              <TextInput placeholder="e.g. 203.0.113.45" value={newBlackIp} onChange={(e) => setNewBlackIp(e.target.value)} />
              <button
                onClick={() => { if (newBlackIp.trim()) { update("ipBlacklist", [...state.ipBlacklist, newBlackIp.trim()]); setNewBlackIp(""); } }}
                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">
              {state.ipBlacklist.length === 0 && <div className="text-xs text-slate-500">No blacklisted IPs.</div>}
              {state.ipBlacklist.map((ip) => (
                <div key={ip} 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">{ip}</span>
                  <button onClick={() => update("ipBlacklist", state.ipBlacklist.filter((x) => x !== ip))} 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="Audit Log" description="Recent security events (read-only).">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-slate-500 border-b border-slate-200">
                <th className="py-2 pr-3">User</th>
                <th className="py-2 pr-3">Action</th>
                <th className="py-2 pr-3">IP</th>
                <th className="py-2 pr-3">When</th>
              </tr>
            </thead>
            <tbody>
              {MOCK_AUDIT.map((a, i) => (
                <tr key={i} className="border-b border-slate-100">
                  <td className="py-2.5 pr-3 font-semibold text-slate-800">{a.who}</td>
                  <td className="py-2.5 pr-3 text-slate-700">{a.what}</td>
                  <td className="py-2.5 pr-3 text-slate-500 font-mono text-xs">{a.ip}</td>
                  <td className="py-2.5 pr-3"><Badge>{a.when}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>

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