"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-beige-100 via-beige-50 to-beige-100 py-8">
      <div className="container mx-auto px-4">
        {/* Welcome Section */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-primary-500 mb-2">
            Bonjour {user?.firstName} !
          </h1>
          <p className="text-gray-600">
            Bienvenue dans votre espace client
          </p>
        </div>

        {/* Quick Action */}
        <div className="mb-8">
          <div className="bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-xl shadow-md p-8 border-2 border-primary-400">
            <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-primary-500 hover:bg-beige-50 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-beige-300">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 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-beige-300">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-2">
                  Gains réclamés
                </p>
                <p className="text-4xl font-bold text-primary-600">
                  {stats.claimed}
                </p>
              </div>
              <div className="w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-primary-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-beige-300">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-2">
                  En attente
                </p>
                <p className="text-4xl font-bold text-secondary-600">
                  {stats.pending}
                </p>
              </div>
              <div className="w-16 h-16 bg-secondary-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-secondary-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-beige-300">
          <div className="px-6 py-4 border-b border-beige-300">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-bold text-primary-500">Mes derniers tickets</h2>
              <Link href={ROUTES.HISTORY}>
                <button className="text-primary-500 hover:text-primary-600 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-gray-600 mb-4">
                  Vous n'avez pas encore participé au jeu
                </p>
                <Link href={ROUTES.GAME}>
                  <button className="bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 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-beige-300">
                      <th className="px-6 py-3 text-left text-xs font-semibold text-primary-500 uppercase tracking-wider">
                        Code Ticket
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-primary-500 uppercase tracking-wider">
                        Gain
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-primary-500 uppercase tracking-wider">
                        Statut
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-primary-500 uppercase tracking-wider">
                        Date
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-beige-200">
                    {tickets.slice(0, 5).map((ticket) => (
                      <TicketTableRow key={ticket.id} ticket={ticket} />
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
