"use client";
import { useEffect, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import Button from "@/components/Button";
import { Loading } from "@/components/ui/Loading";
import { Ticket } from "@/types";
import { gameService } from "@/services/game.service";
import { ROUTES, PRIZE_CONFIG } 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;
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "CLAIMED":
        return <Badge variant="success">Réclamé</Badge>;
      case "PENDING":
        return <Badge variant="warning">En attente</Badge>;
      case "REJECTED":
        return <Badge variant="danger">Rejeté</Badge>;
      default:
        return <Badge variant="default">{status}</Badge>;
    }
  };

  return (
    <div className="py-8">
      {/* Welcome Section */}
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-gray-900 mb-2">
          Bonjour {user?.firstName} ! 👋
        </h1>
        <p className="text-gray-600">
          Bienvenue dans votre espace client
        </p>
      </div>

      {/* Quick Action */}
      <div className="mb-8">
        <Card className="bg-gradient-to-r from-primary-500 to-primary-600 text-white">
          <CardContent className="py-8">
            <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-primary-50">
                  Entrez votre code et découvrez votre gain instantanément
                </p>
              </div>
              <Link href={ROUTES.GAME}>
                <Button
                  size="lg"
                  className="bg-white text-black hover:bg-gray-50 border-2 border-black"
                >
                  Jouer maintenant 🎮
                </Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Statistics Cards */}
      <div className="grid md:grid-cols-3 gap-6 mb-8">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  Total Participations
                </p>
                <p className="text-3xl font-bold text-gray-900 mt-2">
                  {stats.total}
                </p>
              </div>
              <div className="text-4xl">🎫</div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  Gains réclamés
                </p>
                <p className="text-3xl font-bold text-green-600 mt-2">
                  {stats.claimed}
                </p>
              </div>
              <div className="text-4xl">✅</div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  En attente
                </p>
                <p className="text-3xl font-bold text-yellow-600 mt-2">
                  {stats.pending}
                </p>
              </div>
              <div className="text-4xl">⏳</div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Tickets */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Mes derniers tickets</CardTitle>
            <Link href={ROUTES.HISTORY}>
              <Button variant="outline" size="sm">
                Voir tout l'historique
              </Button>
            </Link>
          </div>
        </CardHeader>
        <CardContent>
          {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-white text-black hover:bg-gray-50 border-2 border-black">Jouer maintenant</Button>
              </Link>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Code Ticket
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Gain
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Statut
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Date
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {tickets.slice(0, 5).map((ticket) => {
                    const prizeConfig = ticket.prize
                      ? PRIZE_CONFIG[ticket.prize.type]
                      : null;

                    return (
                      <tr key={ticket.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className="font-mono text-sm font-medium text-gray-900">
                            {ticket.code}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            {prizeConfig && (
                              <>
                                <span className="text-2xl mr-2">
                                  {prizeConfig.icon}
                                </span>
                                <span className="text-sm text-gray-900">
                                  {prizeConfig.name}
                                </span>
                              </>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {getStatusBadge(ticket.status)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {ticket.playedAt ? new Date(ticket.playedAt).toLocaleDateString("fr-FR") : "-"}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
