import { useState, type FormEvent } from 'react';
import { useAuth } from '../lib/auth';
import { supabase } from '../lib/supabase';

export default function Registro() {
  const { refrescar, salir } = useAuth();
  const [nombre, setNombre] = useState('');
  const [telefono, setTelefono] = useState('');
  const [err, setErr] = useState<string | null>(null);
  const [cargando, setCargando] = useState(false);

  async function crear(e: FormEvent) {
    e.preventDefault();
    setErr(null);
    setCargando(true);
    const { error } = await supabase.rpc('crear_restaurante', {
      p_nombre: nombre,
      p_telefono: telefono || undefined,
    });
    if (error) {
      setErr(error.message);
      setCargando(false);
      return;
    }
    await refrescar(); // el perfil ahora es dueno con restaurante -> App lleva al wizard
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-noche p-4 text-white">
      <form onSubmit={crear} className="w-full max-w-sm rounded-3xl bg-superficie p-6 shadow-2xl ring-1 ring-white/10">
        <h1 className="text-xl font-extrabold text-white">Registra tu negocio</h1>
        <p className="mb-4 text-sm text-niebla">Ponle nombre a tu restaurante. En un momento armamos tu tienda.</p>
        <label className="mb-3 block">
          <span className="text-xs font-medium text-niebla">Nombre del negocio</span>
          <input
            className="mt-1 w-full rounded-xl border border-white/10 bg-superficie-2 px-4 py-3 text-sm text-white placeholder:text-white/40 outline-none focus:border-dorado"
            value={nombre}
            onChange={(e) => setNombre(e.target.value)}
            placeholder="Ej. Cachapera La Esquina"
            required
          />
        </label>
        <label className="mb-4 block">
          <span className="text-xs font-medium text-niebla">Telefono / WhatsApp</span>
          <input
            className="mt-1 w-full rounded-xl border border-white/10 bg-superficie-2 px-4 py-3 text-sm text-white placeholder:text-white/40 outline-none focus:border-dorado"
            value={telefono}
            onChange={(e) => setTelefono(e.target.value)}
            placeholder="0414-1234567"
            inputMode="tel"
          />
        </label>
        {err && <p className="mb-3 rounded-lg bg-red-500/15 px-3 py-2 text-sm text-red-300 ring-1 ring-red-500/25">{err}</p>}
        <button disabled={cargando} className="w-full rounded-2xl bg-dorado py-3 text-base font-bold text-noche shadow-glow transition active:scale-[0.99] disabled:opacity-60">
          {cargando ? 'Creando...' : 'Crear mi tienda'}
        </button>
        <button type="button" onClick={salir} className="mt-3 w-full text-sm text-niebla hover:text-white">
          Salir
        </button>
      </form>
    </div>
  );
}
