"use client";

import { useState, useEffect } from "react";
import { employeeService } from "@/services/employee.service";
import { Ticket } from "@/types";
import toast from "react-hot-toast";
import {
  Search,
  CheckCircle,
  XCircle,
  RefreshCw,
  Users,
  Clock,
  Ticket as TicketIcon,
  Gift,
} from "lucide-react";

export default function EmployeeVerificationPage() {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchCode, setSearchCode] = useState("");
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [validating, setValidating] = useState(false);
  const [rejectReason, setRejectReason] = useState("");
  const [showRejectInput, setShowRejectInput] = useState(false);

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

  const loadPendingTickets = async () => {
    try {
      setLoading(true);
      const data = await employeeService.getPendingTickets();
      // Trier par date décroissante (plus récent en premier)
      const sortedData = data.sort((a: Ticket, b: Ticket) => {
        const dateA = a.playedAt ? new Date(a.playedAt).getTime() : 0;
        const dateB = b.playedAt ? new Date(b.playedAt).getTime() : 0;
        return dateB - dateA;
      });
      setTickets(sortedData);
    } catch (error: any) {
      console.error("Error loading tickets:", error);
      toast.error("Erreur lors du chargement des tickets");
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    if (!searchCode.trim()) {
      toast.error("Veuillez entrer un code de ticket");
      return;
    }

    const ticket = tickets.find(
      (t) => t.code.toLowerCase() === searchCode.toLowerCase()
    );

    if (ticket) {
      setSelectedTicket(ticket);
      setShowModal(true);
      setSearchCode("");
    } else {
      toast.error("Ticket non trouvé ou déjà traité");
    }
  };

  const handleValidate = async () => {
    if (!selectedTicket) return;

    setValidating(true);
    try {
      await employeeService.validateTicket(selectedTicket.id, "APPROVE");
      toast.success("Ticket validé ! Le lot peut être remis au client.");
      setShowModal(false);
      setSelectedTicket(null);
      loadPendingTickets();
    } catch (error: any) {
      toast.error(error.message || "Erreur lors de la validation");
    } finally {
      setValidating(false);
    }
  };

  const handleReject = async () => {
    if (!selectedTicket) return;

    if (!rejectReason.trim()) {
      toast.error("Veuillez indiquer la raison du rejet");
      return;
    }

    setValidating(true);
    try {
      await employeeService.validateTicket(
        selectedTicket.id,
        "REJECT",
        rejectReason
      );
      toast.success("Ticket rejeté");
      setShowModal(false);
      setSelectedTicket(null);
      setShowRejectInput(false);
      setRejectReason("");
      loadPendingTickets();
    } catch (error: any) {
      toast.error(error.message || "Erreur lors du rejet");
    } finally {
      setValidating(false);
    }
  };


  if (loading) {
    return (
      <div className="p-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="h-32 bg-gray-200 rounded"></div>
        </div>
      </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-emerald-500 to-teal-600 rounded-xl flex items-center justify-center shadow-lg">
            <TicketIcon className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-emerald-600 to-teal-600 bg-clip-text text-transparent">
              Validation des Tickets
            </h1>
            <p className="text-gray-500">
              Scannez ou recherchez un code pour valider les lots gagnés
            </p>
          </div>
        </div>
      </div>

      {/* Search Section - Style blanc cassé */}
      <div className="bg-[#faf8f5] rounded-2xl p-6 mb-6 border border-gray-200">
        <div className="flex flex-col md:flex-row gap-4 items-center">
          <div className="flex-1 w-full">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Entrez le code du ticket (ex: TTABC123)"
                value={searchCode}
                onChange={(e) => setSearchCode(e.target.value.toUpperCase())}
                onKeyPress={(e) => e.key === "Enter" && handleSearch()}
                className="w-full pl-12 pr-4 py-3 bg-white border border-gray-200 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-transparent font-mono text-lg"
                maxLength={12}
              />
            </div>
          </div>
          <button
            onClick={handleSearch}
            className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl hover:from-emerald-700 hover:to-teal-700 transition-all font-semibold shadow-lg hover:shadow-xl"
          >
            <Search className="w-5 h-5" />
            Rechercher
          </button>
        </div>
      </div>


      {/* Table des tickets en attente */}
      <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 flex items-center justify-between bg-gradient-to-r from-gray-50 to-gray-100">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center">
              <Clock className="w-5 h-5 text-amber-600" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-gray-800">
                Lots en attente de remise
              </h2>
              <p className="text-sm text-gray-500">{tickets.length} ticket(s) en attente</p>
            </div>
          </div>
          <button
            onClick={loadPendingTickets}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-white text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-colors shadow-sm border border-gray-200"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            Actualiser
          </button>
        </div>

        <div className="overflow-x-auto">
          {tickets.length === 0 ? (
            <div className="text-center py-16">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-8 h-8 text-green-600" />
              </div>
              <p className="text-gray-900 font-medium text-lg mb-2">
                Aucun lot en attente
              </p>
              <p className="text-sm text-gray-500">
                Tous les lots ont été remis !
              </p>
            </div>
          ) : (
            <table className="min-w-full">
              <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                <tr>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                    Code Ticket
                  </th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                    Client
                  </th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                    Lot Gagné
                  </th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                    Date
                  </th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {tickets.map((ticket) => (
                  <tr key={ticket.id} className="hover:bg-gray-50 transition-colors">
                    {/* CODE TICKET */}
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gradient-to-br from-emerald-500 to-teal-500 rounded-lg flex items-center justify-center">
                          <TicketIcon className="w-5 h-5 text-white" />
                        </div>
                        <span className="text-sm font-mono font-semibold text-gray-900">
                          {ticket.code}
                        </span>
                      </div>
                    </td>

                    {/* CLIENT */}
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white text-xs font-bold">
                          {ticket.user ? `${ticket.user.firstName?.charAt(0) || ''}${ticket.user.lastName?.charAt(0) || ''}` : '?'}
                        </div>
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {ticket.user ? `${ticket.user.firstName} ${ticket.user.lastName}` : 'N/A'}
                          </div>
                          <div className="text-xs text-gray-500">
                            {ticket.user?.email || 'N/A'}
                          </div>
                        </div>
                      </div>
                    </td>

                    {/* LOT GAGNÉ */}
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2">
                        <Gift className="w-4 h-4 text-purple-500" />
                        <span className="text-sm font-medium text-gray-900">
                          {ticket.prize?.name || 'N/A'}
                        </span>
                      </div>
                    </td>

                    {/* DATE */}
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {ticket.playedAt
                        ? new Date(ticket.playedAt).toLocaleDateString('fr-FR', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit'
                          })
                        : '-'}
                    </td>

                    {/* ACTIONS */}
                    <td className="px-6 py-4 whitespace-nowrap">
                      <button
                        onClick={() => {
                          setSelectedTicket(ticket);
                          setShowModal(true);
                        }}
                        className="px-4 py-2 text-sm font-medium bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-lg hover:from-emerald-700 hover:to-teal-700 transition-colors"
                      >
                        Traiter
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Modal de validation */}
      {showModal && selectedTicket && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-hidden">
            <div className="bg-gradient-to-r from-emerald-600 to-teal-600 px-6 py-4">
              <div className="flex items-center justify-between">
                <h2 className="text-xl font-bold text-white">Détails du Ticket</h2>
                <button
                  onClick={() => {
                    setShowModal(false);
                    setSelectedTicket(null);
                    setShowRejectInput(false);
                    setRejectReason("");
                  }}
                  className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                >
                  <XCircle className="w-5 h-5" />
                </button>
              </div>
            </div>

            <div className="p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-200px)]">
              {/* Code et Statut */}
              <div className="flex items-center justify-between p-4 bg-gradient-to-r from-gray-50 to-gray-100 rounded-xl">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-gradient-to-br from-emerald-500 to-teal-500 rounded-xl flex items-center justify-center">
                    <TicketIcon className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-gray-500">Code ticket</p>
                    <p className="text-lg font-mono font-bold text-gray-900">{selectedTicket.code}</p>
                  </div>
                </div>
                <span className="px-3 py-1 bg-amber-100 text-amber-700 rounded-full text-sm font-medium">
                  En attente
                </span>
              </div>

              {/* Client Info */}
              <div className="p-4 bg-blue-50 rounded-xl border border-blue-100">
                <p className="text-xs text-blue-600 font-semibold mb-2 uppercase">Client</p>
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white font-bold">
                    {selectedTicket.user ? `${selectedTicket.user.firstName?.charAt(0) || ''}${selectedTicket.user.lastName?.charAt(0) || ''}` : '?'}
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">
                      {selectedTicket.user ? `${selectedTicket.user.firstName} ${selectedTicket.user.lastName}` : 'N/A'}
                    </p>
                    <p className="text-sm text-gray-500">{selectedTicket.user?.email || 'N/A'}</p>
                    {selectedTicket.user?.phone && (
                      <p className="text-sm text-gray-500">{selectedTicket.user.phone}</p>
                    )}
                  </div>
                </div>
              </div>

              {/* Lot gagné */}
              <div className="p-4 bg-purple-50 rounded-xl border border-purple-100">
                <p className="text-xs text-purple-600 font-semibold mb-2 uppercase">Lot à remettre</p>
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                    <Gift className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">{selectedTicket.prize?.name}</p>
                    <p className="text-sm text-gray-500">{selectedTicket.prize?.description}</p>
                  </div>
                </div>
              </div>

              {/* Date */}
              <div className="p-4 bg-gray-50 rounded-xl">
                <p className="text-xs text-gray-500 font-semibold mb-1 uppercase">Date de participation</p>
                <p className="text-sm font-medium text-gray-900">
                  {selectedTicket.playedAt
                    ? new Date(selectedTicket.playedAt).toLocaleDateString('fr-FR', {
                        day: 'numeric',
                        month: 'long',
                        year: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit'
                      })
                    : 'N/A'}
                </p>
              </div>

              {/* Reject Reason Input */}
              {showRejectInput && (
                <div className="p-4 bg-red-50 rounded-xl border border-red-100">
                  <label className="block text-sm font-medium text-red-700 mb-2">
                    Raison du rejet *
                  </label>
                  <textarea
                    value={rejectReason}
                    onChange={(e) => setRejectReason(e.target.value)}
                    placeholder="Ex: Ticket endommagé, code illisible..."
                    className="w-full px-4 py-2 border border-red-200 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent"
                    rows={3}
                  />
                </div>
              )}
            </div>

            {/* Actions */}
            <div className="px-6 py-4 bg-gray-50 border-t flex gap-3 justify-end">
              {!showRejectInput ? (
                <>
                  <button
                    onClick={() => {
                      setShowModal(false);
                      setSelectedTicket(null);
                    }}
                    disabled={validating}
                    className="px-4 py-2.5 bg-gray-200 text-gray-700 rounded-xl font-semibold hover:bg-gray-300 transition-colors"
                  >
                    Annuler
                  </button>
                  <button
                    onClick={() => setShowRejectInput(true)}
                    disabled={validating}
                    className="px-4 py-2.5 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition-colors flex items-center gap-2"
                  >
                    <XCircle className="w-4 h-4" />
                    Rejeter
                  </button>
                  <button
                    onClick={handleValidate}
                    disabled={validating}
                    className="px-4 py-2.5 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl font-semibold hover:from-emerald-700 hover:to-teal-700 transition-colors flex items-center gap-2"
                  >
                    <CheckCircle className="w-4 h-4" />
                    {validating ? "Validation..." : "Valider et Remettre"}
                  </button>
                </>
              ) : (
                <>
                  <button
                    onClick={() => {
                      setShowRejectInput(false);
                      setRejectReason("");
                    }}
                    disabled={validating}
                    className="px-4 py-2.5 bg-gray-200 text-gray-700 rounded-xl font-semibold hover:bg-gray-300 transition-colors"
                  >
                    Retour
                  </button>
                  <button
                    onClick={handleReject}
                    disabled={validating || !rejectReason.trim()}
                    className="px-4 py-2.5 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <XCircle className="w-4 h-4" />
                    {validating ? "Rejet..." : "Confirmer le Rejet"}
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
