import { useState, type FormEvent } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import {
  WORK_ORDER_PRIORITY_LABELS,
  WORK_ORDER_TYPE_LABELS,
  WORK_ORDER_TYPES,
  type WorkOrderPriority,
  type WorkOrderType,
} from '@siop/shared';
import { useCreateWorkOrder } from '@/api/exploitation';
import { useAssets } from '@/api/referentiel';
import { useUsers } from '@/api/referentiel';
import { Button } from '@/components/ui/button';

/** Écran 2 des maquettes R2 : l'OT manuel — « personne bloquée » est un
 *  choix EXPLICITE (interrupteur) qui déclenche l'urgence partout. */
export default function PageNouvelOT() {
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const { data: assets } = useAssets();
  const { data: users } = useUsers();
  const creation = useCreateWorkOrder();
  const [personneBloquee, setPersonneBloquee] = useState(false);

  const techniciens = (users ?? []).filter(
    (u) => u.status === 'active' && u.role.name.startsWith('Technicien'),
  );

  const surEnvoi = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const donnees = new FormData(e.currentTarget);
    const champ = (n: string) => String(donnees.get(n) ?? '').trim();
    const assigne = champ('assigneeId');
    creation.mutate(
      {
        title: champ('title'),
        description: champ('description') || undefined,
        type: champ('type') as WorkOrderType,
        priority: personneBloquee
          ? 'PERSON_TRAPPED'
          : (champ('priority') as WorkOrderPriority),
        assetId: champ('assetId'),
        dueDate: champ('dueDate') ? new Date(champ('dueDate')).toISOString() : undefined,
        assigneeIds: assigne ? [assigne] : undefined,
      },
      { onSuccess: (ot) => navigate(`/ot/${ot.id}`) },
    );
  };

  return (
    <div style={{ maxWidth: 760 }} className="flex flex-col gap-4">
      <div className="filajout">
        <Link to="/ot">Ordres de travail</Link> / Nouvel OT
      </div>
      <div className="entete-page"><h1>Nouvel ordre de travail</h1></div>
      <form onSubmit={surEnvoi} className="flex flex-col gap-4">
        <div className="carte">
          <div className="form-grille">
            <div className="champ pleine-l">
              <label htmlFor="not-titre">Objet *</label>
              <input id="not-titre" name="title" required placeholder="Ex. : Remplacement contact de porte" />
            </div>
            <div className="champ">
              <label htmlFor="not-type">Type *</label>
              <select id="not-type" name="type" required defaultValue="CORRECTIVE">
                {WORK_ORDER_TYPES.map((t) => (
                  <option key={t} value={t}>{WORK_ORDER_TYPE_LABELS[t]}</option>
                ))}
              </select>
            </div>
            <div className="champ">
              <label htmlFor="not-asset">Équipement *</label>
              <select id="not-asset" name="assetId" required defaultValue={params.get('asset') ?? ''}>
                <option value="" disabled>Choisir…</option>
                {(assets ?? []).map((a) => (
                  <option key={a.id} value={a.id}>
                    {a.reference} — {a.siteName}
                  </option>
                ))}
              </select>
            </div>
            <div className="champ">
              <label htmlFor="not-prio">Priorité *</label>
              <select id="not-prio" name="priority" defaultValue="MEDIUM" disabled={personneBloquee}>
                {(['NONE', 'LOW', 'MEDIUM', 'HIGH'] as const).map((p) => (
                  <option key={p} value={p}>{WORK_ORDER_PRIORITY_LABELS[p]}</option>
                ))}
              </select>
            </div>
            <div className="champ">
              <label htmlFor="not-echeance">Échéance</label>
              <input id="not-echeance" name="dueDate" type="date" />
            </div>
            <div className="champ pleine-l">
              <label htmlFor="not-desc">Description</label>
              <input id="not-desc" name="description" placeholder="Constat, contexte, consignes…" />
            </div>
            <div className="champ">
              <label htmlFor="not-assigne">Assigner à</label>
              <select id="not-assigne" name="assigneeId" defaultValue="">
                <option value="">—</option>
                {techniciens.map((t) => (
                  <option key={t.id} value={t.id}>{t.displayName}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="gros-toggle" style={{ marginTop: 14 }}>
            <b>Personne bloquée dans la cabine ?</b>
            <span style={{ marginLeft: 6, fontSize: 12, color: 'var(--encre-2)' }}>
              passe l'OT en urgence absolue (bandeau + tête de liste)
            </span>
            <button
              type="button"
              className="interrupteur"
              role="switch"
              aria-checked={personneBloquee}
              aria-label="Personne bloquée"
              onClick={() => setPersonneBloquee((v) => !v)}
            />
          </div>
        </div>
        {creation.isError ? (
          <p className="erreur-form" role="alert">{creation.error.message}</p>
        ) : null}
        <div className="flex justify-end gap-2">
          <Button onClick={() => navigate('/ot')}>Annuler</Button>
          <Button type="submit" variant="prim" disabled={creation.isPending}>
            Créer l'OT (statut Ouvert)
          </Button>
        </div>
      </form>
    </div>
  );
}
