"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;
  /** Installateur à modifier ; absent → création. */
  installer?: Installer | null;
  onSuccess: () => void;
}

export function InstallerFormDialog({
  open,
  onOpenChange,
  installer,
  onSuccess,
}: Props) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        {/* Monté uniquement à l'ouverture : l'état initial vient des props au
            montage (pas d'effet → pas de setState dans un useEffect). */}
        {open && (
          <InstallerForm
            key={installer?.id ?? "new"}
            installer={installer}
            onOpenChange={onOpenChange}
            onSuccess={onSuccess}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}

function InstallerForm({
  installer,
  onOpenChange,
  onSuccess,
}: {
  installer?: Installer | null;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}) {
  const t = useT();
  const tr = t.installers.manage;
  const container = useRepositories();
  const isEdit = !!installer;

  const [name, setName] = useState(installer?.name ?? "");
  const [email, setEmail] = useState(installer?.email ?? "");
  const [password, setPassword] = useState("");
  const [passwordConfirm, setPasswordConfirm] = useState("");
  const [localError, setLocalError] = useState<string | null>(null);

  const mutation = useApiMutation(
    () =>
      isEdit
        ? container.installerRepository.update(installer!.id, { name, email })
        : container.installerRepository.create({
            name,
            email,
            password,
            password_confirmation: passwordConfirm,
          }),
    {
      successMessage: isEdit ? tr.updateSuccess : tr.createSuccess,
      onSuccess: () => {
        onOpenChange(false);
        onSuccess();
      },
    }
  );

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

  return (
    <>
      <DialogHeader>
        <DialogTitle>{isEdit ? tr.editTitle : tr.createTitle}</DialogTitle>
        <DialogDescription>
          {isEdit ? tr.editLead : tr.createLead}
        </DialogDescription>
      </DialogHeader>

      <form onSubmit={submit} className="space-y-4">
        <div className="space-y-1.5">
          <Label htmlFor="installer-name">{tr.nameLabel}</Label>
          <Input
            id="installer-name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder={tr.namePlaceholder}
            required
          />
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="installer-email">{tr.emailLabel}</Label>
          <Input
            id="installer-email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder={tr.emailPlaceholder}
            required
          />
        </div>

        {!isEdit && (
          <>
            <div className="space-y-1.5">
              <Label htmlFor="installer-password">{tr.passwordLabel}</Label>
              <Input
                id="installer-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-password-confirm">
                {tr.passwordConfirmLabel}
              </Label>
              <Input
                id="installer-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}>
            {isEdit ? tr.save : tr.create}
          </Button>
        </DialogFooter>
      </form>
    </>
  );
}
