import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { LocationPicker } from '@/components/maps/LocationPicker';
import { Location } from '@/services/geolocation';
import { useToast } from '@/hooks/use-toast';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { apiRequest } from '@/lib/queryClient';
import { PRICING } from '@/lib/constants';
import { PaymentModal } from '@/components/payment-modal';
import { useAuth } from '@/contexts/AuthContext';
import { 
  Pill, 
  Phone, 
  MapPin, 
  Upload, 
  Calculator, 
  Ambulance,
  Loader2,
  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).max(10),
  clientPhone: z.string().min(8, 'Numéro de téléphone requis'),
  prescriptionFile: z.instanceof(File).optional(),
});

type SosFormData = z.infer<typeof sosFormSchema>;

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

export function SosForm({ onSuccess, className }: SosFormProps) {
  const { toast } = useToast();
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [estimatedTotal, setEstimatedTotal] = useState<number | null>(null);
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(null);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [currentOrderId, setCurrentOrderId] = useState<string | null>(null);

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

  const createSosMutation = useMutation({
    mutationFn: async (data: SosFormData & { clientLat: number; clientLng: number }) => {
      const formData = new FormData();
      
      // Add form fields
      Object.entries(data).forEach(([key, value]) => {
        if (key !== 'prescriptionFile' && value !== undefined) {
          formData.append(key, value.toString());
        }
      });

      // Add prescription file if present
      if (data.prescriptionFile) {
        formData.append('prescriptionFile', data.prescriptionFile);
      }

      const response = await apiRequest('POST', '/api/sos', data);
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "Demande SOS envoyée !",
        description: `Recherche de pharmacies à proximité... ID: ${data.orderId}`,
      });
      
      // Ouvrir le modal de paiement avec l'orderId
      setCurrentOrderId(data.orderId);
      setShowPaymentModal(true);
      
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
      onSuccess?.(data.orderId);
    },
    onError: (error) => {
      toast({
        title: "Erreur",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: SosFormData) => {
    if (!selectedLocation) {
      toast({
        title: "Position requise",
        description: "Veuillez sélectionner votre position sur la carte",
        variant: "destructive",
      });
      return;
    }

    createSosMutation.mutate({
      ...data,
      clientLat: selectedLocation.lat,
      clientLng: selectedLocation.lng,
    });
  };

  // Calculate estimated pricing
  const calculateEstimatedTotal = (distance: number = 2) => {
    const deliveryFee = Math.max(PRICING.DELIVERY_MIN, distance * PRICING.DELIVERY_PER_KM);
    const estimatedMedicinePrice = 1000; // Placeholder
    return estimatedMedicinePrice + PRICING.SERVICE_FEE + deliveryFee;
  };

  return (
    <Card className={className} data-testid="sos-form">
      <CardHeader className="text-center">
        <CardTitle className="flex items-center justify-center gap-2 text-primary">
          <Ambulance className="h-6 w-6 text-red-500" />
          Demande SOS
        </CardTitle>
        <p className="text-muted-foreground">
          Remplissez le formulaire pour une livraison d'urgence
        </p>
      </CardHeader>
      
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            {/* Medicine Name */}
            <FormField
              control={form.control}
              name="medicineName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-2">
                    <Pill className="h-4 w-4 text-primary" />
                    Nom du médicament *
                  </FormLabel>
                  <FormControl>
                    <Input 
                      placeholder="Ex: Paracétamol, Doliprane..." 
                      {...field}
                      data-testid="input-medicine-name"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              {/* Quantity */}
              <FormField
                control={form.control}
                name="quantity"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Quantité</FormLabel>
                    <Select 
                      value={field.value?.toString()} 
                      onValueChange={(value) => field.onChange(parseInt(value))}
                    >
                      <FormControl>
                        <SelectTrigger data-testid="select-quantity">
                          <SelectValue placeholder="1 boîte" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="1">1 boîte</SelectItem>
                        <SelectItem value="2">2 boîtes</SelectItem>
                        <SelectItem value="3">3 boîtes</SelectItem>
                        <SelectItem value="4">4 boîtes</SelectItem>
                        <SelectItem value="5">5+ boîtes</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

            {/* Prescription File */}
            <FormField
              control={form.control}
              name="prescriptionFile"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-2">
                    <Upload className="h-4 w-4 text-primary" />
                    Ordonnance (optionnel)
                  </FormLabel>
                  <FormControl>
                    <Input
                      type="file"
                      accept="image/*,.pdf"
                      onChange={(e) => field.onChange(e.target.files?.[0])}
                      data-testid="input-prescription"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Location Picker */}
            <div>
              <LocationPicker
                onLocationSelect={(location) => {
                  setSelectedLocation(location);
                }}
                label="Localisation de livraison"
                placeholder="Entrez votre adresse ou cliquez sur la carte"
                required={true}
                className="space-y-2"
              />
            </div>

            {/* Pricing Preview */}
            <Alert className="border-blue-200 bg-blue-50">
              <Calculator className="h-4 w-4" />
              <AlertDescription>
                <div className="space-y-2">
                  <h4 className="font-medium mb-2">Estimation des frais</h4>
                  <div className="space-y-1 text-sm">
                    <div className="flex justify-between">
                      <span>Prix médicament:</span>
                      <span className="font-medium">Variable</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Frais de service:</span>
                      <Badge variant="outline">{PRICING.SERVICE_FEE} FCFA</Badge>
                    </div>
                    <div className="flex justify-between">
                      <span>Livraison (min {PRICING.DELIVERY_MIN}F + distance):</span>
                      <Badge variant="outline">À calculer</Badge>
                    </div>
                    <hr className="my-2" />
                    <div className="flex justify-between font-medium">
                      <span>Total estimé:</span>
                      <span className="text-primary">À calculer</span>
                    </div>
                  </div>
                </div>
              </AlertDescription>
            </Alert>

            {/* Submit Button */}
            <Button
              type="submit"
              className="w-full bg-gradient-to-r from-red-600 to-red-500 hover:from-red-700 hover:to-red-600 text-white font-bold py-3 shadow-lg transform transition hover:scale-105"
              disabled={createSosMutation.isPending || !selectedLocation}
              data-testid="button-submit-sos"
            >
              {createSosMutation.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Envoi en cours...
                </>
              ) : (
                <>
                  <CreditCard className="mr-2 h-4 w-4" />
                  COMMANDER & PAYER
                </>
              )}
            </Button>
          </form>
        </Form>
      </CardContent>

      {/* Modal de paiement Mobile Money */}
      {currentOrderId && (
        <PaymentModal
          isOpen={showPaymentModal}
          onClose={() => {
            setShowPaymentModal(false);
            setCurrentOrderId(null);
            form.reset();
            setEstimatedTotal(null);
          }}
          orderId={currentOrderId}
          amount={calculateEstimatedTotal()}
          customerInfo={{
            email: user?.email || 'client@mediflash.ci',
            firstName: user?.name?.split(' ')[0] || 'Client',
            lastName: user?.name?.split(' ')[1] || 'MediFlash',
            phone: form.getValues('clientPhone') || user?.phone || ''
          }}
        />
      )}
    </Card>
  );
}
