import { useState } from 'react';
import { Link } from 'react-router-dom';
import {
  PURCHASE_ORDER_STATUS_LABELS,
  type PurchaseOrderDto,
  type PurchaseOrderStatus,
} from '@siop/shared';
import { usePurchaseOrders, useTransitionPurchaseOrder } from '@/api/gestion';
import { usePermissions } from '@/auth/use-permissions';
import { Button } from '@/components/ui/button';

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

const CLASSE_STATUT: Record<PurchaseOrderStatus, string> = {
  DRAFT: 'st brouillon',
  SENT: 'st envoye',
  RECEIVED: 'st recu',
  CANCELLED: 'st annule',
};

export function StatutBC({ statut }: { statut: PurchaseOrderStatus }) {
  return <span className={CLASSE_STATUT[statut]}>{PURCHASE_ORDER_STATUS_LABELS[statut]}</span>;
}

/** Écran 3 des maquettes R3 : liste + panneau — la réception crée les
 *  mouvements d'entrée et fige le PU côté API, en une transaction. */
export default function PageAchats() {
  const { data: bons } = usePurchaseOrders();
  const { can } = usePermissions();
  const [selection, setSelection] = useState<string | null>(null);

  const liste = bons ?? [];
  // sans sélection explicite, le panneau montre le premier BC de la liste
  const bc = liste.find((b) => b.id === selection) ?? liste[0];

  return (
    <>
      <div className="entete-page">
        <h1>Bons de commande</h1>
        <div className="actions">
          {can('PURCHASE_ORDERS', 'create') ? (
            <Link to="/achats/nouveau">
              <Button variant="prim">+ Nouveau BC</Button>
            </Link>
          ) : null}
        </div>
      </div>
      <div className="grille-2" style={{ gridTemplateColumns: '1.1fr 1fr' }}>
        <div className="carte" style={{ padding: 0 }}>
          <div className="table">
            <table>
              <thead>
                <tr><th>N°</th><th>Fournisseur</th><th>Lignes</th><th>Total</th><th>Statut</th></tr>
              </thead>
              <tbody>
                {liste.map((b) => (
                  <tr
                    key={b.id}
                    onClick={() => setSelection(b.id)}
                    style={{
                      cursor: 'pointer',
                      background: bc?.id === b.id ? 'var(--primaire-doux)' : undefined,
                    }}
                  >
                    <td className="ref num">{b.reference}</td>
                    <td>{b.supplierName}</td>
                    <td className="num">{b.lines.length}</td>
                    <td className="num">{fmt.format(b.total)} MAD</td>
                    <td><StatutBC statut={b.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        {bc ? <PanneauBC bc={bc} /> : null}
      </div>
    </>
  );
}

function PanneauBC({ bc }: { bc: PurchaseOrderDto }) {
  const { can } = usePermissions();
  const transition = useTransitionPurchaseOrder();
  const peutEditer = can('PURCHASE_ORDERS', 'edit');

  return (
    <div className="panneau">
      <h2
        style={{
          fontSize: 13, fontWeight: 700, letterSpacing: '0.04em',
          textTransform: 'uppercase', color: 'var(--encre-2)',
        }}
      >
        {bc.reference} — {bc.supplierName} <StatutBC statut={bc.status} />
      </h2>
      <div className="table">
        <table>
          <thead>
            <tr><th>Pièce</th><th>Qté</th><th>PU</th><th>Total</th></tr>
          </thead>
          <tbody>
            {bc.lines.map((l) => (
              <tr key={l.id}>
                <td>{l.designation}</td>
                <td className="num">{l.quantity}</td>
                <td className="num">{fmt.format(l.unitPrice)}</td>
                <td className="num">{fmt.format(l.quantity * l.unitPrice)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="total">
        <span>Total</span>
        <span className="num">{fmt.format(bc.total)} MAD</span>
      </div>
      {peutEditer && (bc.status === 'DRAFT' || bc.status === 'SENT') ? (
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <Button
            variant="dangerLeger"
            disabled={transition.isPending}
            onClick={() => {
              if (window.confirm(`Annuler le ${bc.reference} ?`)) {
                transition.mutate({ id: bc.id, to: 'CANCELLED' });
              }
            }}
          >
            Annuler le BC
          </Button>
          {bc.status === 'DRAFT' ? (
            <Button
              variant="prim"
              disabled={transition.isPending}
              onClick={() => transition.mutate({ id: bc.id, to: 'SENT' })}
            >
              Envoyer au fournisseur
            </Button>
          ) : (
            <Button
              variant="succes"
              disabled={transition.isPending}
              onClick={() => transition.mutate({ id: bc.id, to: 'RECEIVED' })}
            >
              Réceptionner (→ entrées de stock)
            </Button>
          )}
        </div>
      ) : null}
      {transition.isError ? <p className="erreur-form">{transition.error.message}</p> : null}
      <p style={{ fontSize: 12, color: 'var(--encre-3)' }}>
        La réception crée un mouvement d'entrée par ligne et fige le PU — le stock
        remonte, l'alerte s'éteint.
      </p>
    </div>
  );
}
