'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/hooks';
import { Card, EmptyState, StatusBadge } from '@/components/ui';
import { Loading } from '@/components/ui/Loading';
import { api } from '@/hooks/useApi';
import toast from 'react-hot-toast';
import {
  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 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="min-h-full bg-gradient-to-br from-gray-50 via-white to-gray-50 p-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-[#2d5a3d] mb-2">
          Historique des Validations
        </h1>
        <p className="text-gray-600 text-lg">
          Consultez l'historique de vos validations de tickets
        </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">Total traités</p>
              <p className="text-4xl font-bold text-blue-600">{stats.total}</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 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">Validés</p>
              <p className="text-4xl font-bold text-green-600">{stats.claimed}</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">Rejetés</p>
              <p className="text-4xl font-bold text-red-600">{stats.rejected}</p>
            </div>
            <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center">
              <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Filters & History List */}
      <div className="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden">
        <div className="px-6 py-5 border-b border-gray-100 bg-gradient-to-r from-gray-50 to-white">
          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <button
                onClick={() => setFilter('ALL')}
                className={`px-5 py-2.5 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-5 py-2.5 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-5 py-2.5 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-green-700 bg-green-50 hover:bg-green-100 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 items-start justify-between">
                    <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>
  );
}
