'use client';

import { FormEvent, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useToast } from '@/components/toast';

export default function LoginPage() {
  const { showToast } = useToast();
  const router = useRouter();
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password })
      });

      const data = await response.json();
      if (!response.ok) throw new Error(data.error || 'No se pudo iniciar sesión');

      showToast('Bienvenido', 'success');
      router.replace('/venta-rapida');
      router.refresh();
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Error al iniciar sesión', 'error');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <form onSubmit={onSubmit} className="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h1 className="text-2xl font-bold text-slate-900">Inventario Farmacia</h1>
        <p className="mt-1 text-sm text-slate-600">Ingresa la contraseña de administrador</p>

        <input
          type="password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
          placeholder="Contraseña"
          className="mt-4 w-full rounded-xl border border-slate-300 px-4 py-3"
          required
        />

        <button
          type="submit"
          disabled={loading}
          className="mt-4 w-full rounded-xl bg-brand-600 px-4 py-3 text-base font-semibold text-white disabled:opacity-70"
        >
          {loading ? 'Ingresando...' : 'Entrar'}
        </button>
      </form>
    </div>
  );
}
