"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Modal from "@/components/Modal";
import { createManualInvoice } from "../actions";

type AgencyOption = {
  id: string;
  name: string;
  billingCutoffDay: number | null;
  license: { name: string } | null;
};

export default function InvoiceCreateModal({ agencies }: { agencies: AgencyOption[] }) {
  const [open, setOpen] = useState(false);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  const router = useRouter();

  const withLicense = agencies.filter((a) => a.license);

  async function onSubmit(formData: FormData) {
    setSaving(true);
    setError("");
    const res = await createManualInvoice(formData);
    setSaving(false);
    if (res && "error" in res && res.error) {
      setError(res.error);
      return;
    }
    setOpen(false);
    router.refresh();
  }

  return (
    <>
      <button className="btn-primary" onClick={() => setOpen(true)}>
        + Nueva factura
      </button>

      <Modal open={open} onClose={() => setOpen(false)} title="Crear factura manual">
        <form action={onSubmit} className="space-y-4">
          <div>
            <label className="label">Agencia de viaje *</label>
            <select name="agencyId" required className="input">
              <option value="">— Seleccionar agencia —</option>
              {withLicense.map((a) => (
                <option key={a.id} value={a.id}>
                  {a.name} · {a.license?.name}
                </option>
              ))}
            </select>
            {withLicense.length === 0 ? (
              <p className="mt-1 text-xs text-amber-600">
                No hay agencias con licencia asignada.
              </p>
            ) : null}
          </div>

          <div>
            <label className="label">Fecha de corte</label>
            <input name="cutoffDate" type="date" className="input" />
            <p className="mt-1 text-xs text-slate-500">
              Opcional. Si no la indicas, se usa el día de corte configurado en la agencia.
            </p>
          </div>

          {error ? (
            <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{error}</p>
          ) : null}

          <div className="flex justify-end gap-2">
            <button type="button" className="btn-ghost" onClick={() => setOpen(false)}>
              Cancelar
            </button>
            <button
              type="submit"
              disabled={saving || withLicense.length === 0}
              className="btn-primary"
            >
              {saving ? "Creando…" : "Crear factura"}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}
