"use client";

import { useState } from "react";
import { useRepositories } from "@/di/repository-provider";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useT } from "@/shared/i18n/client";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Label } from "@/presentation/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import type { Installer } from "@/domain/entities/installer";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  installer: Installer | null;
  onSuccess: () => void;
}

export function InstallerPasswordDialog({
  open,
  onOpenChange,
  installer,
  onSuccess,
}: Props) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        {/* Monté uniquement à l'ouverture : l'état repart de zéro à chaque ouverture. */}
        {open && installer && (
          <PasswordForm
            key={installer.id}
            installer={installer}
            onOpenChange={onOpenChange}
            onSuccess={onSuccess}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}

function PasswordForm({
  installer,
  onOpenChange,
  onSuccess,
}: {
  installer: Installer;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}) {
  const t = useT();
  const tr = t.installers.manage;
  const container = useRepositories();

  const [password, setPassword] = useState("");
  const [passwordConfirm, setPasswordConfirm] = useState("");
  const [localError, setLocalError] = useState<string | null>(null);

  const mutation = useApiMutation(
    () =>
      container.installerRepository.updatePassword(installer.id, {
        password,
        password_confirmation: passwordConfirm,
      }),
    {
      successMessage: tr.passwordSuccess,
      onSuccess: () => {
        onOpenChange(false);
        onSuccess();
      },
    }
  );

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError(null);
    if (password !== passwordConfirm) {
      setLocalError(tr.passwordMismatch);
      return;
    }
    mutation.mutate(undefined);
  };

  return (
    <>
      <DialogHeader>
        <DialogTitle>{tr.passwordTitle}</DialogTitle>
        <DialogDescription>{tr.passwordLead(installer.name)}</DialogDescription>
      </DialogHeader>

      <form onSubmit={submit} className="space-y-4">
        <div className="space-y-1.5">
          <Label htmlFor="installer-new-password">{tr.newPasswordLabel}</Label>
          <Input
            id="installer-new-password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder={tr.passwordPlaceholder}
            minLength={8}
            required
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="installer-new-password-confirm">
            {tr.passwordConfirmLabel}
          </Label>
          <Input
            id="installer-new-password-confirm"
            type="password"
            value={passwordConfirm}
            onChange={(e) => setPasswordConfirm(e.target.value)}
            minLength={8}
            required
          />
        </div>

        {localError && <p className="text-sm text-destructive">{localError}</p>}

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            {tr.cancel}
          </Button>
          <Button type="submit" disabled={mutation.loading}>
            {tr.save}
          </Button>
        </DialogFooter>
      </form>
    </>
  );
}
