'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks';
import { Card } from '@/components/ui';
import { Loading } from '@/components/ui/Loading';
import { ROUTES, API_BASE_URL } from '@/utils/constants';
import toast from 'react-hot-toast';
import Link from 'next/link';

interface PendingTicket {
  id: string;
  code: string;
  status: string;
  played_at: string;
  user_email: string;
  user_name: string;
  user_phone: string;
  prize_name: string;
  prize_type: string;
  prize_value: string;
}

export default function EmployeDashboardPage() {
  const { user, isAuthenticated, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const [stats, setStats] = useState({
    pendingTickets: 0,
    claimedToday: 0,
    totalClaimed: 0,
  });
  const [pendingTickets, setPendingTickets] = useState<PendingTicket[]>([]);
  const [loadingTickets, setLoadingTickets] = useState(true);

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

    if (isAuthenticated && user?.role !== 'EMPLOYEE') {
      router.push(ROUTES.HOME);
      toast.error('Accès refusé : rôle employé requis');
      return;
    }

    if (isAuthenticated) {
      loadPendingTickets();
      loadEmployeeStats();
    }
  }, [authLoading, isAuthenticated, user, router]);

  const loadPendingTickets = async () => {
    try {
      setLoadingTickets(true);
      const token = localStorage.getItem('auth_token') || localStorage.getItem('token');
      const response = await fetch(
        `${API_BASE_URL}/employee/pending-tickets?limit=10`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (!response.ok) throw new Error('Erreur lors du chargement');

      const data = await response.json();
      setPendingTickets(data.data || []);
      setStats((prev) => ({
        ...prev,
        pendingTickets: data.pagination?.total || data.data?.length || 0,
      }));
    } catch (error: any) {
      console.error('Error loading pending tickets:', error);
    } finally {
      setLoadingTickets(false);
    }
  };

  const loadEmployeeStats = async () => {
    try {
      const token = localStorage.getItem('auth_token') || localStorage.getItem('token');
      const response = await fetch(
        `${API_BASE_URL}/employee/stats`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (!response.ok) throw new Error('Erreur lors du chargement des statistiques');

      const result = await response.json();
      const statsData = result.data;

      setStats((prev) => ({
        ...prev,
        claimedToday: parseInt(statsData.claimed_today) || 0,
        totalClaimed: parseInt(statsData.total_approved) || 0,
      }));
    } catch (error: any) {
      console.error('Error loading employee stats:', error);
    }
  };

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

  if (!isAuthenticated || user?.role !== 'EMPLOYEE') {
    return null;
  }

  return (
    <div className="py-8">
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-gray-900 mb-2">
          Tableau de bord employé
        </h1>
        <p className="text-gray-600">
          Bienvenue {user?.firstName}, voici un aperçu de votre activité
        </p>
      </div>

      {/* Statistics Cards */}
      <div className="grid md:grid-cols-3 gap-6 mb-8">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Tickets en attente
              </p>
              <p className="text-3xl font-bold text-yellow-600 mt-2">
                {stats.pendingTickets}
              </p>
            </div>
            <div className="text-4xl">⏳</div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Réclamés aujourd'hui
              </p>
              <p className="text-3xl font-bold text-green-600 mt-2">
                {stats.claimedToday}
              </p>
            </div>
            <div className="text-4xl">✅</div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Total réclamés
              </p>
              <p className="text-3xl font-bold text-blue-600 mt-2">
                {stats.totalClaimed}
              </p>
            </div>
            <div className="text-4xl">📊</div>
          </div>
        </Card>
      </div>

      {/* Quick Actions */}
      <div className="grid md:grid-cols-3 gap-6">
        <Link href="/employe/verification">
          <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer">
            <div className="flex items-center">
              <div className="text-5xl mr-4">🔍</div>
              <div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">
                  Validation des gains
                </h3>
                <p className="text-gray-600">
                  Rechercher et valider les tickets des clients
                </p>
              </div>
            </div>
          </Card>
        </Link>

        <Link href="/employe/gains-client">
          <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer">
            <div className="flex items-center">
              <div className="text-5xl mr-4">🎁</div>
              <div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">
                  Gains du Client
                </h3>
                <p className="text-gray-600">
                  Rechercher tous les gains d'un client
                </p>
              </div>
            </div>
          </Card>
        </Link>

        <Link href="/employe/historique">
          <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer">
            <div className="flex items-center">
              <div className="text-5xl mr-4">📜</div>
              <div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">
                  Historique
                </h3>
                <p className="text-gray-600">
                  Consulter l'historique des validations
                </p>
              </div>
            </div>
          </Card>
        </Link>
      </div>
    </div>
  );
}
