import { useState, type FormEvent } from 'react';
import { Link, useParams } from 'react-router-dom';
import { STOCK_MOVEMENT_KIND_LABELS } from '@siop/shared';
import { useAddStockMovement, usePart } from '@/api/gestion';
import { usePermissions } from '@/auth/use-permissions';
import { Button } from '@/components/ui/button';
import { Modale } from '@/components/ui/modale';

const fmt = new Intl.NumberFormat('fr-FR');

/** Écran 2 des maquettes R3 : les mouvements SONT le stock. */
export default function PageFichePiece() {
  const { id } = useParams<{ id: string }>();
  const { data: piece } = usePart(id);
  const { can } = usePermissions();
  const [modale, setModale] = useState<'ENTRY' | 'ADJUSTMENT' | null>(null);

  if (!piece) return null;

  return (
    <>
      <div className="filajout">
        <Link to="/stock">Stock</Link> / {piece.reference}
      </div>
      <div className="entete-page">
        <h1>{piece.designation}</h1>
        {piece.belowThreshold ? <span className="stock-bas">Sous le seuil</span> : null}
        <div className="actions">
          {can('PARTS', 'edit') ? (
            <>
              <Button onClick={() => setModale('ENTRY')}>Entrée de stock</Button>
              <Button onClick={() => setModale('ADJUSTMENT')}>Ajustement d'inventaire</Button>
            </>
          ) : null}
          {piece.belowThreshold && can('PURCHASE_ORDERS', 'create') ? (
            <Link to={`/achats/nouveau?part=${piece.id}`}>
              <Button variant="prim">Préparer le BC</Button>
            </Link>
          ) : null}
        </div>
      </div>
      <div className="grille-2">
        <div className="carte">
          <h2>Identité</h2>
          <dl className="infos">
            <dt>Référence</dt>
            <dd className="num">{piece.reference}</dd>
            <dt>Stock actuel</dt>
            <dd className="num"><b>{piece.stock}</b> (seuil : {piece.threshold})</dd>
            <dt>Dernier PU</dt>
            <dd className="num">
              {piece.lastUnitPrice != null ? `${fmt.format(piece.lastUnitPrice)} MAD` : 'aucun prix connu'}
            </dd>
            <dt>Fournisseur</dt>
            <dd>
              {piece.supplierName ? (
                <Link to="/tiers" style={{ color: 'var(--primaire)', fontWeight: 600 }}>
                  {piece.supplierName}
                </Link>
              ) : (
                '—'
              )}
            </dd>
            <dt>Compatible</dt>
            <dd>{piece.compatible ?? '—'}</dd>
          </dl>
        </div>
        <div className="carte">
          <h2>
            Mouvements{' '}
            <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--encre-3)' }}>
              — le stock EST cette liste
            </span>
          </h2>
          <div className="table">
            <table>
              <thead>
                <tr><th>Date</th><th>Mouvement</th><th>Qté</th><th>Origine</th></tr>
              </thead>
              <tbody>
                {piece.movements.map((m) => (
                  <tr key={m.id}>
                    <td className="num">
                      {new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium' }).format(new Date(m.createdAt))}
                    </td>
                    <td>
                      <span className={m.quantity > 0 ? 'mvt entree' : 'mvt sortie'}>
                        {m.quantity > 0 ? '+ ' : '− '}
                        {STOCK_MOVEMENT_KIND_LABELS[m.kind]}
                      </span>
                    </td>
                    <td className="num">{Math.abs(m.quantity)}</td>
                    <td>
                      {m.workOrderReference ? (
                        <span className="ref num">{m.workOrderReference}</span>
                      ) : m.purchaseOrderReference ? (
                        <>
                          <span className="ref num">{m.purchaseOrderReference}</span>
                          {m.unitPrice != null ? ` · ${fmt.format(m.unitPrice)} MAD/u` : ''}
                        </>
                      ) : (
                        m.reason ?? '—'
                      )}
                      {m.byName ? ` · ${m.byName}` : ''}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <ModaleMouvement
        pieceId={piece.id}
        kind={modale}
        surFermeture={() => setModale(null)}
      />
    </>
  );
}

function ModaleMouvement({
  pieceId,
  kind,
  surFermeture,
}: {
  pieceId: string;
  kind: 'ENTRY' | 'ADJUSTMENT' | null;
  surFermeture: () => void;
}) {
  const mouvement = useAddStockMovement(pieceId);
  if (!kind) return null;

  const surEnvoi = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const donnees = new FormData(e.currentTarget);
    mouvement.mutate(
      {
        kind,
        quantity: Number(donnees.get('quantity')),
        reason: String(donnees.get('reason') ?? '').trim() || undefined,
      },
      { onSuccess: surFermeture },
    );
  };

  return (
    <Modale
      titre={kind === 'ENTRY' ? 'Entrée de stock' : "Ajustement d'inventaire"}
      ouverte
      surFermeture={surFermeture}
    >
      <form onSubmit={surEnvoi} className="flex flex-col gap-3">
        <div className="champ">
          <label htmlFor="mv-qte">
            Quantité {kind === 'ADJUSTMENT' ? '(± signée)' : ''} *
          </label>
          <input
            id="mv-qte"
            name="quantity"
            type="number"
            required
            min={kind === 'ENTRY' ? 1 : undefined}
            placeholder={kind === 'ENTRY' ? '5' : '-1'}
          />
        </div>
        <div className="champ">
          <label htmlFor="mv-motif">
            Motif {kind === 'ADJUSTMENT' ? '(requis)' : '(optionnel)'}
          </label>
          <input
            id="mv-motif"
            name="reason"
            required={kind === 'ADJUSTMENT'}
            placeholder={kind === 'ADJUSTMENT' ? 'Ex. : pièce endommagée à l’inventaire' : 'Ex. : reprise de stock atelier'}
          />
        </div>
        {mouvement.isError ? <p className="erreur-form">{mouvement.error.message}</p> : null}
        <div className="pied">
          <Button onClick={surFermeture}>Annuler</Button>
          <Button type="submit" variant="prim" disabled={mouvement.isPending}>
            Tracer le mouvement
          </Button>
        </div>
      </form>
    </Modale>
  );
}
