"use client";

import { useState } from "react";
import { Spinner } from "@/components/common/Spinner";

export function ChangePasswordForm() {
  const [current, setCurrent] = useState("");
  const [next, setNext] = useState("");
  const [confirm, setConfirm] = useState("");
  const [show, setShow] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [ok, setOk] = useState(false);
  const [busy, setBusy] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setOk(false);
    if (next.trim().length < 8) {
      setError("Nova šifra mora imati najmanje 8 karaktera.");
      return;
    }
    if (next !== confirm) {
      setError("Nove šifre se ne poklapaju.");
      return;
    }
    setBusy(true);
    try {
      const res = await fetch("/api/portal/change-password", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ currentPassword: current, newPassword: next }),
      });
      const data = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };
      if (!res.ok || !data.ok) {
        setError(data.error || "Promena šifre nije uspela. Pokušajte ponovo.");
        setBusy(false);
        return;
      }
      setOk(true);
      setCurrent("");
      setNext("");
      setConfirm("");
      setBusy(false);
    } catch {
      setError("Mrežna greška. Pokušajte ponovo.");
      setBusy(false);
    }
  }

  const inputClass =
    "w-full rounded-xl border border-[#ece7e1] bg-[#faf8f6] px-4 py-3 text-sm text-[#0c1828] placeholder:text-zinc-400 outline-none transition focus:border-[#ffc9ad] focus:bg-white";

  return (
    <div className="rounded-2xl border border-[#ece7e1] bg-white p-5 shadow-[0_18px_44px_-26px_rgba(12,24,40,0.16)] sm:p-6">
      <div className="flex items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[#fff4ef] text-[#c2410c]">
          <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <rect x="3" y="11" width="18" height="11" rx="2" />
            <path d="M7 11V7a5 5 0 0 1 10 0v4" />
          </svg>
        </span>
        <div className="min-w-0">
          <h2 className="text-base font-semibold text-[#0c1828]">Promeni lozinku</h2>
          <p className="mt-1 text-sm leading-relaxed text-zinc-500">
            Postavite novu šifru za pristup kontrolnom panelu. Potrebna je trenutna šifra radi potvrde.
          </p>
        </div>
      </div>

      <form onSubmit={onSubmit} className="mt-5 space-y-3.5">
        <div>
          <label className="mb-1.5 block text-xs font-semibold text-zinc-500">Trenutna šifra</label>
          <input
            type={show ? "text" : "password"}
            value={current}
            onChange={(e) => setCurrent(e.target.value)}
            autoComplete="current-password"
            placeholder="Vaša trenutna šifra"
            className={inputClass}
          />
        </div>
        <div className="grid gap-3.5 sm:grid-cols-2">
          <div>
            <label className="mb-1.5 block text-xs font-semibold text-zinc-500">Nova šifra</label>
            <input
              type={show ? "text" : "password"}
              value={next}
              onChange={(e) => setNext(e.target.value)}
              autoComplete="new-password"
              placeholder="Najmanje 8 karaktera"
              className={inputClass}
            />
          </div>
          <div>
            <label className="mb-1.5 block text-xs font-semibold text-zinc-500">Potvrdi novu šifru</label>
            <input
              type={show ? "text" : "password"}
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              autoComplete="new-password"
              placeholder="Ponovite novu šifru"
              className={inputClass}
            />
          </div>
        </div>

        <label className="flex items-center gap-2 text-xs font-medium text-zinc-500">
          <input
            type="checkbox"
            checked={show}
            onChange={(e) => setShow(e.target.checked)}
            className="h-3.5 w-3.5 rounded border-zinc-300 text-[#c2410c] focus:ring-[#c2410c]"
          />
          Prikaži šifre
        </label>

        {error ? (
          <p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs font-medium text-red-600">
            {error}
          </p>
        ) : null}
        {ok ? (
          <p className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs font-medium text-emerald-700">
            Šifra je uspešno promenjena.
          </p>
        ) : null}

        <div className="pt-1">
          <button
            type="submit"
            disabled={busy}
            className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-[#c2410c] px-5 text-sm font-bold text-white transition hover:bg-[#a8380a] active:scale-[0.99] disabled:opacity-60"
          >
            {busy ? <Spinner className="h-4 w-4" /> : null}
            {busy ? "Čuvam..." : "Sačuvaj novu šifru"}
          </button>
        </div>
      </form>
    </div>
  );
}
