"use client";

import * as React from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { KeyRound, ArrowRight, ShieldAlert } from "lucide-react";
import { FloatingInput } from "@/components/ui/floating-input";
import { Button } from "@/components/ui/button";

export default function ChangePasswordPage() {
  const router = useRouter();

  const [currentPassword, setCurrentPassword] = React.useState("");
  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [pin, setPin] = React.useState("");
  const [confirmPin, setConfirmPin] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (newPassword.length < 8) {
      setError("New password must be at least 8 characters long.");
      return;
    }

    if (newPassword !== confirmPassword) {
      setError("New password and confirmation do not match.");
      return;
    }

    if (currentPassword === newPassword) {
      setError("Your new password must be different from your temporary password.");
      return;
    }

    if (!/^\d{4}$/.test(pin)) {
      setError("Screen lock PIN must consist of exactly 4 numeric digits (0-9).");
      return;
    }

    if (pin !== confirmPin) {
      setError("Screen lock PIN and confirmation PIN do not match.");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/admin/auth/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword, pin, confirmPin }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Failed to update security credentials.");
        return;
      }

      router.push("/admin");
      router.refresh();
    } catch {
      setError("Network error updating credentials. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full max-w-md">
      <div className="rounded-2xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-900">
        <div className="flex flex-col items-center text-center">
          <div className="relative mb-4 flex h-12 w-12 items-center justify-center overflow-hidden rounded-xl bg-neutral-100 dark:bg-neutral-800 border border-neutral-200/60 dark:border-neutral-700/60">
            <Image
              src="/images/quto-logo.webp"
              alt="Quto AI"
              width={40}
              height={40}
              className="object-contain"
              priority
            />
          </div>
          <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
            Establish Permanent Password
          </h1>
          <p className="mt-1 text-xs text-neutral-500">
            Security policy requires updating your initial temporary credentials and configuring your 4-digit screen lock PIN.
          </p>
        </div>

        {error && (
          <div className="mt-6 rounded-xl border border-red-200 bg-red-50 p-3 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-300 flex items-center gap-2">
            <ShieldAlert className="h-4 w-4 shrink-0 text-red-600 dark:text-red-400" />
            <span>{error}</span>
          </div>
        )}

        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <FloatingInput
            id="current-password"
            type="password"
            showPasswordToggle
            required
            autoComplete="current-password"
            name="current-password"
            label="Current / Temporary Password"
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
          />

          <FloatingInput
            id="new-password"
            type="password"
            showPasswordToggle
            required
            minLength={8}
            autoComplete="new-password"
            name="new-password"
            label="New Permanent Password (min 8 chars)"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
          />

          <FloatingInput
            id="confirm-password"
            type="password"
            showPasswordToggle
            required
            minLength={8}
            autoComplete="new-password"
            name="confirm-password"
            label="Confirm Permanent Password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
          />

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
            <FloatingInput
              id="screen-pin"
              type="password"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={4}
              required
              autoComplete="off"
              name="admin-initial-pin"
              data-1p-ignore="true"
              data-lpignore="true"
              data-bwignore="true"
              data-form-type="other"
              label="New 4-Digit PIN"
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, "").slice(0, 4))}
              className="font-mono tracking-widest text-center"
            />

            <FloatingInput
              id="confirm-screen-pin"
              type="password"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={4}
              required
              autoComplete="off"
              name="admin-initial-pin-confirm"
              data-1p-ignore="true"
              data-lpignore="true"
              data-bwignore="true"
              data-form-type="other"
              label="Confirm PIN"
              value={confirmPin}
              onChange={(e) => setConfirmPin(e.target.value.replace(/\D/g, "").slice(0, 4))}
              className="font-mono tracking-widest text-center"
            />
          </div>

          <Button
            type="submit"
            disabled={loading}
            loading={loading}
            className="h-11 w-full gap-2 rounded-xl text-xs font-semibold"
          >
            <span>{loading ? "Updating Security..." : "Save Permanent Credentials"}</span>
            <ArrowRight className="h-3.5 w-3.5" />
          </Button>
        </form>

        <div className="mt-6 flex items-center justify-center gap-1.5 border-t border-neutral-100 dark:border-neutral-800 pt-4 text-[11px] text-neutral-400">
          <KeyRound className="h-3.5 w-3.5 text-neutral-500" />
          <span>Credentials are protected with cryptographic salted scrypt</span>
        </div>
      </div>
    </div>
  );
}
