'use client';

import { useState, useEffect } from 'react';
import LoginForm from './interface';

const STRAPI_URL =
  process.env.NEXT_PUBLIC_STRAPI_URL || process.env.STRAPI_URL || 'http://localhost:1337';

export default function LoginPage() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Limpar JWT ao carregar a página /login
  useEffect(() => {
    const clearJWT = async () => {
      try {
        await fetch(`${STRAPI_URL}/api/auth/logout`, {
          method: 'POST',
          credentials: 'include',
        });
      } catch (err) {
        console.log('JWT já estava limpo ou erro ao limpar:', err.message);
      }
    };

    clearJWT();
  }, []);

  const handleSubmit = async (values) => {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch(`${STRAPI_URL}/api/auth/login`, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          identifier: values.identifier || values.username,
          password: values.password,
          recaptchaToken: values.recaptchaToken,
        }),
      });

      if (!res.ok) {
        let msg = 'Login inválido';
        try {
          const json = await res.json();
          msg = json?.message || json?.error?.message || msg;
        } catch {}
        throw new Error(msg);
      }

      await res.json().catch(() => null);
      window.location.href = '/admin/site-configuration';
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <LoginForm
      onSubmit={handleSubmit}
      loading={loading}
      error={error}
    />
  );
}
