import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { z } from 'zod';
import { apiRequest } from '@/lib/queryClient';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { PharmacyMap } from '@/components/maps/PharmacyMap';
import { LocationPicker } from '@/components/maps/LocationPicker';
import { useGeolocation } from '@/hooks/useGeolocation';
import { geolocationService, type Location } from '@/services/geolocationService';
import { useToast } from '@/hooks/use-toast';
import { AlertTriangle, MapPin, Pill, User, Phone, Clock, CreditCard } from 'lucide-react';

const sosFormSchema = z.object({
  medicineName: z.string().min(1, 'Le nom du médicament est requis'),
  quantity: z.number().min(1, 'La quantité doit être d\'au moins 1'),
  notes: z.string().optional(),
  clientPhone: z.string().min(8, 'Numéro de téléphone requis'),
  clientName: z.string().min(1, 'Nom requis'),
  urgencyLevel: z.enum(['low', 'medium', 'high', 'critical']),
});

type SosFormData = z.infer<typeof sosFormSchema>;

interface Pharmacy {
  id: string;
  name: string;
  address: string;
  phone: string;
  lat: number;
  lng: number;
  isOpen: boolean;
  rating: number;
  distance?: number;
  duration?: number;
  hasStock?: boolean;
}

interface SosFormWithMapProps {
  onSuccess?: (orderId: string) => void;
  className?: string;
}

