import { useState } from "react";
import { CheckCircle2, KeyRound, Mail, ShieldCheck } from "lucide-react";
import { useServerFn } from "@tanstack/react-start";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import {
  clearResetCode,
  createResetCode,
  getCredentials,
  maskEmail,
  setPassword,
  verifyResetCode,
} from "@/lib/auth";
import { loadDB } from "@/lib/store";
import { sendResetCode } from "@/lib/reset.functions";
import { sendResetCodeViaPhp } from "@/lib/mailer-browser";

export function ForgotPasswordDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
}) {
  const send = useServerFn(sendResetCode);
  const [step, setStep] = useState<"send" | "verify" | "done">("send");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [code, setCode] = useState("");
  const [pass, setPass] = useState("");
  const [confirm, setConfirm] = useState("");

  const email = typeof window !== "undefined" ? loadDB().settings.adminEmail?.trim() ?? "" : "";

  function reset() {
    setStep("send");
    setError("");
    setCode("");
    setPass("");
    setConfirm("");
  }

  async function onSend() {
    setError("");
    if (!email) {
      setError(
        "Hakuna email ya admin iliyowekwa. Ingia kwenye mfumo → Mipangilio → Akaunti ya Admin, weka email yako kwanza.",
      );
      return;
    }
    setBusy(true);
    try {
      const c = createResetCode();
      const payload = { email, code: c, username: getCredentials().user };
      let res: { ok: boolean; reason?: string };
      try {
        res = await send({ data: payload });
      } catch {
        res = { ok: false, reason: "not_configured" };
      }
      // cPanel (static hosting): tumia daraja la PHP moja kwa moja
      if (!res.ok) res = await sendResetCodeViaPhp(payload);
      if (!res.ok) {
        clearResetCode();
        setError(
          res.reason === "not_configured"
            ? "Huduma ya kutuma email bado haijawashwa kwenye mfumo huu. Wasiliana na msimamizi wa mfumo."
            : "Imeshindikana kutuma email. Hakikisha email ni sahihi kisha jaribu tena.",
        );
        return;
      }
      setStep("verify");
    } finally {
      setBusy(false);
    }
  }

  function onVerify(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (!verifyResetCode(code)) {
      setError("Msimbo si sahihi au umeisha muda wake (dakika 15). Omba msimbo mpya.");
      return;
    }
    if (pass.length < 6) {
      setError("Nenosiri jipya liwe na herufi 6 au zaidi.");
      return;
    }
    if (pass !== confirm) {
      setError("Nenosiri jipya na uthibitisho hazifanani.");
      return;
    }
    setPassword(pass);
    clearResetCode();
    setStep("done");
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        onOpenChange(o);
        if (!o) reset();
      }}
    >
      <DialogContent className="rounded-3xl sm:max-w-md">
        <DialogHeader>
          <div className="mx-auto flex size-14 items-center justify-center rounded-full brand-gradient text-primary-foreground">
            {step === "done" ? <CheckCircle2 className="size-7" /> : <KeyRound className="size-7" />}
          </div>
          <DialogTitle className="text-center text-xl font-extrabold">
            {step === "send" && "Umesahau nenosiri?"}
            {step === "verify" && "Weka msimbo na nenosiri jipya"}
            {step === "done" && "Nenosiri limebadilishwa!"}
          </DialogTitle>
          <DialogDescription className="text-center">
            {step === "send" &&
              (email
                ? `Tutakutumia msimbo wa tarakimu 6 kwenye email ${maskEmail(email)}.`
                : "Weka email yako kwanza kwenye Mipangilio ili uweze kurejesha nenosiri.")}
            {step === "verify" && `Msimbo umetumwa kwenda ${maskEmail(email)}. Unaisha baada ya dakika 15.`}
            {step === "done" && "Sasa unaweza kuingia kwa kutumia nenosiri lako jipya."}
          </DialogDescription>
        </DialogHeader>

        {error && (
          <p
            role="alert"
            className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm font-semibold text-destructive"
          >
            {error}
          </p>
        )}

        {step === "send" && (
          <div className="space-y-3">
            <div className="flex items-center gap-3 rounded-2xl border border-border bg-secondary/50 px-4 py-3">
              <Mail className="size-5 text-primary" />
              <div className="min-w-0">
                <p className="text-xs text-muted-foreground">Email ya admin</p>
                <p className="truncate text-sm font-semibold">{email ? maskEmail(email) : "Haijawekwa"}</p>
              </div>
            </div>
            <Button
              onClick={onSend}
              disabled={busy || !email}
              className="h-12 w-full rounded-xl brand-gradient text-base font-bold text-primary-foreground"
            >
              <Mail className="size-4" /> {busy ? "Inatuma..." : "Nitumie msimbo"}
            </Button>
          </div>
        )}

        {step === "verify" && (
          <form onSubmit={onVerify} className="space-y-4">
            <div className="space-y-2">
              <Label>Msimbo wa tarakimu 6</Label>
              <div className="flex justify-center">
                <InputOTP maxLength={6} value={code} onChange={setCode}>
                  <InputOTPGroup>
                    {[0, 1, 2, 3, 4, 5].map((i) => (
                      <InputOTPSlot key={i} index={i} className="size-11 text-lg font-bold" />
                    ))}
                  </InputOTPGroup>
                </InputOTP>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="np">Nenosiri jipya</Label>
              <Input
                id="np"
                type="password"
                value={pass}
                onChange={(e) => setPass(e.target.value)}
                className="h-11 rounded-xl"
                autoComplete="new-password"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="npc">Thibitisha nenosiri jipya</Label>
              <Input
                id="npc"
                type="password"
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                className="h-11 rounded-xl"
                autoComplete="new-password"
              />
            </div>
            <Button
              type="submit"
              className="h-12 w-full rounded-xl brand-gradient text-base font-bold text-primary-foreground"
            >
              <ShieldCheck className="size-4" /> Badilisha nenosiri
            </Button>
            <button
              type="button"
              onClick={onSend}
              disabled={busy}
              className="w-full text-center text-sm font-semibold text-primary hover:underline"
            >
              {busy ? "Inatuma..." : "Sikupokea msimbo? Tuma tena"}
            </button>
          </form>
        )}

        {step === "done" && (
          <Button
            onClick={() => onOpenChange(false)}
            className="h-12 w-full rounded-xl brand-gradient text-base font-bold text-primary-foreground"
          >
            Rudi kuingia
          </Button>
        )}
      </DialogContent>
    </Dialog>
  );
}
