"use client";
import { useEffect, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { Loading } from "@/components/ui/Loading";
import { TicketTableRow } from "@/components/ui/TicketTableRow";
import { Ticket } from "@/types";
import { gameService } from "@/services/game.service";
import { ROUTES } from "@/utils/constants";
import Link from "next/link";

export default function ClientPage() {
  const { user, isAuthenticated, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState({
    total: 0,
    claimed: 0,
    pending: 0,
  });

  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.push(ROUTES.LOGIN);
      return;
    }

    if (isAuthenticated) {
      loadUserTickets();
    }
  }, [authLoading, isAuthenticated, router]);

  const loadUserTickets = async () => {
    try {
      const response = await gameService.getMyTickets(1, 100);
      const ticketsData = response?.data || [];
      setTickets(ticketsData);

      // Calculate stats
      const total = ticketsData.length;
      const claimed = ticketsData.filter((t: Ticket) => t.status === "CLAIMED").length;
      const pending = ticketsData.filter((t: Ticket) => t.status === "PENDING").length;

      setStats({ total, claimed, pending });
    } catch (error) {
      console.error("Error loading tickets:", error);
    } finally {
      setIsLoading(false);
    }
  };

  if (authLoading || isLoading) {
    return (
      <div className="min-h-[calc(100vh-8rem)] flex items-center justify-center">
        <Loading size="lg" />
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }


  return (
    <div className="min-h-screen bg-gradient-to-br from-[#f5f5f0] via-[#faf9f5] to-[#f5f5f0] py-8">
      <div className="container mx-auto px-4">
        {/* Welcome Section */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-[#5a5a4e] mb-2">
            Bonjour {user?.firstName} ! 👋
          </h1>
          <p className="text-[#8a8a7a]">
            Bienvenue dans votre espace client
          </p>
        </div>

        {/* Quick Action */}
        <div className="mb-8">
          <div className="bg-gradient-to-r from-[#d4a574] to-[#c4956a] text-white rounded-xl shadow-md p-8 border-2 border-[#e5e4dc]">
            <div className="flex flex-col md:flex-row items-center justify-between gap-4">
              <div>
                <h2 className="text-2xl font-bold mb-2">
                  Vous avez un nouveau ticket ?
                </h2>
                <p className="text-white/90">
                  Entrez votre code et découvrez votre gain instantanément
                </p>
              </div>
              <Link href={ROUTES.GAME}>
                <button className="bg-white text-[#d4a574] hover:bg-[#f5f5f0] font-bold px-8 py-4 rounded-lg transition-all shadow-lg hover:scale-105 duration-300 whitespace-nowrap">
                  Jouer maintenant 🎮
                </button>
              </Link>
            </div>
          </div>
        </div>

        {/* Statistics Cards */}
        <div className="grid md:grid-cols-3 gap-6 mb-8">
          <div className="bg-white rounded-xl shadow-md p-6 border border-[#e5e4dc]">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-[#8a8a7a] mb-2">
                  Total Participations
                </p>
                <p className="text-4xl font-bold text-blue-600">
                  {stats.total}
                </p>
              </div>
              <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-md p-6 border border-[#e5e4dc]">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-[#8a8a7a] mb-2">
                  Gains réclamés
                </p>
                <p className="text-4xl font-bold text-green-600">
                  {stats.claimed}
                </p>
              </div>
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-md p-6 border border-[#e5e4dc]">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-[#8a8a7a] mb-2">
                  En attente
                </p>
                <p className="text-4xl font-bold text-yellow-600">
                  {stats.pending}
                </p>
              </div>
              <div className="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        {/* Recent Tickets */}
        <div className="bg-white rounded-xl shadow-md overflow-hidden border border-[#e5e4dc]">
          <div className="px-6 py-4 border-b border-[#e5e4dc]">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-bold text-[#5a5a4e]">Mes derniers tickets</h2>
              <Link href={ROUTES.HISTORY}>
                <button className="text-[#d4a574] hover:text-[#c4956a] font-semibold text-sm transition-colors">
                  Voir tout l'historique
                </button>
              </Link>
            </div>
          </div>
          <div className="p-6">
            {tickets.length === 0 ? (
              <div className="text-center py-12">
                <div className="text-6xl mb-4">🎲</div>
                <p className="text-[#8a8a7a] mb-4">
                  Vous n'avez pas encore participé au jeu
                </p>
                <Link href={ROUTES.GAME}>
                  <button className="bg-gradient-to-r from-[#d4a574] to-[#c4956a] hover:from-[#e5b685] hover:to-[#d4a574] text-white font-bold px-6 py-3 rounded-lg transition-all shadow-lg hover:scale-105 duration-300">
                    Jouer maintenant
                  </button>
                </Link>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead>
                    <tr className="border-b border-[#e5e4dc]">
                      <th className="px-6 py-3 text-left text-xs font-semibold text-[#5a5a4e] uppercase tracking-wider">
                        Code Ticket
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-[#5a5a4e] uppercase tracking-wider">
                        Gain
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-[#5a5a4e] uppercase tracking-wider">
                        Statut
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-[#5a5a4e] uppercase tracking-wider">
                        Date
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[#e5e4dc]">
                    {tickets.slice(0, 5).map((ticket) => (
                      <TicketTableRow key={ticket.id} ticket={ticket} />
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
