"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';
import FooterBase from '@/components/sections/footer/FooterBase';
import { Mail, Lock, User, Eye, EyeOff, Check } from 'lucide-react';

export default function RegisterPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    name: "",    email: "",    password: "",    confirmPassword: ""});
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

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

    if (!agreedToTerms) {
      setError("Você deve concordar com os Termos e Condições");
      return;
    }

    if (formData.password !== formData.confirmPassword) {
      setError("As senhas não conferem");
      return;
    }

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

    setLoading(true);

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

      if (!response.ok) {
        const data = await response.json();
        setError(data.message || "Falha ao registrar");
        return;
      }

      const data = await response.json();
      localStorage.setItem("authToken", data.token);
      localStorage.setItem("user", JSON.stringify(data.user));
      router.push("/dashboard");
    } catch (err) {
      setError("Erro ao conectar ao servidor");
      console.error(err);
    } finally {
      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: "Entrar", href: "/auth/login" }}
          brandName="FitFlow Pro"
        />
      </div>

      <div className="min-h-screen flex items-center justify-center px-4 py-20">
        <div className="w-full max-w-md">
          <div className="bg-card rounded-2xl p-8 shadow-lg">
            <h1 className="text-3xl font-bold text-center mb-2">Registre-se</h1>
            <p className="text-center text-foreground/60 mb-8">Comece sua transformação com FitFlow Pro</p>

            {error && (
              <div className="bg-red-500/10 border border-red-500 text-red-500 px-4 py-3 rounded-lg mb-6">
                {error}
              </div>
            )}

            <form onSubmit={handleRegister} className="space-y-6">
              <div>
                <label className="block text-sm font-medium mb-2">Nome Completo</label>
                <div className="relative">
                  <User className="absolute left-3 top-3 w-5 h-5 text-foreground/40" />
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder="Seu nome completo"
                    required
                    className="w-full pl-10 pr-4 py-3 border border-foreground/20 rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-cta"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">Email</label>
                <div className="relative">
                  <Mail className="absolute left-3 top-3 w-5 h-5 text-foreground/40" />
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    placeholder="seu.email@exemplo.com"
                    required
                    className="w-full pl-10 pr-4 py-3 border border-foreground/20 rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-cta"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">Senha</label>
                <div className="relative">
                  <Lock className="absolute left-3 top-3 w-5 h-5 text-foreground/40" />
                  <input
                    type={showPassword ? "text" : "password"}
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    placeholder="Mínimo 8 caracteres"
                    required
                    className="w-full pl-10 pr-10 py-3 border border-foreground/20 rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-cta"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-3 text-foreground/40"
                  >
                    {showPassword ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">Confirmar Senha</label>
                <div className="relative">
                  <Lock className="absolute left-3 top-3 w-5 h-5 text-foreground/40" />
                  <input
                    type={showConfirm ? "text" : "password"}
                    name="confirmPassword"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                    placeholder="Confirme sua senha"
                    required
                    className="w-full pl-10 pr-10 py-3 border border-foreground/20 rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-cta"
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirm(!showConfirm)}
                    className="absolute right-3 top-3 text-foreground/40"
                  >
                    {showConfirm ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <div className="flex items-start space-x-3">
                <input
                  type="checkbox"
                  id="terms"
                  checked={agreedToTerms}
                  onChange={(e) => setAgreedToTerms(e.target.checked)}
                  className="mt-1 w-5 h-5 rounded cursor-pointer"
                />
                <label htmlFor="terms" className="text-sm text-foreground/60 cursor-pointer">
                  Concordo com os <Link href="/terms" className="text-primary-cta hover:underline">Termos e Condições</Link> e a <Link href="/privacy" className="text-primary-cta hover:underline">Política de Privacidade</Link>
                </label>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-primary-cta text-white py-3 rounded-lg font-semibold hover:opacity-90 disabled:opacity-50 transition"
              >
                {loading ? "Registrando..." : "Criar Conta"}
              </button>
            </form>

            <p className="text-center mt-6 text-foreground/60">
              Já tem uma conta?{" "}
              <Link href="/auth/login" className="text-primary-cta font-semibold hover:underline">
                Faça login aqui
              </Link>
            </p>
          </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>
  );
}