'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/hooks';
import { StatusBadge } from '@/components/ui';
import { Loading } from '@/components/ui/Loading';
import { api } from '@/hooks/useApi';
import toast from 'react-hot-toast';
import {
  ClipboardList,
  Calendar,
  Gift,
  RefreshCw,
  CheckCircle,
  XCircle,
  BarChart3,
  User,
} from 'lucide-react';

interface HistoryTicket {
  id: string;
  code: string;
  status: string;
  played_at: string;
  claimed_at: string | null;
  validated_at: string | null;
  rejection_reason: string | null;
  user_email: string;
  user_name: string;
  prize_name: string;
  prize_value: string;
}

export default function EmployeeHistoryPage() {
  const { user, isAuthenticated } = useAuth();
  const [history, setHistory] = useState<HistoryTicket[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<'ALL' | 'CLAIMED' | 'REJECTED'>('ALL');

  useEffect(() => {
    if (isAuthenticated) {
      loadHistory();
    }
  }, [isAuthenticated]);

  const loadHistory = async () => {
    try {
      setLoading(true);
      const data = await api.get<{ data: HistoryTicket[] }>('/employee/history');
      setHistory(data.data || []);
    } catch (error: any) {
      console.error('Error loading history:', error);
      toast.error(error.message || 'Erreur lors du chargement de l\'historique');
    } finally {
      setLoading(false);
    }
  };


  const filteredHistory = history.filter((ticket) => {
    if (filter === 'ALL') return true;
    return ticket.status === filter;
  });

  const stats = {
    total: history.length,
    claimed: history.filter((t) => t.status === 'CLAIMED').length,
    rejected: history.filter((t) => t.status === 'REJECTED').length,
  };

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

  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-slate-600 to-slate-700 rounded-xl flex items-center justify-center shadow-lg">
            <ClipboardList className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-600 to-slate-700 bg-clip-text text-transparent">
              Historique des Validations
            </h1>
            <p className="text-gray-500">
              Consultez l'historique de vos validations de tickets
            </p>
          </div>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid md:grid-cols-3 gap-4 mb-6">
        <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.total}</p>
              <p className="text-sm text-blue-600">Total traités</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.claimed}</p>
              <p className="text-sm text-green-600">Validés</p>
            </div>
          </div>
        </div>

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

      {/* Filters & History List */}
      <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">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex gap-2 flex-wrap">
              <button
                onClick={() => setFilter('ALL')}
                className={`px-4 py-2 rounded-xl font-semibold transition-all ${
                  filter === 'ALL'
                    ? 'bg-gradient-to-r from-slate-600 to-slate-700 text-white shadow-md'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                Tous ({history.length})
              </button>
              <button
                onClick={() => setFilter('CLAIMED')}
                className={`px-4 py-2 rounded-xl font-semibold transition-all ${
                  filter === 'CLAIMED'
                    ? 'bg-gradient-to-r from-green-600 to-green-700 text-white shadow-md'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                Validés ({stats.claimed})
              </button>
              <button
                onClick={() => setFilter('REJECTED')}
                className={`px-4 py-2 rounded-xl font-semibold transition-all ${
                  filter === 'REJECTED'
                    ? 'bg-gradient-to-r from-red-600 to-red-700 text-white shadow-md'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                Rejetés ({stats.rejected})
              </button>
            </div>

            <button
              onClick={loadHistory}
              className="flex items-center gap-2 px-4 py-2 text-slate-700 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors font-medium"
            >
              <RefreshCw className="w-4 h-4" />
              Actualiser
            </button>
          </div>
        </div>

        <div className="p-6">
          {filteredHistory.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <Calendar className="w-8 h-8 text-gray-400" />
              </div>
              <p className="text-gray-800 font-semibold mb-1">Aucun ticket dans l'historique</p>
              <p className="text-sm text-gray-500">
                {filter === 'ALL'
                  ? 'Vous n\'avez pas encore validé de tickets'
                  : `Aucun ticket ${filter === 'CLAIMED' ? 'validé' : 'rejeté'}`}
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredHistory.map((ticket) => (
                <div
                  key={ticket.id}
                  className={`border-2 rounded-xl p-5 transition-all hover:shadow-md ${
                    ticket.status === 'REJECTED'
                      ? 'border-red-200 bg-red-50/30'
                      : 'border-gray-100 bg-white'
                  }`}
                >
                  <div className="flex flex-col lg:flex-row items-start justify-between gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-4">
                        <span className="font-mono font-bold text-lg bg-gray-100 px-3 py-1 rounded-lg text-gray-900">
                          {ticket.code}
                        </span>
                        <StatusBadge type="ticket" value={ticket.status} showIcon />
                      </div>

                      <div className="grid md:grid-cols-2 gap-6 mb-4">
                        <div className="flex items-start gap-3">
                          <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-full flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
                            {ticket.user_name.split(' ').map(n => n.charAt(0)).join('').slice(0, 2)}
                          </div>
                          <div>
                            <p className="text-xs font-medium text-gray-500 mb-1">Client</p>
                            <p className="text-sm font-semibold text-gray-900">{ticket.user_name}</p>
                            <p className="text-xs text-gray-500">{ticket.user_email}</p>
                          </div>
                        </div>

                        <div className="flex items-start gap-3">
                          <div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center flex-shrink-0">
                            <Gift className="w-5 h-5 text-purple-600" />
                          </div>
                          <div>
                            <p className="text-xs font-medium text-gray-500 mb-1">Lot</p>
                            <p className="text-sm font-semibold text-gray-900">{ticket.prize_name}</p>
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center gap-2 text-sm text-gray-500">
                        <Calendar className="w-4 h-4" />
                        <span>
                          {ticket.status === 'REJECTED' ? 'Rejeté' : 'Validé'} le{' '}
                          {ticket.validated_at
                            ? new Date(ticket.validated_at).toLocaleDateString('fr-FR', {
                                day: 'numeric',
                                month: 'long',
                                year: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit',
                              })
                            : 'N/A'}
                        </span>
                      </div>

                      {ticket.rejection_reason && (
                        <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-xl">
                          <p className="text-sm font-semibold text-red-800 mb-1">
                            Raison du rejet:
                          </p>
                          <p className="text-sm text-red-700">{ticket.rejection_reason}</p>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
