/**
 * Track & Trace Page
 *
 * Allows users to track their shipments by entering tracking numbers
 * and selecting the carrier. Redirects to carrier's tracking page.
 */

'use client';

import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

// Carrier tracking URLs - the tracking number will be appended
const carriers = [
  {
    id: 'maersk',
    name: 'Maersk',
    logo: '🚢',
    trackingUrl: 'https://www.maersk.com/tracking/',
    placeholder: 'Ex: MSKU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'msc',
    name: 'MSC',
    logo: '🛳️',
    trackingUrl: 'https://www.msc.com/track-a-shipment?query=',
    placeholder: 'Ex: MSCU1234567',
    description: 'Container, B/L or Booking number',
  },
  {
    id: 'cma-cgm',
    name: 'CMA CGM',
    logo: '⚓',
    trackingUrl: 'https://www.cma-cgm.com/ebusiness/tracking/search?SearchBy=Container&Reference=',
    placeholder: 'Ex: CMAU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'hapag-lloyd',
    name: 'Hapag-Lloyd',
    logo: '🔷',
    trackingUrl: 'https://www.hapag-lloyd.com/en/online-business/track/track-by-container-solution.html?container=',
    placeholder: 'Ex: HLCU1234567',
    description: 'Container number',
  },
  {
    id: 'cosco',
    name: 'COSCO',
    logo: '🌊',
    trackingUrl: 'https://elines.coscoshipping.com/ebusiness/cargoTracking?trackingNumber=',
    placeholder: 'Ex: COSU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'one',
    name: 'ONE (Ocean Network Express)',
    logo: '🟣',
    trackingUrl: 'https://ecomm.one-line.com/one-ecom/manage-shipment/cargo-tracking?trkNoParam=',
    placeholder: 'Ex: ONEU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'evergreen',
    name: 'Evergreen',
    logo: '🌲',
    trackingUrl: 'https://www.shipmentlink.com/servlet/TDB1_CargoTracking.do?BL=',
    placeholder: 'Ex: EGHU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'yangming',
    name: 'Yang Ming',
    logo: '🟡',
    trackingUrl: 'https://www.yangming.com/e-service/Track_Trace/track_trace_cargo_tracking.aspx?rdolType=CT&str=',
    placeholder: 'Ex: YMLU1234567',
    description: 'Container number',
  },
  {
    id: 'zim',
    name: 'ZIM',
    logo: '🔵',
    trackingUrl: 'https://www.zim.com/tools/track-a-shipment?consnumber=',
    placeholder: 'Ex: ZIMU1234567',
    description: 'Container or B/L number',
  },
  {
    id: 'hmm',
    name: 'HMM (Hyundai)',
    logo: '🟠',
    trackingUrl: 'https://www.hmm21.com/cms/business/ebiz/trackTrace/trackTrace/index.jsp?type=1&number=',
    placeholder: 'Ex: HDMU1234567',
    description: 'Container or B/L number',
  },
];

export default function TrackTracePage() {
  const [trackingNumber, setTrackingNumber] = useState('');
  const [selectedCarrier, setSelectedCarrier] = useState('');
  const [error, setError] = useState('');

  const handleTrack = () => {
    // Validation
    if (!trackingNumber.trim()) {
      setError('Veuillez entrer un numéro de tracking');
      return;
    }
    if (!selectedCarrier) {
      setError('Veuillez sélectionner un transporteur');
      return;
    }

    setError('');

    // Find the carrier and build the tracking URL
    const carrier = carriers.find(c => c.id === selectedCarrier);
    if (carrier) {
      const trackingUrl = carrier.trackingUrl + encodeURIComponent(trackingNumber.trim());
      // Open in new tab
      window.open(trackingUrl, '_blank', 'noopener,noreferrer');
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleTrack();
    }
  };

  const selectedCarrierData = carriers.find(c => c.id === selectedCarrier);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Track & Trace</h1>
        <p className="mt-2 text-gray-600">
          Suivez vos expéditions en temps réel. Entrez votre numéro de tracking et sélectionnez le transporteur.
        </p>
      </div>

      {/* Search Form */}
      <Card className="bg-white shadow-lg border-blue-100">
        <CardHeader>
          <CardTitle className="text-xl flex items-center gap-2">
            <span className="text-2xl">🔍</span>
            Rechercher une expédition
          </CardTitle>
          <CardDescription>
            Entrez votre numéro de conteneur, connaissement (B/L) ou référence de booking
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Carrier Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              Sélectionnez le transporteur
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
              {carriers.map(carrier => (
                <button
                  key={carrier.id}
                  type="button"
                  onClick={() => {
                    setSelectedCarrier(carrier.id);
                    setError('');
                  }}
                  className={`flex flex-col items-center justify-center p-3 rounded-lg border-2 transition-all ${
                    selectedCarrier === carrier.id
                      ? 'border-blue-500 bg-blue-50 shadow-md'
                      : 'border-gray-200 hover:border-blue-300 hover:bg-gray-50'
                  }`}
                >
                  <span className="text-2xl mb-1">{carrier.logo}</span>
                  <span className="text-xs font-medium text-gray-700 text-center">{carrier.name}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Tracking Number Input */}
          <div>
            <label htmlFor="tracking-number" className="block text-sm font-medium text-gray-700 mb-2">
              Numéro de tracking
            </label>
            <div className="flex gap-3">
              <div className="flex-1">
                <Input
                  id="tracking-number"
                  type="text"
                  value={trackingNumber}
                  onChange={e => {
                    setTrackingNumber(e.target.value.toUpperCase());
                    setError('');
                  }}
                  onKeyPress={handleKeyPress}
                  placeholder={selectedCarrierData?.placeholder || 'Ex: MSKU1234567'}
                  className="text-lg font-mono border-gray-300 focus:border-blue-500"
                />
                {selectedCarrierData && (
                  <p className="mt-1 text-xs text-gray-500">{selectedCarrierData.description}</p>
                )}
              </div>
              <Button
                onClick={handleTrack}
                className="bg-blue-600 hover:bg-blue-700 text-white px-6"
              >
                <span className="mr-2">🔍</span>
                Rechercher
              </Button>
            </div>
          </div>

          {/* Error Message */}
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-sm text-red-600">{error}</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Help Section */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card className="bg-white">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <span>📦</span>
              Numéro de conteneur
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600">
              Format standard: 4 lettres + 7 chiffres (ex: MSKU1234567).
              Le préfixe indique généralement le propriétaire du conteneur.
            </p>
          </CardContent>
        </Card>

        <Card className="bg-white">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <span>📋</span>
              Connaissement (B/L)
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600">
              Le numéro de Bill of Lading est fourni par le transporteur lors de la confirmation de booking.
              Format variable selon le carrier.
            </p>
          </CardContent>
        </Card>

        <Card className="bg-white">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <span>📝</span>
              Référence de booking
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600">
              Numéro de réservation attribué par le transporteur lors de la réservation initiale de l&apos;espace sur le navire.
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Info Box */}
      <div className="p-4 bg-blue-50 rounded-lg border border-blue-100">
        <div className="flex items-start gap-3">
          <span className="text-xl">💡</span>
          <div>
            <p className="text-sm font-medium text-blue-800">Comment fonctionne le suivi ?</p>
            <p className="text-sm text-blue-700 mt-1">
              Cette fonctionnalité vous redirige vers le site officiel du transporteur pour obtenir les informations
              de suivi les plus récentes. Les données affichées proviennent directement du système du transporteur.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
