import { Badge } from '@/components/ui/badge';
import { ORDER_STATUSES } from '@/lib/constants';
import { OrderEvent } from '@shared/schema';
import { 
  CheckCircle, 
  Clock, 
  Package, 
  Truck, 
  Store,
  User,
  AlertCircle
} from 'lucide-react';
import { cn } from '@/lib/utils';

interface OrderTimelineProps {
  currentStatus: keyof typeof ORDER_STATUSES;
  events?: OrderEvent[];
  className?: string;
}

const timelineSteps = [
  {
    key: 'CREATED',
    label: 'Commande créée',
    description: 'Demande SOS reçue et validée',
    icon: User,
  },
  {
    key: 'PHARMACY_CONFIRMED',
    label: 'Pharmacie confirmée',
    description: 'Stock validé par la pharmacie',
    icon: Store,
  },
  {
    key: 'COURIER_ASSIGNED',
    label: 'Livreur assigné',
    description: 'Livreur accepté la livraison',
    icon: Truck,
  },
  {
    key: 'PICKED_UP',
    label: 'Récupéré',
    description: 'Médicament récupéré à la pharmacie',
    icon: Package,
  },
  {
    key: 'DELIVERED',
    label: 'Livré',
    description: 'Remise au client',
    icon: CheckCircle,
  },
] as const;

export function OrderTimeline({ currentStatus, events = [], className }: OrderTimelineProps) {
  const currentStepIndex = timelineSteps.findIndex(step => step.key === currentStatus);

  const getStepStatus = (stepIndex: number) => {
    if (stepIndex < currentStepIndex) return 'completed';
    if (stepIndex === currentStepIndex) return 'active';
    return 'pending';
  };

  const getEventTime = (stepKey: string) => {
    const event = events.find(e => 
      e.event.includes(stepKey) || e.event === `STATUS_CHANGED_${stepKey}`
    );
    if (event && event.createdAt) {
      return new Date(event.createdAt).toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    return null;
  };

  return (
    <div className={cn("relative", className)} data-testid="order-timeline">
      {/* Timeline line */}
      <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-border" />
      
      <div className="space-y-6">
        {timelineSteps.map((step, index) => {
          const status = getStepStatus(index);
          const Icon = step.icon;
          const eventTime = getEventTime(step.key);
          
          return (
            <div key={step.key} className="relative flex items-start gap-4" data-testid={`timeline-step-${step.key}`}>
              {/* Timeline marker */}
              <div 
                className={cn(
                  "flex items-center justify-center w-8 h-8 rounded-full border-2 bg-background z-10",
                  status === 'completed' && "border-green-500 bg-green-500",
                  status === 'active' && "border-yellow-500 bg-yellow-500 animate-pulse",
                  status === 'pending' && "border-gray-300 bg-gray-100"
                )}
              >
                <Icon 
                  className={cn(
                    "h-4 w-4",
                    status === 'completed' && "text-white",
                    status === 'active' && "text-white",
                    status === 'pending' && "text-gray-400"
                  )} 
                />
              </div>
              
              {/* Timeline content */}
              <div className="flex-1 min-w-0 pb-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 
                    className={cn(
                      "font-medium",
                      status === 'completed' && "text-green-700",
                      status === 'active' && "text-yellow-700",
                      status === 'pending' && "text-gray-500"
                    )}
                  >
                    {step.label}
                  </h3>
                  
                  {status === 'completed' && (
                    <Badge variant="outline" className="text-green-600 border-green-300">
                      <CheckCircle className="h-3 w-3 mr-1" />
                      Complété
                    </Badge>
                  )}
                  
                  {status === 'active' && (
                    <Badge variant="outline" className="text-yellow-600 border-yellow-300">
                      <Clock className="h-3 w-3 mr-1" />
                      En cours
                    </Badge>
                  )}
                  
                  {status === 'pending' && (
                    <Badge variant="outline" className="text-gray-500 border-gray-300">
                      En attente
                    </Badge>
                  )}
                </div>
                
                <p className={cn(
                  "text-sm mb-1",
                  status === 'pending' ? "text-gray-500" : "text-muted-foreground"
                )}>
                  {step.description}
                </p>
                
                {eventTime && (
                  <p className={cn(
                    "text-xs",
                    status === 'completed' && "text-green-600",
                    status === 'active' && "text-yellow-600",
                    status === 'pending' && "text-gray-400"
                  )}>
                    {eventTime}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
