'use client';

import { FormEvent, useState } from 'react';

import { markSignedIn } from '@/services/auth';

import Section from '@/components/common/Section';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Heading, Text } from '@/components/ui/typography';

import { useRouter } from '@/i18n/navigation';

const getLoginError = (value: unknown): string | null =>
  value &&
  typeof value === 'object' &&
  'error' in value &&
  typeof (value as { error?: unknown }).error === 'string'
    ? (value as { error: string }).error
    : null;

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

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

      if (!response.ok) {
        setError(getLoginError(data) ?? 'Sikertelen belépés.');
        return;
      }

      // The session itself is an HttpOnly cookie set by /api/login; the marker change makes
      // AuthProvider re-check the access, so no full reload is needed.
      markSignedIn();
      router.push('/');
    } catch {
      setError('A belépés most nem érhető el.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Section surface="white" spacing="compact">
      <div className="mx-auto w-full max-w-sm py-10">
        <Heading as="h1" variant="sectionTitle">
          Belső belépés
        </Heading>
        <Text as="p" variant="bodySm" tone="muted" className="mt-2">
          Jelentkezz be a belső eszközök használatához.
        </Text>

        <form onSubmit={handleSubmit} className="mt-7 space-y-4">
          <label className="block space-y-1.5">
            <span className="text-sm font-medium text-[#151720]">E-mail</span>
            <Input
              type="email"
              autoComplete="email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              required
            />
          </label>

          <label className="block space-y-1.5">
            <span className="text-sm font-medium text-[#151720]">Jelszó</span>
            <Input
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              required
            />
          </label>

          {error && (
            <Text
              as="p"
              variant="bodySm"
              className="border border-red-200 bg-red-50 p-3 text-red-800"
            >
              {error}
            </Text>
          )}

          <Button type="submit" size="control" disabled={isSubmitting} className="w-full">
            {isSubmitting ? 'Belépés…' : 'Belépés'}
          </Button>
        </form>
      </div>
    </Section>
  );
}
