// components/staff/PdfVerificationModal.tsx
"use client";

import React, { useState, useEffect, useCallback } from "react";
import { X, ChevronLeft, ChevronRight, FileText, AlertCircle, CheckCircle, Download, ExternalLink } from "lucide-react";

type ContractPdf = {
  id: string;
  contractNumber?: string;
  employeeName?: string;
  pdfUrl?: string;
  hasError: boolean;
  errorMessage?: string;
};

type PdfVerificationModalProps = {
  isOpen: boolean;
  onClose: () => void;
  contracts: ContractPdf[];
  isLoading: boolean;
};

export default function PdfVerificationModal({
  isOpen,
  onClose,
  contracts,
  isLoading
}: PdfVerificationModalProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [pdfError, setPdfError] = useState(false);

  const currentContract = contracts[currentIndex];
  const hasContracts = contracts.length > 0;

  // Reset index when contracts change
  useEffect(() => {
    setCurrentIndex(0);
    setPdfError(false);
  }, [contracts]);

  // Keyboard navigation
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
        e.preventDefault();
        goToPrevious();
      } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
        e.preventDefault();
        goToNext();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onClose();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, currentIndex, contracts.length]);

  const goToPrevious = useCallback(() => {
    if (contracts.length === 0) return;
    setCurrentIndex(prev => prev > 0 ? prev - 1 : contracts.length - 1);
    setPdfError(false);
  }, [contracts.length]);

  const goToNext = useCallback(() => {
    if (contracts.length === 0) return;
    setCurrentIndex(prev => prev < contracts.length - 1 ? prev + 1 : 0);
    setPdfError(false);
  }, [contracts.length]);

  const goToIndex = useCallback((index: number) => {
    setCurrentIndex(index);
    setPdfError(false);
  }, []);

  const handlePdfError = useCallback(() => {
    setPdfError(true);
  }, []);

  const openPdfInNewTab = useCallback(() => {
    if (currentContract?.pdfUrl) {
      window.open(currentContract.pdfUrl, '_blank');
    }
  }, [currentContract?.pdfUrl]);

  const downloadPdf = useCallback(() => {
    if (currentContract?.pdfUrl) {
      const link = document.createElement('a');
      link.href = currentContract.pdfUrl;
      link.download = `contrat_${currentContract.contractNumber || currentContract.id}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }, [currentContract]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg w-full h-full max-w-7xl max-h-[95vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b bg-gray-50">
          <div className="flex items-center gap-3">
            <FileText className="size-5 text-blue-600" />
            <div>
              <h2 className="text-lg font-semibold">Vérification des PDFs</h2>
              {hasContracts && (
                <p className="text-sm text-gray-600">
                  {currentIndex + 1} sur {contracts.length} contrats
                </p>
              )}
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            {currentContract && !currentContract.hasError && currentContract.pdfUrl && (
              <>
                <button
                  onClick={downloadPdf}
                  className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                  title="Télécharger le PDF"
                >
                  <Download className="size-4" />
                </button>
                <button
                  onClick={openPdfInNewTab}
                  className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                  title="Ouvrir dans un nouvel onglet"
                >
                  <ExternalLink className="size-4" />
                </button>
              </>
            )}
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
            >
              <X className="size-5" />
            </button>
          </div>
        </div>

        <div className="flex flex-1 overflow-hidden">
          {/* Sidebar with contract list */}
          <div className="w-80 border-r bg-gray-50 flex flex-col">
            <div className="p-3 border-b bg-white">
              <h3 className="font-medium text-sm text-gray-700">Liste des contrats</h3>
            </div>
            
            <div className="flex-1 overflow-y-auto">
              {isLoading ? (
                <div className="p-4 text-center text-gray-500">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mx-auto mb-2"></div>
                  Chargement des PDFs...
                </div>
              ) : contracts.length === 0 ? (
                <div className="p-4 text-center text-gray-500">
                  <AlertCircle className="size-8 mx-auto mb-2 text-gray-400" />
                  <p className="text-sm">Aucun contrat sélectionné</p>
                </div>
              ) : (
                <div className="space-y-1 p-2">
                  {contracts.map((contract, index) => (
                    <button
                      key={contract.id}
                      onClick={() => goToIndex(index)}
                      className={`w-full text-left p-3 rounded-lg transition-colors ${
                        index === currentIndex
                          ? 'bg-blue-100 border border-blue-200'
                          : 'hover:bg-gray-100'
                      }`}
                    >
                      <div className="flex items-center gap-2">
                        <div className="flex-shrink-0">
                          {contract.hasError ? (
                            <AlertCircle className="size-4 text-red-500" />
                          ) : contract.pdfUrl ? (
                            <CheckCircle className="size-4 text-green-500" />
                          ) : (
                            <div className="size-4 rounded-full border-2 border-gray-300"></div>
                          )}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="font-medium text-sm truncate">
                            {contract.contractNumber || `Contrat ${index + 1}`}
                          </div>
                          <div className="text-xs text-gray-500 truncate">
                            {contract.employeeName || 'Nom non disponible'}
                          </div>
                          {contract.hasError && (
                            <div className="text-xs text-red-500 truncate">
                              {contract.errorMessage || 'Erreur PDF'}
                            </div>
                          )}
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* PDF Viewer */}
          <div className="flex-1 flex flex-col">
            {isLoading ? (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                  <p className="text-gray-600">Chargement des PDFs...</p>
                </div>
              </div>
            ) : !hasContracts ? (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center text-gray-500">
                  <FileText className="size-16 mx-auto mb-4 text-gray-300" />
                  <p className="text-lg font-medium mb-2">Aucun contrat sélectionné</p>
                  <p className="text-sm">Sélectionnez des contrats pour vérifier leurs PDFs</p>
                </div>
              </div>
            ) : currentContract?.hasError ? (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center text-red-500">
                  <AlertCircle className="size-16 mx-auto mb-4" />
                  <p className="text-lg font-medium mb-2">PDF non disponible</p>
                  <p className="text-sm">{currentContract.errorMessage || 'Le PDF de ce contrat n\'a pas pu être chargé'}</p>
                </div>
              </div>
            ) : pdfError ? (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center text-red-500">
                  <AlertCircle className="size-16 mx-auto mb-4" />
                  <p className="text-lg font-medium mb-2">Erreur de chargement</p>
                  <p className="text-sm">Impossible d'afficher ce PDF</p>
                  <button
                    onClick={openPdfInNewTab}
                    className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    Ouvrir dans un nouvel onglet
                  </button>
                </div>
              </div>
            ) : currentContract?.pdfUrl ? (
              <div className="flex-1 relative">
                <iframe
                  src={currentContract.pdfUrl}
                  className="w-full h-full border-0"
                  onError={handlePdfError}
                  title={`PDF du contrat ${currentContract.contractNumber || currentContract.id}`}
                />
              </div>
            ) : (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center text-gray-500">
                  <FileText className="size-16 mx-auto mb-4 text-gray-300" />
                  <p className="text-lg font-medium mb-2">PDF non généré</p>
                  <p className="text-sm">Ce contrat n'a pas encore de PDF généré</p>
                </div>
              </div>
            )}

            {/* Navigation controls */}
            {hasContracts && (
              <div className="border-t bg-gray-50 p-3">
                <div className="flex items-center justify-between">
                  <button
                    onClick={goToPrevious}
                    disabled={contracts.length <= 1}
                    className="flex items-center gap-2 px-3 py-2 bg-white border rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <ChevronLeft className="size-4" />
                    Précédent
                  </button>

                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-600">
                      {currentIndex + 1} / {contracts.length}
                    </span>
                    <div className="text-xs text-gray-500">
                      (Utilisez ← → pour naviguer)
                    </div>
                  </div>

                  <button
                    onClick={goToNext}
                    disabled={contracts.length <= 1}
                    className="flex items-center gap-2 px-3 py-2 bg-white border rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    Suivant
                    <ChevronRight className="size-4" />
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}