import { useParams } from 'wouter';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { OrderTimeline } from '@/components/order-timeline';
import { MapTracker } from '@/components/map-tracker';
import { OrderWithDetails } from '@shared/schema';
import { ORDER_STATUSES } from '@/lib/constants';
import {
  MapPin,
  RotateCcw,
  Phone,
  Pill,
  Store,
  Truck,
  Clock,
  DollarSign,
  User,
  AlertCircle
} from 'lucide-react';

export default function OrderTracking() {
  const { orderId } = useParams();

  // Fetch order details
  const { data: order, isLoading, error, refetch } = useQuery<OrderWithDetails>({
    queryKey: ['/api/orders', orderId],
    enabled: !!orderId,
    refetchInterval: 10000, // Refresh every 10 seconds for real-time updates
  });

  if (isLoading) {
    return (
      <div className="container mx-auto p-4">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">Chargement de la commande...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error || !order) {
    return (
      <div className="container mx-auto p-4">
        <Card className="max-w-md mx-auto">
          <CardContent className="text-center py-8">
            <AlertCircle className="h-16 w-16 mx-auto text-red-500 mb-4" />
            <h2 className="text-xl font-bold mb-2">Commande non trouvée</h2>
            <p className="text-muted-foreground mb-4">
              La commande #{orderId} n'existe pas ou n'est plus accessible.
            </p>
            <Button onClick={() => window.history.back()}>
              Retour
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const statusConfig = order.status ? ORDER_STATUSES[order.status] : ORDER_STATUSES.CREATED;
  const estimatedArrival = () => {
    if (order.status === 'DELIVERED') return 'Livré';
    if (order.status === 'PICKED_UP') return '8 min';
    if (order.status === 'COURIER_ASSIGNED') return '15 min';
    return 'Calcul...';
  };

  return (
    <div className="container mx-auto p-4 space-y-6" data-testid="order-tracking">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold text-primary flex items-center gap-2">
            <MapPin className="h-8 w-8" />
            Suivi de commande
          </h1>
          <p className="text-muted-foreground">
            Commande <span className="font-medium text-primary">#{order.id.slice(0, 8)}</span>
          </p>
        </div>
        
        <Button 
          onClick={() => refetch()} 
          variant="outline"
          data-testid="button-refresh-tracking"
        >
          <RotateCcw className="h-4 w-4 mr-2" />
          Actualiser
        </Button>
      </div>

      {/* Status Overview */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="text-center">
                <Badge className={`${statusConfig.color} text-white text-lg px-4 py-2`}>
                  {statusConfig.label}
                </Badge>
              </div>
              <div>
                <h2 className="text-xl font-bold">{order.medicineName}</h2>
                <p className="text-muted-foreground">
                  Quantité: {order.qty} • Créé le {order.createdAt ? new Date(order.createdAt).toLocaleDateString('fr-FR') : 'Date inconnue'}
                </p>
              </div>
            </div>
            
            <div className="text-center bg-primary text-white rounded-lg p-4">
              <div className="text-2xl font-bold">{estimatedArrival()}</div>
              <div className="text-sm opacity-90">Temps estimé</div>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Map & Timeline - Left Column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Map Tracker */}
          <MapTracker order={order} />
          
          {/* Order Timeline */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5" />
                Progression de la commande
              </CardTitle>
            </CardHeader>
            <CardContent>
              <OrderTimeline 
                currentStatus={order.status || 'CREATED'}
                events={order.events || []}
              />
            </CardContent>
          </Card>
        </div>

        {/* Order Details - Right Column */}
        <div className="space-y-6">
          {/* Order Summary */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Pill className="h-5 w-5" />
                Détails de la commande
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Médicament:</span>
                  <span className="font-medium">{order.medicineName}</span>
                </div>
                
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Quantité:</span>
                  <span className="font-medium">{order.qty} boîte(s)</span>
                </div>

                {order.pharmacy && (
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Pharmacie:</span>
                    <span className="font-medium">{order.pharmacy.name}</span>
                  </div>
                )}

                {order.courier && (
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Livreur:</span>
                    <span className="font-medium">{order.courier.user.name}</span>
                  </div>
                )}

                <div className="flex justify-between">
                  <span className="text-muted-foreground">Distance:</span>
                  <span className="font-medium">{order.distanceKm || 'Calcul...'} km</span>
                </div>
              </div>

              <hr />

              {/* Pricing Breakdown */}
              <div className="space-y-2">
                <h4 className="font-bold text-primary">Récapitulatif des frais</h4>
                
                <div className="space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Prix médicament:</span>
                    <span>{(order.medPriceTotal || 0).toLocaleString()} FCFA</span>
                  </div>
                  
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Frais de service:</span>
                    <span>{(order.serviceFee || 0).toLocaleString()} FCFA</span>
                  </div>
                  
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Livraison:</span>
                    <span>{(order.deliveryFee || 0).toLocaleString()} FCFA</span>
                  </div>
                </div>

                <hr />
                
                <div className="flex justify-between font-bold text-primary text-lg">
                  <span>Total payé:</span>
                  <span>{((order.medPriceTotal || 0) + (order.serviceFee || 0) + (order.deliveryFee || 0)).toLocaleString()} FCFA</span>
                </div>
              </div>

              {/* Contact Actions */}
              {order.courier && order.status && ['COURIER_ASSIGNED', 'PICKED_UP'].includes(order.status) && (
                <Button className="w-full" data-testid="button-call-courier">
                  <Phone className="h-4 w-4 mr-2" />
                  Contacter le livreur
                </Button>
              )}
            </CardContent>
          </Card>

          {/* Delivery Address */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="h-5 w-5" />
                Adresse de livraison
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <div className="flex items-start gap-2">
                  <User className="h-4 w-4 text-primary mt-1" />
                  <div>
                    <div className="font-medium">{order.client?.name || 'Client'}</div>
                    <div className="text-sm text-muted-foreground">{order.clientPhone || 'Téléphone non disponible'}</div>
                  </div>
                </div>
                
                <div className="flex items-start gap-2">
                  <MapPin className="h-4 w-4 text-primary mt-1" />
                  <div className="text-sm">{order.clientAddress || 'Adresse non disponible'}</div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Pharmacy Info */}
          {order.pharmacy && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Store className="h-5 w-5" />
                  Pharmacie
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div>
                    <div className="font-medium">{order.pharmacy.name}</div>
                    <div className="text-sm text-muted-foreground">{order.pharmacy.address}</div>
                  </div>
                  
                  {order.pharmacy.verified && (
                    <Badge variant="outline" className="text-green-600 border-green-300">
                      <Store className="h-3 w-3 mr-1" />
                      Pharmacie vérifiée
                    </Badge>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Receipt Download */}
          {order.status && ['DELIVERED', 'CLOSED'].includes(order.status) && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <DollarSign className="h-5 w-5" />
                  Reçu de transaction
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <p className="text-sm text-muted-foreground">
                    Votre commande a été livrée avec succès. 
                    Téléchargez votre reçu détaillé.
                  </p>
                  
                  <div className="flex gap-2">
                    <Button variant="outline" className="flex-1" data-testid="button-download-receipt">
                      Télécharger PDF
                    </Button>
                    <Button variant="outline" className="flex-1" data-testid="button-email-receipt">
                      Envoyer par email
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* Emergency Contact */}
      <Card className="bg-red-50 border-red-200">
        <CardContent className="p-4">
          <div className="flex items-center gap-3">
            <AlertCircle className="h-5 w-5 text-red-500" />
            <div className="flex-1">
              <h3 className="font-medium text-red-700">Problème avec votre commande ?</h3>
              <p className="text-sm text-red-600">
                Contactez notre support au <strong>+225 XX XX XX XX</strong> pour une assistance immédiate.
              </p>
            </div>
            <Button variant="outline" className="border-red-300 text-red-600 hover:bg-red-50">
              <Phone className="h-4 w-4 mr-2" />
              Appeler
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
