'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { FormEvent, useMemo, useState } from 'react';
import { writeSession } from '../lib/auth-session';

const apiBase = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api';

export function LoginForm() {
  const router = useRouter();
  const [email, setEmail] = useState('loja@chego.app');
  const [password, setPassword] = useState('Admin@123');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const endpoint = useMemo(() => `${apiBase}/auth/login/restaurant`, []);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError('');

    try {
      const loginResponse = await fetch(endpoint, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

      const loginPayload = await loginResponse.json().catch(() => null);
      if (!loginResponse.ok || !loginPayload?.accessToken) {
        throw new Error(loginPayload?.message ?? 'Nao foi possivel autenticar a loja.');
      }

      const profileResponse = await fetch(`${apiBase}/auth/me`, {
        headers: { authorization: `Bearer ${loginPayload.accessToken}` },
      });
      const profilePayload = await profileResponse.json().catch(() => null);

      writeSession({
        ...loginPayload,
        profile: profileResponse.ok ? profilePayload : undefined,
      });
      router.push('/');
      router.refresh();
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : 'Falha ao autenticar.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form className="space-y-4" onSubmit={handleSubmit}>
      <div>
        <label className="text-[11px] font-bold uppercase tracking-[0.24em] text-slate-400">Email da loja</label>
        <input
          type="email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          placeholder="loja@chego.app"
          className="mt-2 h-14 w-full rounded-2xl border border-white/10 bg-white/5 px-4 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-[#ff7a1a] focus:bg-white/10"
        />
      </div>
      <div>
        <label className="text-[11px] font-bold uppercase tracking-[0.24em] text-slate-400">Senha</label>
        <input
          type="password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
          placeholder="Admin@123"
          className="mt-2 h-14 w-full rounded-2xl border border-white/10 bg-white/5 px-4 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-[#ff7a1a] focus:bg-white/10"
        />
      </div>
      {error ? <p className="rounded-2xl border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-200">{error}</p> : null}
      <button
        type="submit"
        disabled={loading}
        className="h-14 w-full rounded-2xl bg-[#ff7a1a] text-sm font-black uppercase tracking-[0.24em] text-[#10141b] shadow-[0_18px_36px_rgba(255,122,26,0.24)] transition hover:bg-[#ff8f3d] disabled:cursor-not-allowed disabled:opacity-70"
      >
        {loading ? 'Validando acesso...' : 'Entrar na loja'}
      </button>
      <p className="text-center text-xs text-slate-500">
        Ainda nao tem acesso?{' '}
        <Link href="/cadastro" className="font-semibold text-[#ff9a57] transition hover:text-white">
          Cadastre-se aqui
        </Link>
      </p>
    </form>
  );
}
