"use client";

import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";

import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { changeProfilePassword } from "./profile-api";
import { ProfileSuccessDialog } from "./profile-success-dialog";
import type { ChangePasswordPayload } from "./profile-types";

interface ProfilePasswordDialogProps { open: boolean; onOpenChange: (open: boolean) => void; }

export function ProfilePasswordDialog({ open, onOpenChange }: ProfilePasswordDialogProps) {
  const t = useTranslations("dashboard.profile.password");
  const [successOpen, setSuccessOpen] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const form = useForm<ChangePasswordPayload>({ defaultValues: { current_password: "", password: "", password_confirmation: "" } });
  const savePassword = form.handleSubmit(async (fields) => {
    setSubmitError("");
    try { await changeProfilePassword(fields); form.reset(); onOpenChange(false); setSuccessOpen(true); }
    catch (error) { setSubmitError(error instanceof Error ? error.message : t("error")); }
  });
  const isSaving = form.formState.isSubmitting;

  return (
    <>
      <Dialog open={open} onOpenChange={isSaving ? undefined : onOpenChange}>
        <DialogContent className="max-w-[656px] rounded-2xl p-0">
          <DialogHeader className="border-b px-6 py-5"><DialogTitle>{t("title")}</DialogTitle><DialogDescription className="sr-only">{t("description")}</DialogDescription></DialogHeader>
          <form onSubmit={savePassword} className="space-y-4 px-6 pb-6">
            <PasswordField label={t("current")} error={form.formState.errors.current_password?.message}><Input aria-label={t("current")} type="password" {...form.register("current_password", { required: t("required") })} /></PasswordField>
            <PasswordField label={t("new")} error={form.formState.errors.password?.message}><Input aria-label={t("new")} type="password" {...form.register("password", { required: t("required"), minLength: { value: 8, message: t("minimum") } })} /></PasswordField>
            <PasswordField label={t("confirmNew")} error={form.formState.errors.password_confirmation?.message}><Input aria-label={t("confirmNew")} type="password" {...form.register("password_confirmation", { required: t("required"), validate: (confirmation) => confirmation === form.getValues("password") || t("mismatch") })} /></PasswordField>
            {submitError ? <p role="alert" className="text-sm text-destructive">{submitError}</p> : null}
            <DialogFooter className="border-t pt-5 sm:justify-start">
              <Button type="submit" className="h-12 min-w-32 rounded-xl" disabled={isSaving}>{isSaving ? <Loader2 className="animate-spin" /> : null}{t("save")}</Button>
              <Button type="button" variant="outline" className="h-12 min-w-32 rounded-xl" disabled={isSaving} onClick={() => onOpenChange(false)}>{t("cancel")}</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
      <ProfileSuccessDialog open={successOpen} title={t("successTitle")} description={t("successDescription")} closeLabel={t("close")} onOpenChange={setSuccessOpen} />
    </>
  );
}

function PasswordField({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return <div className="space-y-2"><Label>{label}</Label>{children}{error ? <p className="text-sm text-destructive">{error}</p> : null}</div>;
}
