'use client';

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

interface Booking {
  id: string;
  bookingNumber?: string | null;
  type?: string;
  status: string;
  origin?: string;
  destination?: string;
  carrierName?: string;
  containerType: string;
  volumeCBM?: number;
  weightKG?: number;
  palletCount?: number;
  priceEUR?: number;
  priceUSD?: number;
  primaryCurrency?: string;
  createdAt?: string;
  requestedAt?: string;
  updatedAt?: string;
  organizationId?: string;
  userId?: string;
}

export default function AdminBookingsPage() {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filterStatus, setFilterStatus] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [validatingId, setValidatingId] = useState<string | null>(null);

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

  const handleValidateTransfer = async (bookingId: string) => {
    if (!window.confirm('Confirmer la réception du virement et activer ce booking ?')) return;
    setValidatingId(bookingId);
    try {
      await validateBankTransfer(bookingId);
      await fetchBookings();
    } catch (err: any) {
      setError(err.message || 'Erreur lors de la validation du virement');
    } finally {
      setValidatingId(null);
    }
  };

  const fetchBookings = async () => {
    try {
      setLoading(true);
      const response = await getAllBookings();
      setBookings(response.bookings || []);
      setError(null);
    } catch (err: any) {
      setError(err.message || 'Impossible de charger les réservations');
    } finally {
      setLoading(false);
    }
  };

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

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      PENDING_PAYMENT: 'Paiement en attente',
      PENDING_BANK_TRANSFER: 'Virement à valider',
      PENDING: 'En attente transporteur',
      ACCEPTED: 'Accepté',
      REJECTED: 'Rejeté',
      CANCELLED: 'Annulé',
    };
    return labels[status.toUpperCase()] || status;
  };

  const getShortId = (booking: Booking) => `#${booking.id.slice(0, 8).toUpperCase()}`;

  const filteredBookings = bookings
    .filter(booking => filterStatus === 'all' || booking.status.toLowerCase() === filterStatus)
    .filter(booking => {
      if (searchTerm === '') return true;
      const s = searchTerm.toLowerCase();
      return (
        booking.bookingNumber?.toLowerCase().includes(s) ||
        booking.id.toLowerCase().includes(s) ||
        booking.carrierName?.toLowerCase().includes(s) ||
        booking.origin?.toLowerCase().includes(s) ||
        booking.destination?.toLowerCase().includes(s) ||
        String(booking.palletCount || '').includes(s) ||
        String(booking.weightKG || '').includes(s) ||
        String(booking.volumeCBM || '').includes(s) ||
        booking.containerType?.toLowerCase().includes(s)
      );
    });

  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 réservations...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Gestion des réservations</h1>
        <p className="mt-1 text-sm text-gray-500">
          Toutes les réservations de la plateforme
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Total</div>
          <div className="text-2xl font-bold text-gray-900 mt-1">{bookings.length}</div>
        </div>
        <div className="bg-amber-50 rounded-lg shadow-sm border border-amber-200 p-4">
          <div className="text-xs text-amber-700 uppercase tracking-wide">Virements à valider</div>
          <div className="text-2xl font-bold text-amber-700 mt-1">
            {bookings.filter(b => b.status.toUpperCase() === 'PENDING_BANK_TRANSFER').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">En attente transporteur</div>
          <div className="text-2xl font-bold text-yellow-600 mt-1">
            {bookings.filter(b => b.status.toUpperCase() === 'PENDING').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Acceptées</div>
          <div className="text-2xl font-bold text-green-600 mt-1">
            {bookings.filter(b => b.status.toUpperCase() === 'ACCEPTED').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div className="text-xs text-gray-500 uppercase tracking-wide">Rejetées</div>
          <div className="text-2xl font-bold text-red-600 mt-1">
            {bookings.filter(b => b.status.toUpperCase() === 'REJECTED').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-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Recherche</label>
            <input
              type="text"
              placeholder="N° booking, transporteur, route, palettes, poids, CBM..."
              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 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Statut</label>
            <select
              value={filterStatus}
              onChange={e => setFilterStatus(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 text-sm"
            >
              <option value="all">Tous les statuts</option>
              <option value="pending_bank_transfer">Virement à valider</option>
              <option value="pending_payment">Paiement en attente</option>
              <option value="pending">En attente transporteur</option>
              <option value="accepted">Accepté</option>
              <option value="rejected">Rejeté</option>
              <option value="cancelled">Annulé</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 text-sm">
          {error}
        </div>
      )}

      {/* Bookings Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  N° Booking
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Route
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Cargo
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Transporteur
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Statut
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Date
                </th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredBookings.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-8 text-center text-sm text-gray-500">
                    Aucune réservation trouvée
                  </td>
                </tr>
              ) : (
                filteredBookings.map(booking => (
                  <tr key={booking.id} className="hover:bg-gray-50">
                    {/* N° Booking */}
                    <td className="px-4 py-4 whitespace-nowrap">
                      {booking.bookingNumber && (
                        <div className="text-sm font-semibold text-gray-900">{booking.bookingNumber}</div>
                      )}
                      <div className="text-xs text-gray-400 font-mono">{getShortId(booking)}</div>
                    </td>

                    {/* Route */}
                    <td className="px-4 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">
                        {booking.origin} → {booking.destination}
                      </div>
                    </td>

                    {/* Cargo */}
                    <td className="px-4 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {booking.containerType}
                        {booking.palletCount != null && (
                          <span className="ml-1 text-gray-500">· {booking.palletCount} pal.</span>
                        )}
                      </div>
                      <div className="text-xs text-gray-500 space-x-2">
                        {booking.weightKG != null && <span>{booking.weightKG.toLocaleString()} kg</span>}
                        {booking.volumeCBM != null && <span>{booking.volumeCBM} CBM</span>}
                      </div>
                    </td>

                    {/* Transporteur */}
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                      {booking.carrierName || '—'}
                    </td>

                    {/* Statut */}
                    <td className="px-4 py-4 whitespace-nowrap">
                      <span className={`px-2 py-0.5 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(booking.status)}`}>
                        {getStatusLabel(booking.status)}
                      </span>
                    </td>

                    {/* Date */}
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {new Date(booking.requestedAt || booking.createdAt || '').toLocaleDateString('fr-FR')}
                    </td>

                    {/* Actions */}
                    <td className="px-4 py-4 whitespace-nowrap text-right text-sm">
                      {booking.status.toUpperCase() === 'PENDING_BANK_TRANSFER' && (
                        <button
                          onClick={() => handleValidateTransfer(booking.id)}
                          disabled={validatingId === booking.id}
                          className="px-3 py-1 bg-green-600 text-white text-xs font-semibold rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          {validatingId === booking.id ? '...' : '✓ Valider virement'}
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
