'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 } = useAuth();
  const [stats, setStats] = useState({
    pendingTickets: 0,
    claimedToday: 0,
    totalClaimed: 0,
  });
  const [pendingTickets, setPendingTickets] = useState<PendingTicket[]>([]);
  const [loadingTickets, setLoadingTickets] = useState(true);

  useEffect(() => {
    loadPendingTickets();
    loadEmployeeStats();
  }, []);

  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 (!user) {
    return null;
  }

  return (
    <div className="min-h-full bg-gradient-to-br from-gray-50 via-white to-gray-50 p-8">
      {/* Welcome Section */}
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-[#2d5a3d] mb-2">
          Bonjour {user?.firstName} ! 👋
        </h1>
        <p className="text-gray-600 text-lg">
          Bienvenue dans votre espace employé. Voici un aperçu de votre activité.
        </p>
      </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-gray-100 hover:shadow-lg transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 mb-2">
                Tickets en attente
              </p>
              <p className="text-4xl font-bold text-yellow-500">
                {stats.pendingTickets}
              </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-500" 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-gray-100 hover:shadow-lg transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 mb-2">
                Réclamés aujourd'hui
              </p>
              <p className="text-4xl font-bold text-green-600">
                {stats.claimedToday}
              </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-gray-100 hover:shadow-lg transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 mb-2">
                Total réclamés
              </p>
              <p className="text-4xl font-bold text-blue-600">
                {stats.totalClaimed}
              </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 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Actions Title */}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800">Actions rapides</h2>
        <p className="text-gray-500">Accédez rapidement aux fonctionnalités principales</p>
      </div>

      {/* Quick Actions */}
      <div className="grid md:grid-cols-3 gap-6">
        <Link href="/employe/verification">
          <div className="bg-gradient-to-br from-green-600 to-green-800 text-white rounded-xl shadow-md p-6 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-bold mb-1">
                  Validation des gains
                </h3>
                <p className="text-white/80 text-sm">
                  Rechercher et valider les tickets
                </p>
              </div>
            </div>
          </div>
        </Link>

        <Link href="/employe/gains-client">
          <div className="bg-gradient-to-br from-purple-600 to-purple-800 text-white rounded-xl shadow-md p-6 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-bold mb-1">
                  Gains du Client
                </h3>
                <p className="text-white/80 text-sm">
                  Rechercher les gains d'un client
                </p>
              </div>
            </div>
          </div>
        </Link>

        <Link href="/employe/historique">
          <div className="bg-gradient-to-br from-slate-600 to-slate-800 text-white rounded-xl shadow-md p-6 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-bold mb-1">
                  Historique
                </h3>
                <p className="text-white/80 text-sm">
                  Consulter l'historique des validations
                </p>
              </div>
            </div>
          </div>
        </Link>
      </div>
    </div>
  );
}
