"use client";
import { useState } from "react";

export default function NewStaffTicketForm({ orgs, activeOrgId }: { orgs: { id: string; name: string }[]; activeOrgId?: string | null }) {
  const [posting, setPosting] = useState(false);
  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const org_id = String(fd.get('org_id') || '').trim();
    const subject = String(fd.get('subject') || '').trim();
    const message = String(fd.get('message') || '').trim();
    const priority = String(fd.get('priority') || 'normal');
    if (!subject || !message) return;
    setPosting(true);
    try {
      const res = await fetch('/api/tickets', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ org_id, subject, message, priority })
      });
      if (!res.ok) throw new Error(await res.text());
      const t = await res.json();
      window.location.href = `/staff/tickets/${t.id}`;
    } catch (e: any) {
      alert('Erreur: ' + (e?.message || 'inconnue'));
    } finally {
      setPosting(false);
    }
  }
  return (
    <form className="space-y-3" onSubmit={onSubmit}>
      <div>
        <label className="block text-sm font-medium mb-1">Organisation</label>
        <select name="org_id" defaultValue={activeOrgId || ''} className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm">
          <option value="">— Sélectionner —</option>
          {orgs.map((o) => (
            <option key={o.id} value={o.id}>{o.name}</option>
          ))}
        </select>
        {activeOrgId ? <p className="text-xs text-slate-500 mt-1">Organisation active détectée.</p> : null}
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Sujet</label>
        <input name="subject" className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm" placeholder="Sujet" />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Message initial</label>
        <textarea name="message" className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm min-h-[120px]" placeholder="Décrivez la demande…" />
      </div>
      <div className="flex items-center gap-3">
        <label className="text-sm">Priorité</label>
        <select name="priority" defaultValue="normal" className="px-2 py-1 rounded-md border text-sm bg-transparent">
          <option value="low">Basse</option>
          <option value="normal">Normale</option>
          <option value="high">Haute</option>
          <option value="urgent">Urgente</option>
        </select>
        <button disabled={posting} className="ml-auto inline-flex items-center px-3 py-2 rounded-lg bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-50">Créer</button>
      </div>
    </form>
  );
}

