"use client";

import { useState, useTransition } from "react";
import {
  updateClient,
  updateClientPassword,
  deleteClient,
} from "./actions";
import Icon from "@/components/Icon";
import { useDialog } from "@/components/feedback/DialogProvider";

type Initial = {
  name: string;
  email: string;
  company: string;
  siret: string;
  phone: string;
  addressStreet: string;
  addressZip: string;
  addressCity: string;
  addressCountry: string;
  notes: string;
};

export default function EditClientForm({
  userId,
  initial,
  dossierCount,
}: {
  userId: string;
  initial: Initial;
  dossierCount: number;
}) {
  /* ─── État form principal ────────────────────────────────────────── */
  const [form, setForm] = useState<Initial>(initial);
  const [savedAt, setSavedAt] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isSaving, startSaving] = useTransition();

  /* ─── État changement de mot de passe ────────────────────────────── */
  const [newPwd, setNewPwd] = useState("");
  const [pwdMsg, setPwdMsg] = useState<string | null>(null);
  const [pwdError, setPwdError] = useState<string | null>(null);
  const [isPwdSaving, startPwdSaving] = useTransition();

  /* ─── État suppression ───────────────────────────────────────────── */
  const [isDeleting, startDeleting] = useTransition();
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const { confirm, toast } = useDialog();

  function update<K extends keyof Initial>(k: K, v: Initial[K]) {
    setForm((prev) => ({ ...prev, [k]: v }));
    setSavedAt(null);
    setError(null);
  }

  function onSave() {
    setError(null);
    startSaving(async () => {
      const res = await updateClient({
        userId,
        name: form.name,
        email: form.email,
        company: form.company || null,
        siret: form.siret || null,
        phone: form.phone || null,
        addressStreet: form.addressStreet || null,
        addressZip: form.addressZip || null,
        addressCity: form.addressCity || null,
        addressCountry: form.addressCountry || "FR",
        notes: form.notes || null,
      });
      if (res.ok) {
        setSavedAt(new Date());
        toast({
          message: "Modifications enregistrées.",
          variant: "success",
        });
      } else {
        setError(res.error);
      }
    });
  }

  function onChangePassword() {
    setPwdMsg(null);
    setPwdError(null);
    if (newPwd.length < 10) {
      setPwdError("Mot de passe trop court (10 caractères min).");
      return;
    }
    startPwdSaving(async () => {
      const res = await updateClientPassword({ userId, newPassword: newPwd });
      if (res.ok) {
        setPwdMsg(
          "Mot de passe mis à jour. Les sessions actives ont été invalidées."
        );
        setNewPwd("");
        toast({
          message: "Mot de passe mis à jour.",
          variant: "success",
        });
      } else {
        setPwdError(res.error);
      }
    });
  }

  async function onDelete() {
    setDeleteError(null);
    const ok = await confirm({
      title: `Supprimer ${initial.name} ?`,
      body: `Le compte de ${initial.email} sera supprimé définitivement. Cette action est irréversible. Les dossiers et factures éventuellement associés bloqueront la suppression.`,
      confirmLabel: "Supprimer le compte",
      danger: true,
    });
    if (!ok) return;
    startDeleting(async () => {
      try {
        await deleteClient(userId);
        // redirect dans l'action, mais au cas où on stay-here :
      } catch (err) {
        const msg =
          err instanceof Error ? err.message : "Erreur de suppression";
        setDeleteError(msg);
        toast({ message: msg, variant: "error" });
      }
    });
  }

  return (
    <div className="space-y-12">
      {/* ─── Infos générales ───────────────────────────────────────── */}
      <section className="space-y-6">
        <header className="flex items-center justify-between gap-4 flex-wrap">
          <div>
            <h2 className="font-serif text-2xl text-primary">
              Informations
            </h2>
            <p className="text-sm text-on-surface-variant mt-1">
              Coordonnées et adresse de facturation du client.
            </p>
          </div>
          <div className="flex items-center gap-3 text-sm">
            {savedAt && (
              <span className="text-secondary inline-flex items-center gap-1">
                <Icon name="check_circle" className="!text-base" />
                Sauvegardé{" "}
                {savedAt.toLocaleTimeString("fr-FR", {
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </span>
            )}
          </div>
        </header>

        <div className="bg-white border border-outline-variant p-8 space-y-6">
          {error && (
            <p className="text-error text-sm bg-error/5 border border-error/30 px-4 py-2">
              {error}
            </p>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Field label="Nom complet" required>
              <Input
                value={form.name}
                onChange={(v) => update("name", v)}
              />
            </Field>
            <Field label="Email" required>
              <Input
                type="email"
                value={form.email}
                onChange={(v) => update("email", v)}
              />
            </Field>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Field label="Société">
              <Input
                value={form.company}
                onChange={(v) => update("company", v)}
              />
            </Field>
            <Field label="SIRET">
              <Input
                value={form.siret}
                onChange={(v) => update("siret", v)}
                maxLength={14}
              />
            </Field>
          </div>

          <Field label="Téléphone">
            <Input value={form.phone} onChange={(v) => update("phone", v)} />
          </Field>

          <Field label="Adresse">
            <Input
              value={form.addressStreet}
              onChange={(v) => update("addressStreet", v)}
              placeholder="N° et rue"
            />
          </Field>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Field label="Code postal">
              <Input
                value={form.addressZip}
                onChange={(v) => update("addressZip", v)}
              />
            </Field>
            <Field label="Ville">
              <Input
                value={form.addressCity}
                onChange={(v) => update("addressCity", v)}
              />
            </Field>
            <Field label="Pays (ISO 2)">
              <Input
                value={form.addressCountry}
                onChange={(v) => update("addressCountry", v)}
                maxLength={2}
              />
            </Field>
          </div>

          <Field label="Notes internes (admin uniquement)">
            <Textarea
              value={form.notes}
              onChange={(v) => update("notes", v)}
              rows={3}
            />
          </Field>

          <div className="flex justify-end pt-2">
            <button
              type="button"
              onClick={onSave}
              disabled={isSaving}
              className="btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSaving ? "Sauvegarde…" : "Enregistrer"}
            </button>
          </div>
        </div>
      </section>

      {/* ─── Sécurité (mot de passe) ──────────────────────────────── */}
      <section className="space-y-6">
        <header>
          <h2 className="font-serif text-2xl text-primary">
            Mot de passe
          </h2>
          <p className="text-sm text-on-surface-variant mt-1">
            Réinitialise le mot de passe du client. Ses sessions actives seront
            déconnectées immédiatement.
          </p>
        </header>

        <div className="bg-white border border-outline-variant p-8 space-y-4">
          <Field label="Nouveau mot de passe (10 caractères min)">
            <Input
              type="password"
              value={newPwd}
              onChange={setNewPwd}
              autoComplete="new-password"
            />
          </Field>

          {pwdError && (
            <p className="text-error text-sm">{pwdError}</p>
          )}
          {pwdMsg && (
            <p className="text-secondary text-sm inline-flex items-center gap-1">
              <Icon name="check_circle" className="!text-base" />
              {pwdMsg}
            </p>
          )}

          <div className="flex justify-end pt-2">
            <button
              type="button"
              onClick={onChangePassword}
              disabled={isPwdSaving || !newPwd}
              className="btn btn-secondary disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isPwdSaving ? "Mise à jour…" : "Mettre à jour le mot de passe"}
            </button>
          </div>
        </div>
      </section>

      {/* ─── Zone dangereuse ──────────────────────────────────────── */}
      <section className="space-y-6">
        <header>
          <h2 className="font-serif text-2xl text-error">Zone dangereuse</h2>
          <p className="text-sm text-on-surface-variant mt-1">
            La suppression est irréversible. Tous les comptes / sessions /
            fichiers profil seront effacés.
          </p>
        </header>

        <div className="bg-white border border-error/40 p-8 space-y-4">
          {dossierCount > 0 ? (
            <div className="flex items-start gap-3 text-sm text-on-surface-variant">
              <Icon name="info" className="!text-base text-secondary mt-0.5" />
              <p>
                Ce client a <strong>{dossierCount}</strong> dossier
                {dossierCount > 1 ? "s" : ""} associé
                {dossierCount > 1 ? "s" : ""}. La suppression est bloquée tant
                que les dossiers ne sont pas annulés ou archivés.
              </p>
            </div>
          ) : (
            <p className="text-sm text-on-surface-variant">
              Aucun dossier associé. Vous pouvez supprimer ce client.
            </p>
          )}

          {deleteError && (
            <p className="text-error text-sm bg-error/5 border border-error/30 px-4 py-2">
              {deleteError}
            </p>
          )}

          <div className="flex justify-end pt-2">
            <button
              type="button"
              onClick={onDelete}
              disabled={isDeleting || dossierCount > 0}
              className="inline-flex items-center gap-2 px-6 py-3 text-xs uppercase tracking-widest font-serif border border-error text-error hover:bg-error hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-error"
            >
              <Icon name="delete" className="!text-base" />
              {isDeleting ? "Suppression…" : "Supprimer définitivement"}
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ─── Sub-components ─────────────────────────────────────────────────── */

function Field({
  label,
  required,
  children,
}: {
  label: string;
  required?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div>
      <label className="eyebrow !text-on-surface-variant block mb-2">
        {label}
        {required && <span className="ml-1 text-secondary">*</span>}
      </label>
      {children}
    </div>
  );
}

function Input({
  value,
  onChange,
  type = "text",
  placeholder,
  maxLength,
  autoComplete,
}: {
  value: string;
  onChange: (v: string) => void;
  type?: string;
  placeholder?: string;
  maxLength?: number;
  autoComplete?: string;
}) {
  return (
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      maxLength={maxLength}
      autoComplete={autoComplete}
      className="w-full bg-white border border-outline-variant px-3 py-2 body-md focus:border-primary outline-none transition-colors"
    />
  );
}

function Textarea({
  value,
  onChange,
  rows = 3,
}: {
  value: string;
  onChange: (v: string) => void;
  rows?: number;
}) {
  return (
    <textarea
      value={value}
      onChange={(e) => onChange(e.target.value)}
      rows={rows}
      className="w-full bg-white border border-outline-variant px-3 py-2 body-md focus:border-primary outline-none transition-colors resize-y"
    />
  );
}
