import { useState, type FormEvent } from 'react';
import { PARTNER_KIND_LABELS, PARTNER_KINDS } from '@siop/shared';
import { useCreatePartner, usePartners } from '@/api/gestion';
import { usePermissions } from '@/auth/use-permissions';
import { Button } from '@/components/ui/button';
import { Modale } from '@/components/ui/modale';

/** Écran 6 des maquettes R3 : annuaire minimal — pas un CRM. */
export default function PageTiers() {
  const { data: partners } = usePartners();
  const { can } = usePermissions();
  const [modale, setModale] = useState(false);

  return (
    <>
      <div className="entete-page">
        <h1>Tiers</h1>
        <div className="actions">
          {can('PURCHASE_ORDERS', 'create') ? (
            <Button variant="prim" onClick={() => setModale(true)}>
              + Nouveau tiers
            </Button>
          ) : null}
        </div>
      </div>
      <div className="carte" style={{ padding: 0 }}>
        <div className="table">
          <table>
            <thead>
              <tr><th>Nom</th><th>Type</th><th>Contact</th><th>Rattachements</th></tr>
            </thead>
            <tbody>
              {(partners ?? []).map((p) => (
                <tr key={p.id} style={!p.isActive ? { color: 'var(--encre-3)' } : undefined}>
                  <td>
                    <b>{p.name}</b>
                    {p.city ? <span className="sous">{p.city}</span> : null}
                  </td>
                  <td>{PARTNER_KIND_LABELS[p.kind]}</td>
                  <td>
                    {p.contactName}
                    {p.contactName && p.phone ? ' · ' : null}
                    {p.phone ? <span className="num">{p.phone}</span> : null}
                    {!p.contactName && !p.phone && !p.email ? '—' : null}
                    {p.email ? <span className="sous">{p.email}</span> : null}
                  </td>
                  <td className="num">
                    {p.kind === 'SUPPLIER'
                      ? p.openOrders
                        ? `${p.openOrders} BC en cours`
                        : '—'
                      : p.siteNames.length
                        ? p.siteNames.join(' · ')
                        : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <NouveauTiers ouverte={modale} surFermeture={setModale} />
    </>
  );
}

function NouveauTiers({
  ouverte,
  surFermeture,
}: {
  ouverte: boolean;
  surFermeture: (o: boolean) => void;
}) {
  const creation = useCreatePartner();
  const surEnvoi = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const donnees = new FormData(e.currentTarget);
    const champ = (n: string) => String(donnees.get(n) ?? '').trim();
    creation.mutate(
      {
        name: champ('name'),
        kind: champ('kind') as 'SUPPLIER' | 'CLIENT',
        contactName: champ('contactName') || undefined,
        phone: champ('phone') || undefined,
        email: champ('email') || undefined,
        city: champ('city') || undefined,
      },
      { onSuccess: () => surFermeture(false) },
    );
  };

  return (
    <Modale titre="Nouveau tiers" ouverte={ouverte} surFermeture={surFermeture}>
      <form onSubmit={surEnvoi} className="flex flex-col gap-3">
        <div className="champ">
          <label htmlFor="nt-nom">Nom *</label>
          <input id="nt-nom" name="name" required placeholder="Ex. : Ascentech Maroc" />
        </div>
        <div className="form-grille">
          <div className="champ">
            <label htmlFor="nt-type">Type *</label>
            <select id="nt-type" name="kind" required defaultValue="SUPPLIER">
              {PARTNER_KINDS.map((k) => (
                <option key={k} value={k}>{PARTNER_KIND_LABELS[k]}</option>
              ))}
            </select>
          </div>
          <div className="champ">
            <label htmlFor="nt-ville">Ville</label>
            <input id="nt-ville" name="city" />
          </div>
          <div className="champ">
            <label htmlFor="nt-contact">Contact</label>
            <input id="nt-contact" name="contactName" />
          </div>
          <div className="champ">
            <label htmlFor="nt-tel">Téléphone</label>
            <input id="nt-tel" name="phone" />
          </div>
          <div className="champ pleine-l">
            <label htmlFor="nt-email">Email</label>
            <input id="nt-email" name="email" type="email" />
          </div>
        </div>
        {creation.isError ? <p className="erreur-form">{creation.error.message}</p> : null}
        <div className="pied">
          <Button onClick={() => surFermeture(false)}>Annuler</Button>
          <Button type="submit" variant="prim" disabled={creation.isPending}>Créer</Button>
        </div>
      </form>
    </Modale>
  );
}
