import { useState, type FormEvent } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { supabase } from '../lib/supabase';

interface RepFila {
  repartidor_id: string;
  nombre: string | null;
  telefono: string | null;
  vehiculo: string | null;
  estado: string;
  creado_en: string;
}

const VACIO = { nombre: '', telefono: '', vehiculo: 'Moto', email: '', password: '' };

export default function Repartidores({ restauranteId }: { restauranteId: string }) {
  const qc = useQueryClient();
  const [form, setForm] = useState(VACIO);
  const [guardando, setGuardando] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);

  const q = useQuery({
    queryKey: ['mis-repartidores', restauranteId],
    queryFn: async () => {
      const { data, error } = await supabase.rpc('mis_repartidores');
      if (error) throw error;
      return (data as unknown as RepFila[]) ?? [];
    },
  });

  async function crear(e: FormEvent) {
    e.preventDefault();
    setErr(null);
    setMsg(null);
    setGuardando(true);
    const { data, error } = await supabase.functions.invoke('crear-repartidor', { body: form });
    setGuardando(false);
    if (error) {
      let m = error.message;
      try {
        const ctx = (error as { context?: Response }).context;
        if (ctx) {
          const j = (await ctx.json()) as { error?: string };
          if (j?.error) m = j.error;
        }
      } catch {
        /* sin cuerpo */
      }
      setErr(m);
      return;
    }
    if ((data as { error?: string })?.error) {
      setErr((data as { error?: string }).error!);
      return;
    }
    setMsg('Repartidor agregado: ' + form.nombre + '. Pasale su correo y clave.');
    setForm(VACIO);
    qc.invalidateQueries({ queryKey: ['mis-repartidores', restauranteId] });
  }

  async function eliminar(rep: RepFila) {
    if (
      !confirm(
        `Eliminar al repartidor "${rep.nombre || 'Repartidor'}"? Ya no podra recibir tus pedidos. No se puede deshacer.`,
      )
    )
      return;
    setErr(null);
    setMsg(null);
    const { error } = await supabase.from('repartidores').delete().eq('id', rep.repartidor_id);
    if (error) {
      setErr(error.message);
      return;
    }
    setMsg('Repartidor eliminado.');
    qc.invalidateQueries({ queryKey: ['mis-repartidores', restauranteId] });
  }

  const reps = q.data ?? [];

  return (
    <div className="space-y-4">
      {q.isLoading && <p className="text-sm text-niebla">Cargando...</p>}
      {reps.length > 0 ? (
        <ul className="space-y-2">
          {reps.map((r) => (
            <li key={r.repartidor_id} className="flex items-center justify-between gap-2 rounded-xl border bg-superficie p-3">
              <div className="min-w-0">
                <p className="truncate text-sm font-bold">{r.nombre || 'Repartidor'}</p>
                <p className="truncate text-xs text-niebla">
                  {r.telefono || 'sin telefono'} · {r.vehiculo || 'vehiculo'}
                </p>
              </div>
              <div className="flex shrink-0 items-center gap-2">
                <span
                  className={`rounded-full px-2 py-1 text-xs font-semibold ${
                    r.estado === 'disponible'
                      ? 'bg-green-100 text-green-700'
                      : r.estado === 'ocupado'
                        ? 'bg-dorado/15 text-dorado'
                        : 'bg-white/10 text-niebla'
                  }`}
                >
                  {r.estado}
                </span>
                <button
                  onClick={() => eliminar(r)}
                  className="rounded-lg p-2 text-red-500 hover:bg-red-50"
                  title="Eliminar repartidor"
                  aria-label="Eliminar repartidor"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v6M14 11v6" />
                  </svg>
                </button>
              </div>
            </li>
          ))}
        </ul>
      ) : (
        !q.isLoading && <p className="text-sm text-niebla">Aun no tienes repartidores. Agrega el primero abajo.</p>
      )}

      <form onSubmit={crear} className="space-y-2 border-t pt-4">
        <p className="text-xs font-bold text-niebla">Agregar repartidor</p>
        <div className="grid grid-cols-2 gap-2">
          <input className="input" placeholder="Nombre" value={form.nombre} onChange={(e) => setForm({ ...form, nombre: e.target.value })} required />
          <input className="input" placeholder="Telefono" value={form.telefono} onChange={(e) => setForm({ ...form, telefono: e.target.value })} inputMode="tel" />
        </div>
        <select className="input" value={form.vehiculo} onChange={(e) => setForm({ ...form, vehiculo: e.target.value })}>
          <option>Moto</option>
          <option>Carro</option>
          <option>Bicicleta</option>
          <option>A pie</option>
        </select>
        <input className="input" type="email" placeholder="Correo del repartidor" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
        <input
          className="input"
          type="text"
          placeholder="Clave (minimo 6, se la das al repartidor)"
          value={form.password}
          onChange={(e) => setForm({ ...form, password: e.target.value })}
          required
          minLength={6}
        />
        {err && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">{err}</p>}
        {msg && <p className="rounded-lg bg-green-50 px-3 py-2 text-sm text-green-700">{msg}</p>}
        <button disabled={guardando} className="btn bg-dorado text-noche disabled:opacity-60">
          {guardando ? 'Agregando...' : 'Agregar repartidor'}
        </button>
      </form>
    </div>
  );
}