export function SosFormWithMap({ onSuccess, className = '' }: SosFormWithMapProps) {
  const [step, setStep] = useState(1);
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(null);
  const [selectedPharmacy, setSelectedPharmacy] = useState<Pharmacy | null>(null);
  const [estimatedCost, setEstimatedCost] = useState<number | null>(null);
  
  const { location: currentLocation, getCurrentLocation } = useGeolocation();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const form = useForm<SosFormData>({
    resolver: zodResolver(sosFormSchema),
    defaultValues: {
      medicineName: '',
      quantity: 1,
      notes: '',
      clientPhone: '',
      clientName: '',
      urgencyLevel: 'medium'
    }
  });

  const createOrderMutation = useMutation({
    mutationFn: async (data: SosFormData & { 
      lat: number; 
      lng: number; 
      address: string;
      pharmacyId?: string;
    }) => {
      const response = await apiRequest('POST', '/api/orders', data);
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "Commande SOS créée",
        description: `Commande #${data.id.substring(0, 8)} créée avec succès`,
      });
      
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
      onSuccess?.(data.id);
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Impossible de créer la commande",
        variant: "destructive",
      });
    },
  });

  // Estimate costs when medicine and location are selected
  useEffect(() => {
    const watchedValues = form.watch(['medicineName', 'quantity']);
    if (watchedValues[0] && watchedValues[1] && selectedLocation) {
      // Simulate cost calculation
      const baseCost = 5000; // Base medicine cost in FCFA
      const quantity = watchedValues[1] as number;
      const deliveryFee = selectedLocation ? 1500 : 2000;
      const serviceFee = 500;
      
      setEstimatedCost(baseCost * quantity + deliveryFee + serviceFee);
    }
  }, [form.watch, selectedLocation]);

  const handleLocationSelect = (location: Location) => {
    setSelectedLocation(location);
  };

  const handlePharmacySelect = (pharmacy: Pharmacy) => {
    setSelectedPharmacy(pharmacy);
  };

  const handleSubmit = async (data: SosFormData) => {
    if (!selectedLocation) {
      toast({
        title: "Position requise",
        description: "Veuillez sélectionner votre position de livraison",
        variant: "destructive",
      });
      return;
    }

    await createOrderMutation.mutateAsync({
      ...data,
      lat: selectedLocation.lat,
      lng: selectedLocation.lng,
      address: selectedLocation.address || 'Position personnalisée',
      pharmacyId: selectedPharmacy?.id
    });
  };

  const getUrgencyColor = (level: string) => {
    const colors = {
      'low': 'bg-green-500',
      'medium': 'bg-yellow-500', 
      'high': 'bg-orange-500',
      'critical': 'bg-red-500'
    };
    return colors[level as keyof typeof colors] || 'bg-gray-500';
  };

  const getUrgencyLabel = (level: string) => {
    const labels = {
      'low': 'Faible',
      'medium': 'Moyen',
      'high': 'Élevé', 
      'critical': 'Critique'
    };
    return labels[level as keyof typeof labels] || level;
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* Progress Steps */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            {[1, 2, 3, 4].map((stepNumber) => (
              <div key={stepNumber} className="flex items-center">
                <div
                  className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
                    step >= stepNumber
                      ? 'bg-red-500 text-white'
                      : 'bg-gray-200 text-gray-600'
                  }`}
                >
                  {stepNumber}
                </div>
                {stepNumber < 4 && (
                  <div
                    className={`w-16 h-1 mx-2 transition-colors ${
                      step > stepNumber ? 'bg-red-500' : 'bg-gray-200'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>
          <div className="flex justify-between mt-2 text-xs text-gray-600">
            <span>Médicament</span>
            <span>Position</span>
            <span>Pharmacie</span>
            <span>Confirmation</span>
          </div>
        </CardContent>
      </Card>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
          
          {/* Step 1: Medicine Information */}
          {step === 1 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-red-600">
                  <AlertTriangle className="h-5 w-5" />
                  Demande SOS - Informations du médicament
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <FormField
                  control={form.control}
                  name="medicineName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center gap-2">
                        <Pill className="h-4 w-4" />
                        Nom du médicament *
                      </FormLabel>
                      <FormControl>
                        <Input 
                          placeholder="Ex: Paracétamol, Amoxicilline..." 
                          {...field} 
                          data-testid="medicine-name"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="quantity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Quantité *</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          min="1"
                          placeholder="1"
                          {...field}
                          onChange={(e) => field.onChange(Number(e.target.value))}
                          data-testid="quantity"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="urgencyLevel"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Niveau d'urgence *</FormLabel>
                      <FormControl>
                        <div className="grid grid-cols-2 gap-2">
                          {(['low', 'medium', 'high', 'critical'] as const).map((level) => (
                            <Button
                              key={level}
                              type="button"
                              variant={field.value === level ? "default" : "outline"}
                              onClick={() => field.onChange(level)}
                              className={`${field.value === level ? getUrgencyColor(level) : ''}`}
                              data-testid={`urgency-${level}`}
                            >
                              {getUrgencyLabel(level)}
                            </Button>
                          ))}
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="notes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Notes additionnelles</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="Informations supplémentaires, posologie, allergies..."
                          rows={3}
                          {...field}
                          data-testid="notes"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="flex justify-end">
                  <Button 
                    type="button" 
                    onClick={() => setStep(2)}
                    disabled={!form.watch('medicineName') || !form.watch('quantity')}
                    data-testid="next-step-1"
                  >
                    Suivant: Position
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Step 2: Location Selection */}
          {step === 2 && (
            <div className="space-y-4">
              <LocationPicker
                onLocationSelect={handleLocationSelect}
                title="Adresse de livraison"
                description="Sélectionnez où vous souhaitez recevoir votre médicament"
                required={true}
              />

              <div className="flex justify-between">
                <Button 
                  type="button" 
                  variant="outline"
                  onClick={() => setStep(1)}
                >
                  Précédent
                </Button>
                <Button 
                  type="button" 
                  onClick={() => setStep(3)}
                  disabled={!selectedLocation}
                  data-testid="next-step-2"
                >
                  Suivant: Pharmacie
                </Button>
              </div>
            </div>
          )}

          {/* Step 3: Pharmacy Selection */}
          {step === 3 && selectedLocation && (
            <div className="space-y-4">
              <PharmacyMap
                medicineName={form.watch('medicineName')}
                userLocation={selectedLocation}
                onPharmacySelect={handlePharmacySelect}
                selectedPharmacyId={selectedPharmacy?.id}
                height="400px"
              />

              <div className="flex justify-between">
                <Button 
                  type="button" 
                  variant="outline"
                  onClick={() => setStep(2)}
                >
                  Précédent
                </Button>
                <Button 
                  type="button" 
                  onClick={() => setStep(4)}
                  data-testid="next-step-3"
                >
                  Suivant: Confirmation
                </Button>
              </div>
            </div>
          )}

          {/* Step 4: Confirmation */}
          {step === 4 && (
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle>Informations personnelles</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <FormField
                    control={form.control}
                    name="clientName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="flex items-center gap-2">
                          <User className="h-4 w-4" />
                          Nom complet *
                        </FormLabel>
                        <FormControl>
                          <Input 
                            placeholder="Votre nom complet"
                            {...field}
                            data-testid="client-name"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="clientPhone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="flex items-center gap-2">
                          <Phone className="h-4 w-4" />
                          Téléphone *
                        </FormLabel>
                        <FormControl>
                          <Input 
                            placeholder="+225 XX XX XX XX XX"
                            {...field}
                            data-testid="client-phone"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>

              {/* Order Summary */}
              <Card>
                <CardHeader>
                  <CardTitle>Résumé de la commande</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <div className="font-medium">Médicament:</div>
                      <div className="text-muted-foreground">{form.watch('medicineName')}</div>
                    </div>
                    <div>
                      <div className="font-medium">Quantité:</div>
                      <div className="text-muted-foreground">{form.watch('quantity')}</div>
                    </div>
                    <div>
                      <div className="font-medium">Urgence:</div>
                      <Badge className={getUrgencyColor(form.watch('urgencyLevel'))}>
                        {getUrgencyLabel(form.watch('urgencyLevel'))}
                      </Badge>
                    </div>
                    <div>
                      <div className="font-medium">Livraison:</div>
                      <div className="text-muted-foreground">{selectedLocation?.address}</div>
                    </div>
                  </div>

                  {selectedPharmacy && (
                    <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                      <div className="font-medium text-green-800">Pharmacie sélectionnée:</div>
                      <div className="text-sm text-green-700">{selectedPharmacy.name}</div>
                      <div className="text-xs text-green-600">{selectedPharmacy.address}</div>
                    </div>
                  )}

                  {estimatedCost && (
                    <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                      <div className="flex items-center gap-2 font-medium text-blue-800">
                        <CreditCard className="h-4 w-4" />
                        Coût estimé: {estimatedCost.toLocaleString()} FCFA
                      </div>
                      <div className="text-xs text-blue-600 mt-1">
                        Prix final confirmé après validation par la pharmacie
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              <div className="flex justify-between">
                <Button 
                  type="button" 
                  variant="outline"
                  onClick={() => setStep(3)}
                >
                  Précédent
                </Button>
                <Button 
                  type="submit"
                  disabled={createOrderMutation.isPending}
                  className="bg-red-500 hover:bg-red-600"
                  data-testid="submit-order"
                >
                  {createOrderMutation.isPending ? 'Création...' : 'Confirmer la commande SOS'}
                </Button>
              </div>
            </div>
          )}
        </form>
      </Form>
    </div>
  );
}