'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  ArrowLeft,
  Package,
  MapPin,
  Calendar,
  DollarSign,
  FileText,
  Download,
  CheckCircle,
  XCircle,
  Clock,
  Truck,
  Weight,
  Box
} from 'lucide-react';

interface BookingDocument {
  id: string;
  type: string;
  fileName: string;
  url: string;
}

interface BookingDetails {
  id: string;
  bookingId?: string;
  carrierName: string;
  carrierEmail: string;
  origin: string;
  destination: string;
  volumeCBM: number;
  weightKG: number;
  palletCount: number;
  priceUSD: number;
  priceEUR: number;
  primaryCurrency: string;
  transitDays: number;
  containerType: string;
  status: 'PENDING' | 'ACCEPTED' | 'REJECTED';
  documents: BookingDocument[];
  notes?: string;
  requestedAt: string;
  respondedAt?: string;
  rejectionReason?: string;
}

export default function CarrierBookingDetailPage() {
  const params = useParams();
  const router = useRouter();
  const bookingId = params.id as string;

  const [booking, setBooking] = useState<BookingDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchBookingDetails = async () => {
      try {
        const token = localStorage.getItem('carrier_access_token');

        if (!token) {
          setError('Non autorisé - veuillez vous connecter');
          setLoading(false);
          return;
        }

        const response = await fetch(`http://localhost:4000/api/v1/csv-bookings/${bookingId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

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

        const data = await response.json();
        setBooking(data);
      } catch (err) {
        console.error('Error fetching booking:', err);
        setError(err instanceof Error ? err.message : 'Erreur lors du chargement');
      } finally {
        setLoading(false);
      }
    };

    if (bookingId) {
      fetchBookingDetails();
    }
  }, [bookingId]);

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'ACCEPTED':
        return (
          <span className="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-green-100 text-green-800">
            <CheckCircle className="w-4 h-4 mr-2" />
            Accepté
          </span>
        );
      case 'REJECTED':
        return (
          <span className="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-red-100 text-red-800">
            <XCircle className="w-4 h-4 mr-2" />
            Refusé
          </span>
        );
      case 'PENDING':
        return (
          <span className="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-yellow-100 text-yellow-800">
            <Clock className="w-4 h-4 mr-2" />
            En attente
          </span>
        );
      default:
        return null;
    }
  };

  const formatPrice = (price: number, currency: string) => {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: currency,
    }).format(price);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('fr-FR', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (loading) {
    return (
      <div className="min-h-screen 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 détails...</p>
        </div>
      </div>
    );
  }

  if (error || !booking) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md">
          <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-gray-900 text-center mb-4">Erreur</h1>
          <p className="text-gray-600 text-center mb-6">{error || 'Réservation introuvable'}</p>
          <button
            onClick={() => router.push('/carrier/dashboard')}
            className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Retour au tableau de bord
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8 px-4">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <button
            onClick={() => router.push('/carrier/dashboard')}
            className="flex items-center text-blue-600 hover:text-blue-800 font-medium mb-4"
          >
            <ArrowLeft className="w-5 h-5 mr-2" />
            Retour au tableau de bord
          </button>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex justify-between items-start mb-4">
              <div>
                <h1 className="text-3xl font-bold text-gray-900 mb-2">
                  Détails de la Réservation
                </h1>
                <p className="text-gray-600">Référence: {booking.bookingId || booking.id}</p>
              </div>
              {getStatusBadge(booking.status)}
            </div>
          </div>
        </div>

        {/* Route Information */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <MapPin className="w-6 h-6 mr-2 text-blue-600" />
            Itinéraire
          </h2>

          <div className="flex items-center justify-between">
            <div className="text-center">
              <p className="text-sm text-gray-600 mb-1">Origine</p>
              <p className="text-2xl font-bold text-blue-600">{booking.origin}</p>
            </div>

            <div className="flex-1 mx-8">
              <div className="border-t-2 border-dashed border-gray-300 relative">
                <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white px-3">
                  <Truck className="w-6 h-6 text-gray-400" />
                </div>
              </div>
              <p className="text-center text-sm text-gray-600 mt-2">
                {booking.transitDays} jours de transit
              </p>
            </div>

            <div className="text-center">
              <p className="text-sm text-gray-600 mb-1">Destination</p>
              <p className="text-2xl font-bold text-blue-600">{booking.destination}</p>
            </div>
          </div>
        </div>

        {/* Shipment Details */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <Package className="w-6 h-6 mr-2 text-blue-600" />
            Détails de la Marchandise
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center mb-2">
                <Box className="w-5 h-5 text-gray-600 mr-2" />
                <p className="text-sm text-gray-600">Volume</p>
              </div>
              <p className="text-2xl font-bold text-gray-900">{booking.volumeCBM} CBM</p>
            </div>

            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center mb-2">
                <Weight className="w-5 h-5 text-gray-600 mr-2" />
                <p className="text-sm text-gray-600">Poids</p>
              </div>
              <p className="text-2xl font-bold text-gray-900">{booking.weightKG} kg</p>
            </div>

            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center mb-2">
                <Package className="w-5 h-5 text-gray-600 mr-2" />
                <p className="text-sm text-gray-600">Palettes</p>
              </div>
              <p className="text-2xl font-bold text-gray-900">{booking.palletCount || 'N/A'}</p>
            </div>

            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center mb-2">
                <Truck className="w-5 h-5 text-gray-600 mr-2" />
                <p className="text-sm text-gray-600">Type</p>
              </div>
              <p className="text-2xl font-bold text-gray-900">{booking.containerType}</p>
            </div>
          </div>
        </div>

        {/* Pricing */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <DollarSign className="w-6 h-6 mr-2 text-blue-600" />
            Prix
          </h2>

          <div className="flex items-center justify-between bg-green-50 rounded-lg p-6">
            <div>
              <p className="text-sm text-gray-600 mb-1">Prix total</p>
              <p className="text-4xl font-bold text-green-600">
                {formatPrice(
                  booking.primaryCurrency === 'USD' ? booking.priceUSD : booking.priceEUR,
                  booking.primaryCurrency
                )}
              </p>
            </div>

            {booking.primaryCurrency === 'USD' && booking.priceEUR > 0 && (
              <div className="text-right">
                <p className="text-sm text-gray-600 mb-1">Équivalent EUR</p>
                <p className="text-2xl font-semibold text-gray-700">
                  {formatPrice(booking.priceEUR, 'EUR')}
                </p>
              </div>
            )}

            {booking.primaryCurrency === 'EUR' && booking.priceUSD > 0 && (
              <div className="text-right">
                <p className="text-sm text-gray-600 mb-1">Équivalent USD</p>
                <p className="text-2xl font-semibold text-gray-700">
                  {formatPrice(booking.priceUSD, 'USD')}
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Documents */}
        {booking.documents && booking.documents.length > 0 && (
          <div className="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
              <FileText className="w-6 h-6 mr-2 text-blue-600" />
              Documents ({booking.documents.length})
            </h2>

            <div className="space-y-3">
              {booking.documents.map((doc) => (
                <div
                  key={doc.id}
                  className="flex items-center justify-between bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition-colors"
                >
                  <div className="flex items-center">
                    <FileText className="w-5 h-5 text-blue-600 mr-3" />
                    <div>
                      <p className="font-medium text-gray-900">{doc.fileName}</p>
                      <p className="text-sm text-gray-600">{doc.type}</p>
                    </div>
                  </div>
                  <a
                    href={doc.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    Télécharger
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Notes */}
        {booking.notes && (
          <div className="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">📝 Notes</h2>
            <p className="text-gray-700 whitespace-pre-wrap">{booking.notes}</p>
          </div>
        )}

        {/* Rejection Reason */}
        {booking.status === 'REJECTED' && booking.rejectionReason && (
          <div className="bg-red-50 border-2 border-red-200 rounded-lg p-6 mb-6">
            <h2 className="text-xl font-bold text-red-900 mb-4">❌ Raison du refus</h2>
            <p className="text-red-800">{booking.rejectionReason}</p>
          </div>
        )}

        {/* Timeline */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <Calendar className="w-6 h-6 mr-2 text-blue-600" />
            Chronologie
          </h2>

          <div className="space-y-4">
            <div className="flex items-start">
              <div className="w-2 h-2 bg-blue-600 rounded-full mt-2 mr-4"></div>
              <div>
                <p className="font-semibold text-gray-900">Demande reçue</p>
                <p className="text-sm text-gray-600">{formatDate(booking.requestedAt)}</p>
              </div>
            </div>

            {booking.respondedAt && (
              <div className="flex items-start">
                <div className={`w-2 h-2 rounded-full mt-2 mr-4 ${
                  booking.status === 'ACCEPTED' ? 'bg-green-600' : 'bg-red-600'
                }`}></div>
                <div>
                  <p className="font-semibold text-gray-900">
                    {booking.status === 'ACCEPTED' ? 'Acceptée' : 'Refusée'}
                  </p>
                  <p className="text-sm text-gray-600">{formatDate(booking.respondedAt)}</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Actions */}
        <div className="mt-6 flex gap-4">
          <button
            onClick={() => router.push('/carrier/dashboard')}
            className="flex-1 px-6 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 font-semibold"
          >
            Retour au tableau de bord
          </button>
          <button
            onClick={() => window.print()}
            className="flex-1 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold"
          >
            Imprimer les détails
          </button>
        </div>
      </div>
    </div>
  );
}
