"use client";

import { useState } from "react";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import ContactSplit from '@/components/sections/contact/ContactSplit';
import FooterBase from '@/components/sections/footer/FooterBase';
import { Mail, Lock } from 'lucide-react';

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      // Validate inputs
      if (!email || !password) {
        setError("Por favor, preencha todos os campos.");
        setLoading(false);
        return;
      }

      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        setError("Por favor, insira um email válido.");
        setLoading(false);
        return;
      }

      if (password.length < 6) {
        setError("A senha deve ter pelo menos 6 caracteres.");
        setLoading(false);
        return;
      }

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

      const data = await response.json();

      if (!response.ok) {
        setError(data.message || "Erro ao fazer login. Tente novamente.");
        setLoading(false);
        return;
      }

      // Store user session
      localStorage.setItem("userSession", JSON.stringify({
        token: data.token,
        user: data.user,
        expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
      }));

      // Redirect to dashboard
      window.location.href = "/dashboard";
    } catch (err) {
      setError("Erro de conexão. Tente novamente mais tarde.");
      setLoading(false);
    }
  };

  return (
    <ThemeProvider
      defaultButtonVariant="elastic-effect"
      defaultTextAnimation="entrance-slide"
      borderRadius="pill"
      contentWidth="smallMedium"
      sizing="mediumSizeLargeTitles"
      background="blurBottom"
      cardStyle="gradient-bordered"
      primaryButtonStyle="flat"
      secondaryButtonStyle="glass"
      headingFontWeight="extrabold"
    >
      <div id="nav" data-section="nav">
        <NavbarStyleCentered
          navItems={[
            { name: "Dashboard", id: "/dashboard" },
            { name: "Treino", id: "training" },
            { name: "Nutrição", id: "nutrition" },
            { name: "Comunidade", id: "community" },
            { name: "Perfil", id: "profile" }
          ]}
          button={{ text: "Começar Agora", href: "contact" }}
          brandName="FitFlow Pro"
        />
      </div>

      <div id="login" data-section="login" className="min-h-screen flex items-center justify-center py-20 px-4">
        <div className="w-full max-w-md">
          <div className="rounded-2xl border border-primary-cta/20 bg-card p-8 shadow-lg">
            <h1 className="text-3xl font-bold text-foreground mb-2">Bem-vindo de Volta</h1>
            <p className="text-foreground/60 mb-8">Faça login em sua conta FitFlow Pro</p>

            {error && (
              <div className="mb-6 p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-600 text-sm">
                {error}
              </div>
            )}

            <form onSubmit={handleLogin} className="space-y-5">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">
                  Email
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-foreground/40" />
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="seu.email@exemplo.com"
                    className="w-full pl-10 pr-4 py-2 rounded-lg border border-foreground/10 bg-background focus:outline-none focus:border-primary-cta/50 text-foreground placeholder-foreground/40 transition"
                    disabled={loading}
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">
                  Senha
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-foreground/40" />
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full pl-10 pr-4 py-2 rounded-lg border border-foreground/10 bg-background focus:outline-none focus:border-primary-cta/50 text-foreground placeholder-foreground/40 transition"
                    disabled={loading}
                  />
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 rounded-lg bg-primary-cta text-white font-medium hover:bg-primary-cta/90 transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? "Entrando..." : "Entrar"}
              </button>
            </form>

            <div className="mt-6 text-center">
              <p className="text-foreground/60 text-sm">
                Não tem uma conta?{" "}
                <a href="/signup" className="text-primary-cta hover:underline font-medium">
                  Cadastre-se aqui
                </a>
              </p>
            </div>

            <div className="mt-6 text-center">
              <a href="/" className="text-primary-cta hover:underline font-medium text-sm">
                Voltar para Home
              </a>
            </div>
          </div>
        </div>
      </div>

      <div id="footer" data-section="footer">
        <FooterBase
          columns={[
            {
              title: "Produto",              items: [
                { label: "Dashboard", href: "dashboard" },
                { label: "Treino", href: "training" },
                { label: "Nutrição", href: "nutrition" },
                { label: "Cardio Hub", href: "cardio" }
              ]
            },
            {
              title: "Comunidade",              items: [
                { label: "Comunidade", href: "community" },
                { label: "Perfil", href: "profile" },
                { label: "Rankings", href: "rankings" },
                { label: "Blog", href: "blog" }
              ]
            },
            {
              title: "Empresa",              items: [
                { label: "Sobre", href: "about" },
                { label: "Contato", href: "contact" },
                { label: "Privacidade", href: "privacy" },
                { label: "Termos", href: "terms" }
              ]
            }
          ]}
          logoText="FitFlow Pro"
          copyrightText="© 2025 FitFlow Pro. Todos os direitos reservados."
        />
      </div>
    </ThemeProvider>
  );
}
