'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/hooks';
import { Card, EmptyState } from '@/components/ui';
import { Loading } from '@/components/ui/Loading';
import { apiFetch } from '@/hooks/useApi';
import toast from 'react-hot-toast';
import {
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  User,
  Gift,
  RefreshCw,
} 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 apiFetch<{ 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 getStatusBadge = (status: string) => {
    const badges = {
      PENDING: (
        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
          <Clock className="w-4 h-4 mr-1" />
          En attente
        </span>
      ),
      CLAIMED: (
        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
          <CheckCircle className="w-4 h-4 mr-1" />
          Validé
        </span>
      ),
      REJECTED: (
        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800">
          <XCircle className="w-4 h-4 mr-1" />
          Rejeté
        </span>
      ),
    };
    return badges[status as keyof typeof badges] || badges.PENDING;
  };

  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 max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold mb-2 flex items-center gap-3">
          <Calendar className="w-10 h-10 text-purple-600" />
          Historique des Validations
        </h1>
        <p className="text-gray-600">
          Consultez l'historique de vos validations de tickets
        </p>
      </div>

      {/* Statistics Cards */}
      <div className="grid md:grid-cols-3 gap-6 mb-6">
        <Card className="p-6 bg-gradient-to-br from-blue-50 to-blue-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Total traités</p>
              <p className="text-3xl font-bold text-blue-600 mt-2">{stats.total}</p>
            </div>
            <div className="text-4xl">📊</div>
          </div>
        </Card>

        <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Validés</p>
              <p className="text-3xl font-bold text-green-600 mt-2">{stats.claimed}</p>
            </div>
            <div className="text-4xl">✅</div>
          </div>
        </Card>

        <Card className="p-6 bg-gradient-to-br from-red-50 to-red-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Rejetés</p>
              <p className="text-3xl font-bold text-red-600 mt-2">{stats.rejected}</p>
            </div>
            <div className="text-4xl">❌</div>
          </div>
        </Card>
      </div>

      {/* Filters */}
      <Card className="p-4 mb-6">
        <div className="flex items-center justify-between">
          <div className="flex gap-2">
            <button
              onClick={() => setFilter('ALL')}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                filter === 'ALL'
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              Tous ({history.length})
            </button>
            <button
              onClick={() => setFilter('CLAIMED')}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                filter === 'CLAIMED'
                  ? 'bg-green-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              Validés ({stats.claimed})
            </button>
            <button
              onClick={() => setFilter('REJECTED')}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                filter === 'REJECTED'
                  ? 'bg-red-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              Rejetés ({stats.rejected})
            </button>
          </div>

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

      {/* History List */}
      <Card className="p-6">
        {filteredHistory.length === 0 ? (
          <EmptyState
            icon="📝"
            title="Aucun ticket dans l'historique"
            message={filter === 'ALL'
              ? 'Vous n\'avez pas encore validé de tickets'
              : `Aucun ticket ${filter === 'CLAIMED' ? 'validé' : 'rejeté'}`}
          />
        ) : (
          <div className="space-y-4">
            {filteredHistory.map((ticket) => (
              <div
                key={ticket.id}
                className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-3">
                      <span className="font-mono font-bold text-lg text-gray-900">
                        {ticket.code}
                      </span>
                      {getStatusBadge(ticket.status)}
                    </div>

                    <div className="grid md:grid-cols-2 gap-4 mb-3">
                      <div className="flex items-start gap-2">
                        <User className="w-5 h-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm font-medium text-gray-600">Client</p>
                          <p className="text-sm 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-2">
                        <Gift className="w-5 h-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm font-medium text-gray-600">Lot</p>
                          <p className="text-sm text-gray-900">{ticket.prize_name}</p>
                          <p className="text-xs text-gray-500">{ticket.prize_value}€</p>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 text-xs text-gray-500">
                      <div className="flex items-center gap-1">
                        <Calendar className="w-3 h-3" />
                        <span>
                          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>
                    </div>

                    {ticket.rejection_reason && (
                      <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
                        <p className="text-sm font-medium 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>
        )}
      </Card>
    </div>
  );
}
