"use client";
import { useEffect, useState, useCallback } 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 { Calendar, Search } from "lucide-react";

export default function HistoriquePage() {
  const { user, isAuthenticated, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [filteredTickets, setFilteredTickets] = useState<Ticket[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filter, setFilter] = useState<'ALL' | 'CLAIMED' | 'PENDING' | 'REJECTED'>('ALL');
  const [searchQuery, setSearchQuery] = useState('');
  const [stats, setStats] = useState({
    total: 0,
    claimed: 0,
    pending: 0,
    rejected: 0,
  });

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

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

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

  const filterTickets = useCallback(() => {
    let result = [...tickets];

    if (filter !== 'ALL') {
      result = result.filter((t) => t.status === filter);
    }

    if (searchQuery) {
      result = result.filter((t) =>
        t.code.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    setFilteredTickets(result);
  }, [tickets, filter, searchQuery]);

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

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

  useEffect(() => {
    filterTickets();
  }, [filterTickets]);

  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">
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-gray-800 mb-2 flex items-center gap-3">
            <Calendar className="w-10 h-10 text-primary-500" />
            Historique de mes participations
          </h1>
          <p className="text-gray-600">
            Consultez l'historique complet de vos participations et gains
          </p>
        </div>

        <div className="grid md:grid-cols-4 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</p>
                <p className="text-4xl font-bold text-primary-600">{stats.total}</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 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">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 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">Rejetés</p>
                <p className="text-4xl font-bold text-red-600">{stats.rejected}</p>
              </div>
              <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-md p-6 mb-6 border border-beige-300">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 w-5 h-5" />
                <input
                  type="text"
                  placeholder="Rechercher par code ticket..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 border-2 border-beige-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 focus:outline-none"
                />
              </div>
            </div>

            <div className="flex gap-2">
              <button
                onClick={() => setFilter('ALL')}
                className={`px-4 py-2 rounded-lg font-semibold transition-all ${
                  filter === 'ALL'
                    ? 'bg-gradient-to-r from-primary-500 to-primary-600 text-white shadow-lg'
                    : 'bg-beige-100 text-gray-700 hover:bg-beige-200'
                }`}
              >
                Tous ({tickets.length})
              </button>
              <button
                onClick={() => setFilter('CLAIMED')}
                className={`px-4 py-2 rounded-lg font-semibold transition-all ${
                  filter === 'CLAIMED'
                    ? 'bg-primary-600 text-white shadow-lg'
                    : 'bg-beige-100 text-gray-700 hover:bg-beige-200'
                }`}
              >
                Réclamés ({stats.claimed})
              </button>
              <button
                onClick={() => setFilter('PENDING')}
                className={`px-4 py-2 rounded-lg font-semibold transition-all ${
                  filter === 'PENDING'
                    ? 'bg-secondary-600 text-white shadow-lg'
                    : 'bg-beige-100 text-gray-700 hover:bg-beige-200'
                }`}
              >
                En attente ({stats.pending})
              </button>
              <button
                onClick={() => setFilter('REJECTED')}
                className={`px-4 py-2 rounded-lg font-semibold transition-all ${
                  filter === 'REJECTED'
                    ? 'bg-red-600 text-white shadow-lg'
                    : 'bg-beige-100 text-gray-700 hover:bg-beige-200'
                }`}
              >
                Rejetés ({stats.rejected})
              </button>
            </div>
          </div>
        </div>

        <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">
            <h2 className="text-xl font-bold text-gray-800">Tous mes tickets ({filteredTickets.length})</h2>
          </div>
          <div className="p-6">
            {filteredTickets.length === 0 ? (
              <div className="text-center py-12">
                <div className="text-6xl mb-4">🎲</div>
                <p className="text-gray-600 mb-4">
                  {searchQuery || filter !== 'ALL'
                    ? 'Aucun ticket trouvé avec ces filtres'
                    : 'Vous n\'avez pas encore participé au jeu'}
                </p>
                {!searchQuery && filter === 'ALL' && (
                  <button
                    onClick={() => router.push(ROUTES.GAME)}
                    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>
                )}
              </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-gray-700 uppercase tracking-wider">
                        Code Ticket
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Gain
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Statut
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Date de participation
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Date de réclamation
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-beige-200">
                    {filteredTickets.map((ticket) => (
                      <TicketTableRow key={ticket.id} ticket={ticket} showClaimedDate />
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
