"use client";

import { FormEvent, useState } from "react";
import { PageHeader } from "@/components/ui/PageHeader";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { AlertMessage } from "@/components/settings/banks/AlertMessage";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import { SETTINGS_PAGE_CONTAINER } from "../constants";
import { validatePassword, clearFieldError } from "@/utils/form-validation";
import { Eye, EyeOff, Loader2, Lock } from "lucide-react";

type FieldKey = "currentPassword" | "newPassword" | "confirmPassword";

export default function AccountSettingsPage() {
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<FieldKey, string>>>({});
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null);

  const clearError = (field: FieldKey) => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaveError(null);
    setSaveSuccess(null);

    const errors: Partial<Record<FieldKey, string>> = {};

    const currentError = validatePassword(currentPassword, "Current password");
    if (currentError) errors.currentPassword = currentError;

    const newError = validatePassword(newPassword, "New password");
    if (newError) errors.newPassword = newError;
    else if (currentPassword && newPassword === currentPassword) {
      errors.newPassword = "New password must be different from current password.";
    }

    if (!confirmPassword) {
      errors.confirmPassword = "Confirm password is required.";
    } else if (newPassword !== confirmPassword) {
      errors.confirmPassword = "Passwords do not match.";
    }

    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    setFieldErrors({});
    setSaving(true);

    try {
      const res = await fetch("/api/account/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          current_password: currentPassword,
          new_password: newPassword,
        }),
      });

      const data = await res.json().catch(() => ({}));

      if (!res.ok) {
        setSaveError(data?.error ?? "Failed to update password. Please try again.");
        return;
      }

      setSaveSuccess("Password updated successfully.");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch {
      setSaveError("Network error. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className={SETTINGS_PAGE_CONTAINER}>
      <PageHeader
        title="Account Settings"
        description="Manage your account security and password."
        breadcrumbs={[...BREADCRUMBS.accountSettings]}
      />

      <AlertMessage error={saveError} success={saveSuccess} />

      <div className="mt-6 max-w-xl">
        <section className="rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="text-base font-semibold text-slate-800 flex items-center gap-2">
            <Lock className="h-4 w-4" />
            Change password
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Enter your current password and choose a new one. Use at least 6 characters.
          </p>

          <form onSubmit={handleSubmit} className="mt-6">
            <FieldGroup>
              <Field>
                <FieldLabel htmlFor="current-password">Current password</FieldLabel>
                <div className="relative">
                  <Input
                    id="current-password"
                    type={showCurrent ? "text" : "password"}
                    value={currentPassword}
                    onChange={(e) => {
                      setCurrentPassword(e.target.value);
                      clearError("currentPassword");
                    }}
                    placeholder="Enter current password"
                    className="pr-9"
                    autoComplete="current-password"
                    aria-invalid={!!fieldErrors.currentPassword}
                  />
                  <button
                    type="button"
                    onClick={() => setShowCurrent((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    aria-label={showCurrent ? "Hide password" : "Show password"}
                  >
                    {showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {fieldErrors.currentPassword && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.currentPassword}
                  </p>
                )}
              </Field>

              <Field>
                <FieldLabel htmlFor="new-password">New password</FieldLabel>
                <div className="relative">
                  <Input
                    id="new-password"
                    type={showNew ? "text" : "password"}
                    value={newPassword}
                    onChange={(e) => {
                      setNewPassword(e.target.value);
                      clearError("newPassword");
                    }}
                    placeholder="Enter new password"
                    className="pr-9"
                    autoComplete="new-password"
                    aria-invalid={!!fieldErrors.newPassword}
                  />
                  <button
                    type="button"
                    onClick={() => setShowNew((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    aria-label={showNew ? "Hide password" : "Show password"}
                  >
                    {showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {fieldErrors.newPassword && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.newPassword}
                  </p>
                )}
              </Field>

              <Field>
                <FieldLabel htmlFor="confirm-password">Confirm new password</FieldLabel>
                <div className="relative">
                  <Input
                    id="confirm-password"
                    type={showConfirm ? "text" : "password"}
                    value={confirmPassword}
                    onChange={(e) => {
                      setConfirmPassword(e.target.value);
                      clearError("confirmPassword");
                    }}
                    placeholder="Confirm new password"
                    className="pr-9"
                    autoComplete="new-password"
                    aria-invalid={!!fieldErrors.confirmPassword}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirm((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    aria-label={showConfirm ? "Hide password" : "Show password"}
                  >
                    {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {fieldErrors.confirmPassword && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.confirmPassword}
                  </p>
                )}
              </Field>

              <div className="pt-2">
                <Button type="submit" disabled={saving}>
                  {saving ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Updating…
                    </>
                  ) : (
                    "Update password"
                  )}
                </Button>
              </div>
            </FieldGroup>
          </form>
        </section>
      </div>
    </div>
  );
}
