'use client';

import { useState, useEffect } from 'react';
import { getAllBookings, getAllUsers } from '@/lib/api/admin';

interface Document {
  id: string;
  fileName: string;
  filePath: string;
  type: string;
  mimeType: string;
  size: number;
  uploadedAt?: Date;
  // Legacy fields for compatibility
  name?: string;
  url?: string;
}

interface Booking {
  id: string;
  bookingNumber?: string;
  bookingId?: string;
  type?: string;
  userId: string;
  organizationId: string;
  origin?: string;
  destination?: string;
  carrierName?: string;
  documents: Document[];
  requestedAt?: string;
  status: string;
}

interface DocumentWithBooking extends Document {
  bookingId: string;
  quoteNumber: string;
  userId: string;
  userName?: string;
  organizationId: string;
  route: string;
  status: string;
  fileName?: string;
  fileType?: string;
}

export default function AdminDocumentsPage() {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [documents, setDocuments] = useState<DocumentWithBooking[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterUserId, setFilterUserId] = useState('all');
  const [filterQuoteNumber, setFilterQuoteNumber] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  // Helper function to get formatted quote number
  const getQuoteNumber = (booking: Booking): string => {
    if (booking.type === 'csv') {
      return `#${booking.bookingId || booking.id.slice(0, 8).toUpperCase()}`;
    }
    return booking.bookingNumber || `#${booking.id.slice(0, 8).toUpperCase()}`;
  };

  // Extract filename from MinIO URL
  const extractFileName = (url: string): string => {
    try {
      const urlObj = new URL(url);
      const pathname = urlObj.pathname;
      const parts = pathname.split('/');
      const fileName = parts[parts.length - 1];
      return decodeURIComponent(fileName);
    } catch {
      return 'document';
    }
  };

  // Get file extension and type
  const getFileType = (fileName: string): string => {
    const ext = fileName.split('.').pop()?.toLowerCase() || '';
    const typeMap: Record<string, string> = {
      pdf: 'PDF',
      doc: 'Word',
      docx: 'Word',
      xls: 'Excel',
      xlsx: 'Excel',
      jpg: 'Image',
      jpeg: 'Image',
      png: 'Image',
      gif: 'Image',
      txt: 'Text',
      csv: 'CSV',
    };
    return typeMap[ext] || ext.toUpperCase();
  };

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

  const fetchBookingsAndDocuments = async () => {
    try {
      setLoading(true);
      const response = await getAllBookings();
      const allBookings = response.bookings || [];
      setBookings(allBookings);

      // Extract all documents from all bookings
      const allDocuments: DocumentWithBooking[] = [];
      const userIds = new Set<string>();

      allBookings.forEach((booking: Booking) => {
        userIds.add(booking.userId);
        if (booking.documents && booking.documents.length > 0) {
          booking.documents.forEach((doc: Document) => {
            // Debug: Log document structure
            console.log('Document structure:', doc);

            // Use the correct field names from the backend
            const actualFileName = doc.fileName || doc.name || 'document';
            const actualFilePath = doc.filePath || doc.url || '';
            const actualMimeType = doc.mimeType || doc.type || '';

            console.log('Extracted:', {
              fileName: actualFileName,
              filePath: actualFilePath,
              mimeType: actualMimeType,
            });

            // Extract clean file type from mimeType or fileName
            let fileType = '';
            if (actualMimeType.includes('/')) {
              // It's a MIME type like "application/pdf"
              const parts = actualMimeType.split('/');
              fileType = getFileType(parts[1]);
            } else {
              // It's already a type or we extract from filename
              fileType = getFileType(actualFileName);
            }

            allDocuments.push({
              ...doc,
              bookingId: booking.id,
              quoteNumber: getQuoteNumber(booking),
              userId: booking.userId,
              organizationId: booking.organizationId,
              route: `${booking.origin || 'N/A'} → ${booking.destination || 'N/A'}`,
              status: booking.status,
              fileName: actualFileName,
              filePath: actualFilePath,
              fileType: fileType,
            });
          });
        }
      });

      // Fetch user names using the API client
      try {
        const usersData = await getAllUsers();
        console.log('Users data:', usersData);

        if (usersData && usersData.users) {
          const usersMap = new Map(
            usersData.users.map((u: any) => {
              const fullName = `${u.firstName || ''} ${u.lastName || ''}`.trim();
              return [u.id, fullName || u.email || u.id.substring(0, 8)];
            })
          );

          console.log('Users map:', usersMap);

          // Enrich documents with user names
          allDocuments.forEach(doc => {
            const userName = usersMap.get(doc.userId);
            doc.userName = userName || doc.userId.substring(0, 8) + '...';
            console.log(`User ${doc.userId} mapped to: ${doc.userName}`);
          });
        }
      } catch (userError) {
        console.error('Failed to fetch user names:', userError);
        // If user fetch fails, keep the userId as fallback
        allDocuments.forEach(doc => {
          doc.userName = doc.userId.substring(0, 8) + '...';
        });
      }

      setDocuments(allDocuments);
      setError(null);
    } catch (err: any) {
      setError(err.message || 'Failed to load documents');
    } finally {
      setLoading(false);
    }
  };

  // Get unique users for filter (with names)
  const uniqueUsers = Array.from(
    new Map(
      documents.map(doc => [doc.userId, { id: doc.userId, name: doc.userName || doc.userId.substring(0, 8) + '...' }])
    ).values()
  );

  // Filter documents
  const filteredDocuments = documents.filter(doc => {
    const matchesSearch = searchTerm === '' ||
      (doc.fileName && doc.fileName.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (doc.name && doc.name.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (doc.type && doc.type.toLowerCase().includes(searchTerm.toLowerCase())) ||
      doc.route.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesUser = filterUserId === 'all' || doc.userId === filterUserId;

    const matchesQuote = filterQuoteNumber === '' ||
      doc.quoteNumber.toLowerCase().includes(filterQuoteNumber.toLowerCase());

    return matchesSearch && matchesUser && matchesQuote;
  });

  // Pagination
  const totalPages = Math.ceil(filteredDocuments.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedDocuments = filteredDocuments.slice(startIndex, endIndex);

  // Reset to page 1 when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, filterUserId, filterQuoteNumber]);

  const getDocumentIcon = (type: string) => {
    const typeLower = type.toLowerCase();
    const icons: Record<string, string> = {
      'application/pdf': '📄',
      'image/jpeg': '🖼️',
      'image/png': '🖼️',
      'image/jpg': '🖼️',
      pdf: '📄',
      jpeg: '🖼️',
      jpg: '🖼️',
      png: '🖼️',
      gif: '🖼️',
      image: '🖼️',
      word: '📝',
      doc: '📝',
      docx: '📝',
      excel: '📊',
      xls: '📊',
      xlsx: '📊',
      csv: '📊',
      text: '📄',
      txt: '📄',
    };
    return icons[typeLower] || '📎';
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      pending: 'bg-yellow-100 text-yellow-800',
      accepted: 'bg-green-100 text-green-800',
      rejected: 'bg-red-100 text-red-800',
      cancelled: 'bg-gray-100 text-gray-800',
    };
    return colors[status.toLowerCase()] || 'bg-gray-100 text-gray-800';
  };

  const handleDownload = async (url: string, fileName: string) => {
    try {
      // Try direct download first
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.target = '_blank';
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // If direct download doesn't work, try fetch with blob
      setTimeout(async () => {
        try {
          const response = await fetch(url, {
            mode: 'cors',
            credentials: 'include',
          });

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          const blob = await response.blob();
          const blobUrl = window.URL.createObjectURL(blob);
          const link2 = document.createElement('a');
          link2.href = blobUrl;
          link2.download = fileName;
          document.body.appendChild(link2);
          link2.click();
          document.body.removeChild(link2);
          window.URL.revokeObjectURL(blobUrl);
        } catch (fetchError) {
          console.error('Fetch download failed:', fetchError);
        }
      }, 100);
    } catch (error) {
      console.error('Error downloading file:', error);
      alert(`Erreur lors du téléchargement du document: ${error instanceof Error ? error.message : 'Erreur inconnue'}`);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Chargement des documents...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Gestion des Documents</h1>
          <p className="mt-1 text-sm text-gray-500">
            Liste de tous les documents des devis CSV
          </p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-sm text-gray-500">Total Documents</div>
          <div className="text-2xl font-bold text-gray-900">{documents.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-sm text-gray-500">Devis avec Documents</div>
          <div className="text-2xl font-bold text-blue-600">
            {bookings.filter(b => b.documents && b.documents.length > 0).length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-sm text-gray-500">Documents Filtrés</div>
          <div className="text-2xl font-bold text-green-600">{filteredDocuments.length}</div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Recherche
            </label>
            <input
              type="text"
              placeholder="Nom, type, route..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Numéro de Devis
            </label>
            <input
              type="text"
              placeholder="Ex: #F2CAD5E1"
              value={filterQuoteNumber}
              onChange={e => setFilterQuoteNumber(e.target.value)}
              className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Utilisateur
            </label>
            <select
              value={filterUserId}
              onChange={e => setFilterUserId(e.target.value)}
              className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
            >
              <option value="all">Tous les utilisateurs</option>
              {uniqueUsers.map(user => (
                <option key={user.id} value={user.id}>
                  {user.name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}

      {/* Documents Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Nom du Document
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Type
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Numéro de Devis
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Route
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Statut
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Utilisateur
              </th>
              <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                Télécharger
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {paginatedDocuments.length === 0 ? (
              <tr>
                <td colSpan={7} className="px-6 py-12 text-center text-gray-500">
                  Aucun document trouvé
                </td>
              </tr>
            ) : (
              paginatedDocuments.map((doc, index) => (
                <tr key={`${doc.bookingId}-${index}`} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div className="text-sm font-medium text-gray-900">
                      {doc.fileName || doc.name}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      <span className="text-2xl mr-2">{getDocumentIcon(doc.fileType || doc.type)}</span>
                      <div className="text-xs text-gray-500">{doc.fileType || doc.type}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{doc.quoteNumber}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-900">{doc.route}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(doc.status)}`}>
                      {doc.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-900">
                      {doc.userName || doc.userId.substring(0, 8) + '...'}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-center">
                    <button
                      onClick={() => handleDownload(doc.filePath || doc.url || '', doc.fileName || doc.name || 'document')}
                      className="inline-flex items-center px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors"
                    >
                      <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                      </svg>
                      Télécharger
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>

        {/* Pagination Controls */}
        {filteredDocuments.length > 0 && (
          <div className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div className="flex-1 flex justify-between sm:hidden">
              <button
                onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                disabled={currentPage === 1}
                className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Précédent
              </button>
              <button
                onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                disabled={currentPage === totalPages}
                className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Suivant
              </button>
            </div>
            <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
              <div>
                <p className="text-sm text-gray-700">
                  Affichage de <span className="font-medium">{startIndex + 1}</span> à{' '}
                  <span className="font-medium">{Math.min(endIndex, filteredDocuments.length)}</span> sur{' '}
                  <span className="font-medium">{filteredDocuments.length}</span> résultats
                </p>
              </div>
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <label className="text-sm text-gray-700">Par page:</label>
                  <select
                    value={itemsPerPage}
                    onChange={(e) => {
                      setItemsPerPage(Number(e.target.value));
                      setCurrentPage(1);
                    }}
                    className="border border-gray-300 rounded-md px-2 py-1 text-sm"
                  >
                    <option value={5}>5</option>
                    <option value={10}>10</option>
                    <option value={25}>25</option>
                    <option value={50}>50</option>
                    <option value={100}>100</option>
                  </select>
                </div>
                <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                  <button
                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                    disabled={currentPage === 1}
                    className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <span className="sr-only">Précédent</span>
                    <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  </button>

                  {/* Page numbers */}
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    let pageNum;
                    if (totalPages <= 5) {
                      pageNum = i + 1;
                    } else if (currentPage <= 3) {
                      pageNum = i + 1;
                    } else if (currentPage >= totalPages - 2) {
                      pageNum = totalPages - 4 + i;
                    } else {
                      pageNum = currentPage - 2 + i;
                    }

                    return (
                      <button
                        key={pageNum}
                        onClick={() => setCurrentPage(pageNum)}
                        className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                          currentPage === pageNum
                            ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                            : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
                        }`}
                      >
                        {pageNum}
                      </button>
                    );
                  })}

                  <button
                    onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                    disabled={currentPage === totalPages}
                    className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <span className="sr-only">Suivant</span>
                    <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clipRule="evenodd" />
                    </svg>
                  </button>
                </nav>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
