import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { apiRequest } from '@/lib/queryClient';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { 
  Clock, 
  CheckCircle, 
  AlertCircle, 
  Truck, 
  Package, 
  XCircle,
  Loader2
} from 'lucide-react';

interface StatusUpdaterProps {
  orderId: string;
  currentStatus: string;
  userRole: 'client' | 'pharmacy' | 'courier' | 'admin';
  onStatusUpdate?: (newStatus: string) => void;
}

interface StatusOption {
  value: string;
  label: string;
  description: string;
  icon: React.ReactNode;
  allowedRoles: string[];
  requiresNote?: boolean;
}

const statusOptions: StatusOption[] = [
  {
    value: 'PHARMACY_CONFIRMED',
    label: 'Confirmer la commande',
    description: 'La pharmacie confirme avoir le médicament en stock',
    icon: <CheckCircle className="h-4 w-4 text-green-500" />,
    allowedRoles: ['pharmacy', 'admin']
  },
  {
    value: 'COURIER_ASSIGNED',
    label: 'Assigner un livreur',
    description: 'Un livreur a été assigné à cette commande',
    icon: <Truck className="h-4 w-4 text-blue-500" />,
    allowedRoles: ['admin']
  },
  {
    value: 'PICKED_UP',
    label: 'Commande récupérée',
    description: 'Le livreur a récupéré la commande en pharmacie',
    icon: <Package className="h-4 w-4 text-orange-500" />,
    allowedRoles: ['courier', 'admin']
  },
  {
    value: 'IN_TRANSIT',
    label: 'En cours de livraison',
    description: 'La commande est en route vers le client',
    icon: <Truck className="h-4 w-4 text-purple-500" />,
    allowedRoles: ['courier', 'admin']
  },
  {
    value: 'DELIVERED',
    label: 'Livraison terminée',
    description: 'La commande a été livrée avec succès',
    icon: <CheckCircle className="h-4 w-4 text-green-600" />,
    allowedRoles: ['courier', 'admin']
  },
  {
    value: 'CANCELLED',
    label: 'Annuler la commande',
    description: 'Annuler cette commande',
    icon: <XCircle className="h-4 w-4 text-red-500" />,
    allowedRoles: ['client', 'pharmacy', 'admin'],
    requiresNote: true
  }
];

export function StatusUpdater({ orderId, currentStatus, userRole, onStatusUpdate }: StatusUpdaterProps) {
  const [selectedStatus, setSelectedStatus] = useState('');
  const [note, setNote] = useState('');
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const updateStatusMutation = useMutation({
    mutationFn: async ({ status, note }: { status: string; note?: string }) => {
      const response = await apiRequest('POST', `/api/orders/${orderId}/status`, {
        status,
        note,
        userRole
      });
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "Statut mis à jour",
        description: `Commande ${orderId.substring(0, 8)} mise à jour`,
      });
      
      // Reset form
      setSelectedStatus('');
      setNote('');
      
      // Invalidate queries
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
      queryClient.invalidateQueries({ queryKey: [`/api/orders/${orderId}`] });
      
      // Notify parent component
      onStatusUpdate?.(selectedStatus);
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Impossible de mettre à jour le statut",
        variant: "destructive",
      });
    },
  });

  // Get available status options based on current status and user role
  const getAvailableStatuses = () => {
    const statusFlow: Record<string, string[]> = {
      'CREATED': ['PHARMACY_CONFIRMED', 'CANCELLED'],
      'PHARMACY_CONFIRMED': ['COURIER_ASSIGNED', 'CANCELLED'],
      'COURIER_ASSIGNED': ['PICKED_UP', 'CANCELLED'],
      'PICKED_UP': ['IN_TRANSIT', 'CANCELLED'],
      'IN_TRANSIT': ['DELIVERED', 'CANCELLED'],
      'DELIVERED': [],
      'CANCELLED': []
    };

    const allowedNextStatuses = statusFlow[currentStatus] || [];
    
    return statusOptions.filter(option => 
      allowedNextStatuses.includes(option.value) &&
      option.allowedRoles.includes(userRole)
    );
  };

  const handleStatusUpdate = async () => {
    if (!selectedStatus) return;
    
    const statusOption = statusOptions.find(option => option.value === selectedStatus);
    
    if (statusOption?.requiresNote && !note.trim()) {
      toast({
        title: "Note requise",
        description: "Veuillez ajouter une note pour cette action",
        variant: "destructive",
      });
      return;
    }

    updateStatusMutation.mutate({ 
      status: selectedStatus, 
      note: note.trim() || undefined 
    });
  };

  const availableStatuses = getAvailableStatuses();
  const selectedOption = statusOptions.find(option => option.value === selectedStatus);

  if (availableStatuses.length === 0) {
    return (
      <Card data-testid="status-updater-empty">
        <CardContent className="p-6">
          <div className="text-center">
            <Clock className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500">Aucune action disponible pour cette commande</p>
            <Badge variant="outline" className="mt-2">
              Statut actuel: {currentStatus}
            </Badge>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card data-testid="status-updater">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <AlertCircle className="h-5 w-5" />
          Mise à jour du statut
        </CardTitle>
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">Statut actuel:</span>
          <Badge variant="outline">{currentStatus}</Badge>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Status Selection */}
        <div>
          <label className="text-sm font-medium mb-2 block">
            Nouveau statut
          </label>
          <Select 
            value={selectedStatus} 
            onValueChange={setSelectedStatus}
            data-testid="status-select"
          >
            <SelectTrigger>
              <SelectValue placeholder="Sélectionner un nouveau statut" />
            </SelectTrigger>
            <SelectContent>
              {availableStatuses.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  <div className="flex items-center gap-2">
                    {option.icon}
                    <span>{option.label}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Status Description */}
        {selectedOption && (
          <div className="p-3 bg-blue-50 rounded-lg border">
            <p className="text-sm text-blue-700">
              {selectedOption.description}
            </p>
          </div>
        )}

        {/* Note Field */}
        {(selectedOption?.requiresNote || selectedStatus) && (
          <div>
            <label className="text-sm font-medium mb-2 block">
              Note {selectedOption?.requiresNote && <span className="text-red-500">*</span>}
            </label>
            <Textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="Ajouter une note (optionnel)"
              rows={3}
              data-testid="status-note"
            />
          </div>
        )}

        {/* Action Button */}
        <Button
          onClick={handleStatusUpdate}
          disabled={!selectedStatus || updateStatusMutation.isPending}
          className="w-full"
          data-testid="update-status-button"
        >
          {updateStatusMutation.isPending ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Mise à jour...
            </>
          ) : (
            <>
              {selectedOption?.icon}
              <span className="ml-2">Mettre à jour le statut</span>
            </>
          )}
        </Button>

        {/* Role Info */}
        <div className="text-xs text-muted-foreground text-center">
          Connecté en tant que: <Badge variant="secondary">{userRole}</Badge>
        </div>
      </CardContent>
    </Card>
  );
}