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

type ProfileState = {
  name: string;
  email: string;
  phone: string;
  avatarUrl: string;
  language: string;
  timezone: string;
  notifyEmail: boolean;
  notifySms: boolean;
  notifyPush: boolean;
  mfaEnabled: boolean;
};

const DEFAULTS: ProfileState = {
  name: "Site Administrator",
  email: "admin@doiteasy.net",
  phone: "+966 55 000 0000",
  avatarUrl: "",
  language: "English",
  timezone: "Asia/Riyadh (UTC+3)",
  notifyEmail: true,
  notifySms: false,
  notifyPush: true,
  mfaEnabled: true,
};

export default function CmsProfile() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<ProfileState>("admin_profile", DEFAULTS);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);
  const [currentPass, setCurrentPass] = useState("");
  const [newPass, setNewPass] = useState("");
  const [confirmPass, setConfirmPass] = useState("");
  const [pwMessage, setPwMessage] = useState<string>("");

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

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

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

  const submitPassword = () => {
    if (!currentPass || !newPass) return setPwMessage("All fields are required.");
    if (newPass.length < 10) return setPwMessage("New password must be at least 10 characters.");
    if (newPass !== confirmPass) return setPwMessage("Passwords do not match.");
    setPwMessage("✓ Password updated successfully.");
    setCurrentPass(""); setNewPass(""); setConfirmPass("");
    setTimeout(() => setPwMessage(""), 3000);
  };

  const initials = state.name.split(" ").map((s) => s[0]).join("").slice(0, 2).toUpperCase();

  return (
    <CmsLayout>
      <PageHeader
        icon={<UserCircle className="w-6 h-6" />}
        title="Admin Profile"
        description="Manage your personal account details and preferences."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">Loading profile…</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="Profile Details">
        <div className="flex items-center gap-5 mb-4">
          {state.avatarUrl ? (
            <img src={state.avatarUrl} alt="Avatar" className="w-20 h-20 rounded-full object-cover border-2 border-slate-200" />
          ) : (
            <div className="w-20 h-20 rounded-full bg-gradient-to-br from-[#0b6e3e] to-[#063019] text-white flex items-center justify-center text-2xl font-bold">
              {initials}
            </div>
          )}
          <div className="flex-1">
            <Field label="Avatar URL">
              <TextInput value={state.avatarUrl} onChange={(e) => update("avatarUrl", e.target.value)} placeholder="https://..." />
            </Field>
          </div>
        </div>
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="Full Name" required><TextInput value={state.name} onChange={(e) => update("name", e.target.value)} /></Field>
          <Field label="Email" required><TextInput type="email" value={state.email} onChange={(e) => update("email", e.target.value)} /></Field>
          <Field label="Phone"><TextInput value={state.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
          <Field label="Language">
            <TextInput value={state.language} onChange={(e) => update("language", e.target.value)} />
          </Field>
          <Field label="Timezone">
            <TextInput value={state.timezone} onChange={(e) => update("timezone", e.target.value)} />
          </Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Change Password" description="Use a strong password (10+ chars, with numbers and symbols).">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Current Password"><TextInput type="password" value={currentPass} onChange={(e) => setCurrentPass(e.target.value)} /></Field>
          <Field label="New Password"><TextInput type="password" value={newPass} onChange={(e) => setNewPass(e.target.value)} /></Field>
          <Field label="Confirm New"><TextInput type="password" value={confirmPass} onChange={(e) => setConfirmPass(e.target.value)} /></Field>
        </div>
        <div className="flex items-center justify-between">
          <div className={`text-sm ${pwMessage.startsWith("✓") ? "text-emerald-600" : "text-red-600"}`}>{pwMessage}</div>
          <button onClick={submitPassword} className="px-5 py-2 rounded-lg bg-[#063019] text-white text-sm font-bold hover:bg-[#0b6e3e] transition inline-flex items-center gap-2">
            <KeyRound className="w-4 h-4" /> Update Password
          </button>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Two-Factor Authentication" description="Secure your account with an additional verification step.">
        <Toggle label="Enable MFA on your account" description="Recommended. Uses the methods enabled site-wide under Security." checked={state.mfaEnabled} onChange={(v) => update("mfaEnabled", v)} />
        <div className="mt-3 flex flex-wrap items-center gap-2">
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-emerald-50 border border-emerald-200 text-xs font-semibold text-emerald-700">
            <Smartphone className="w-3.5 h-3.5" /> Google Authenticator linked
          </div>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Notification Preferences">
        <Toggle label="Email notifications" checked={state.notifyEmail} onChange={(v) => update("notifyEmail", v)} />
        <Toggle label="SMS notifications" checked={state.notifySms} onChange={(v) => update("notifySms", v)} />
        <Toggle label="Push notifications" description="Browser / mobile push (if supported)." checked={state.notifyPush} onChange={(v) => update("notifyPush", v)} />
      </SectionCard>

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