'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/hooks';
import { API_BASE_URL } from '@/utils/constants';
import Link from 'next/link';
import {
  LayoutDashboard,
  Clock,
  CheckCircle,
  BarChart3,
  Search,
  Gift,
  ClipboardList
} from 'lucide-react';

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="p-6">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center gap-3 mb-2">
          <div className="w-12 h-12 bg-gradient-to-br from-green-600 to-green-700 rounded-xl flex items-center justify-center shadow-lg">
            <LayoutDashboard className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-green-600 to-green-700 bg-clip-text text-transparent">
              Dashboard
            </h1>
            <p className="text-gray-500">
              Bonjour {user?.firstName}, bienvenue dans votre espace employé
            </p>
          </div>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid md:grid-cols-3 gap-4 mb-6">
        <div className="bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl p-4 border border-amber-200">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-amber-200 rounded-lg flex items-center justify-center">
              <Clock className="w-6 h-6 text-amber-600" />
            </div>
            <div>
              <p className="text-3xl font-bold text-amber-700">{stats.pendingTickets}</p>
              <p className="text-sm text-amber-600">En attente</p>
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-green-200 rounded-lg flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-3xl font-bold text-green-700">{stats.claimedToday}</p>
              <p className="text-sm text-green-600">Validés aujourd'hui</p>
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-blue-200 rounded-lg flex items-center justify-center">
              <BarChart3 className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-3xl font-bold text-blue-700">{stats.totalClaimed}</p>
              <p className="text-sm text-blue-600">Total validés</p>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-gray-50 to-gray-100">
          <h2 className="text-lg font-bold text-gray-800">Actions rapides</h2>
          <p className="text-sm text-gray-500">Accédez rapidement aux fonctionnalités principales</p>
        </div>

        <div className="p-6 grid md:grid-cols-3 gap-4">
          <Link href="/employe/verification">
            <div className="bg-gradient-to-br from-emerald-600 to-teal-600 text-white rounded-xl p-5 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                  <Search className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 className="text-lg 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-pink-600 text-white rounded-xl p-5 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                  <Gift className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 className="text-lg 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-700 text-white rounded-xl p-5 hover:shadow-xl transition-all hover:scale-[1.02] cursor-pointer">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                  <ClipboardList className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 className="text-lg 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>
    </div>
  );
}
