import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  WORK_ORDER_STATUS_LABELS,
  WORK_ORDER_STATUSES,
  WORK_ORDER_TYPE_LABELS,
  WORK_ORDER_TYPES,
  type WorkOrderStatus,
  type WorkOrderType,
} from '@siop/shared';
import { useWorkOrders } from '@/api/exploitation';
import { usePermissions } from '@/auth/use-permissions';
import { Avatar } from '@/components/avatar';
import { PrioriteOT, StatutOT } from '@/components/chips-ot';
import { Button } from '@/components/ui/button';
import { formatDateFr } from '@/lib/lieux';

/** Écran 3 validé R0 : table dense « bureau », strie rouge sur l'urgence. */
export default function PageOrdresTravail() {
  const navigate = useNavigate();
  const { data: workOrders } = useWorkOrders();
  const { can } = usePermissions();
  const [statut, setStatut] = useState<'actifs' | 'tous' | WorkOrderStatus>('actifs');
  const [type, setType] = useState<'' | WorkOrderType>('');

  const tous = workOrders ?? [];
  const visibles = tous.filter((w) => {
    if (statut === 'actifs' && (w.status === 'DONE' || w.status === 'CANCELLED')) return false;
    if (statut !== 'actifs' && statut !== 'tous' && w.status !== statut) return false;
    if (type && w.type !== type) return false;
    return true;
  });

  return (
    <>
      <div className="entete-page">
        <h1>Ordres de travail</h1>
        <div className="actions">
          {can('WORK_ORDERS', 'create') ? (
            <Button variant="prim" onClick={() => navigate('/ot/nouveau')}>
              + Nouvel OT
            </Button>
          ) : null}
        </div>
      </div>
      <div className="filtres">
        <select
          aria-label="Filtrer par statut"
          value={statut}
          onChange={(e) => setStatut(e.target.value as typeof statut)}
        >
          <option value="actifs">Statut : actifs</option>
          <option value="tous">Statut : tous</option>
          {WORK_ORDER_STATUSES.map((s) => (
            <option key={s} value={s}>{WORK_ORDER_STATUS_LABELS[s]}</option>
          ))}
        </select>
        <select
          aria-label="Filtrer par type"
          value={type}
          onChange={(e) => setType(e.target.value as '' | WorkOrderType)}
        >
          <option value="">Type : tous</option>
          {WORK_ORDER_TYPES.map((t) => (
            <option key={t} value={t}>{WORK_ORDER_TYPE_LABELS[t]}</option>
          ))}
        </select>
        <span className="num" style={{ color: 'var(--encre-3)', fontSize: 12.5, marginLeft: 'auto' }}>
          {visibles.length} résultats
        </span>
      </div>
      <div className="carte" style={{ padding: 0 }}>
        <div className="table">
          <table>
            <thead>
              <tr>
                <th>N°</th>
                <th>Objet</th>
                <th>Équipement · Site</th>
                <th>Type</th>
                <th>Priorité</th>
                <th>Statut</th>
                <th>Assignés</th>
                <th>Échéance</th>
              </tr>
            </thead>
            <tbody>
              {visibles.map((w) => (
                <tr
                  key={w.id}
                  className={w.priority === 'PERSON_TRAPPED' ? 'ligne-bloque' : undefined}
                  onClick={() => navigate(`/ot/${w.id}`)}
                  style={{ cursor: 'pointer' }}
                >
                  <td className="ref num">{w.reference}</td>
                  <td>{w.priority === 'PERSON_TRAPPED' ? <b>{w.title}</b> : w.title}</td>
                  <td>
                    Asc. {w.assetReference}
                    <span className="sous">{w.siteName}</span>
                  </td>
                  <td>{WORK_ORDER_TYPE_LABELS[w.type]}</td>
                  <td><PrioriteOT priorite={w.priority} /></td>
                  <td><StatutOT statut={w.status} /></td>
                  <td>
                    {w.assignees.length ? (
                      <div className="avatars">
                        {w.assignees.map((a) => (
                          <Avatar key={a.id} initials={a.initials} className="h-6 w-6 text-[10px]" />
                        ))}
                      </div>
                    ) : (
                      '—'
                    )}
                  </td>
                  <td className="num">
                    {w.priority === 'PERSON_TRAPPED' ? <b>immédiat</b> : formatDateFr(w.dueDate)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
