"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import FooterBase from '@/components/sections/footer/FooterBase';
import { LogOut, User, Mail, Zap } from 'lucide-react';

interface UserData {
  id: string;
  name: string;
  email: string;
}

export default function DashboardPage() {
  const router = useRouter();
  const [user, setUser] = useState<UserData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem("authToken");
      const userData = localStorage.getItem("user");

      if (!token || !userData) {
        router.push("/auth/login");
        return;
      }

      try {
        const response = await fetch("/api/auth/verify", {
          headers: { Authorization: `Bearer ${token}` },
        });

        if (!response.ok) {
          localStorage.removeItem("authToken");
          localStorage.removeItem("user");
          router.push("/auth/login");
          return;
        }

        setUser(JSON.parse(userData));
      } catch (err) {
        setError("Erro ao verificar sessão");
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, [router]);

  const handleLogout = () => {
    localStorage.removeItem("authToken");
    localStorage.removeItem("user");
    router.push("/");
  };

  if (loading) {
    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 className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-cta"></div>
            <p className="mt-4 text-foreground/60">Carregando...</p>
          </div>
        </div>
      </ThemeProvider>
    );
  }

  if (error) {
    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 className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <p className="text-red-500">{error}</p>
          </div>
        </div>
      </ThemeProvider>
    );
  }

  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: "Sair", href: "/" }}
          brandName="FitFlow Pro"
        />
      </div>

      <div className="min-h-screen px-4 py-20">
        <div className="max-w-4xl mx-auto">
          <h1 className="text-4xl font-bold mb-8">Dashboard</h1>

          {user && (
            <div className="grid gap-6">
              <div className="bg-card rounded-2xl p-8 shadow-lg border border-foreground/10">
                <h2 className="text-2xl font-bold mb-6">Bem-vindo, {user.name}!</h2>
                
                <div className="grid md:grid-cols-2 gap-8">
                  <div className="space-y-4">
                    <div className="flex items-center space-x-3">
                      <User className="w-6 h-6 text-primary-cta" />
                      <div>
                        <p className="text-sm text-foreground/60">Nome</p>
                        <p className="font-semibold">{user.name}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <Mail className="w-6 h-6 text-primary-cta" />
                      <div>
                        <p className="text-sm text-foreground/60">Email</p>
                        <p className="font-semibold">{user.email}</p>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="bg-background rounded-lg p-4">
                      <p className="text-sm text-foreground/60 mb-2">Status da Sessão</p>
                      <div className="flex items-center space-x-2">
                        <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                        <p className="font-semibold text-green-500">Conectado</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid md:grid-cols-3 gap-6">
                <div className="bg-gradient-to-br from-primary-cta/20 to-accent/20 rounded-2xl p-6 border border-primary-cta/20">
                  <Zap className="w-8 h-8 text-primary-cta mb-2" />
                  <h3 className="text-lg font-semibold mb-1">Treinos</h3>
                  <p className="text-3xl font-bold text-primary-cta">0</p>
                  <p className="text-sm text-foreground/60 mt-2">Treinos concluídos</p>
                </div>

                <div className="bg-gradient-to-br from-accent/20 to-secondary-cta/20 rounded-2xl p-6 border border-accent/20">
                  <Zap className="w-8 h-8 text-accent mb-2" />
                  <h3 className="text-lg font-semibold mb-1">Nutrição</h3>
                  <p className="text-3xl font-bold text-accent">0</p>
                  <p className="text-sm text-foreground/60 mt-2">Refeições rastreadas</p>
                </div>

                <div className="bg-gradient-to-br from-secondary-cta/20 to-primary-cta/20 rounded-2xl p-6 border border-secondary-cta/20">
                  <Zap className="w-8 h-8 text-secondary-cta mb-2" />
                  <h3 className="text-lg font-semibold mb-1">Cardio</h3>
                  <p className="text-3xl font-bold text-secondary-cta">0 km</p>
                  <p className="text-sm text-foreground/60 mt-2">Distância total</p>
                </div>
              </div>

              <button
                onClick={handleLogout}
                className="w-full bg-red-500 hover:bg-red-600 text-white py-3 rounded-lg font-semibold transition flex items-center justify-center space-x-2"
              >
                <LogOut className="w-5 h-5" />
                <span>Sair da Conta</span>
              </button>
            </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>
  );
}