import { useState, useEffect } from 'react';
import { Search, Package, MapPin, Clock, AlertCircle } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useQuery } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';

interface Medicine {
  id: string;
  name: string;
  genericName?: string;
  category?: string;
  form?: string;
  dosage?: string;
  requiresPrescription: boolean;
  manufacturer?: string;
  description?: string;
}

interface PharmacyStock {
  pharmacyId: string;
  stock: number;
  unitPrice: number;
  available: boolean;
  pharmacy: {
    id: string;
    name: string;
    address: string;
    lat: number;
    lng: number;
    verified: boolean;
  };
}

interface MedicineSearchProps {
  onMedicineSelect?: (medicine: Medicine) => void;
  showStockInfo?: boolean;
  searchPlaceholder?: string;
}

export function MedicineSearch({ 
  onMedicineSelect, 
  showStockInfo = false,
  searchPlaceholder = "Rechercher un médicament..." 
}: MedicineSearchProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedMedicine, setSelectedMedicine] = useState<Medicine | null>(null);
  const { toast } = useToast();

  // Search medicines
  const { data: medicines = [], isLoading: isSearching } = useQuery<Medicine[]>({
    queryKey: ['/api/medicines/search', searchQuery],
    enabled: searchQuery.length >= 2,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Get popular medicines when no search
  const { data: popularMedicines = [] } = useQuery<Medicine[]>({
    queryKey: ['/api/medicines/popular'],
    staleTime: 30 * 60 * 1000, // 30 minutes
  });

  // Get stock information for selected medicine
  const { data: stockInfo = [] } = useQuery<PharmacyStock[]>({
    queryKey: ['/api/medicines', selectedMedicine?.id, 'stock'],
    enabled: showStockInfo && !!selectedMedicine,
    staleTime: 2 * 60 * 1000, // 2 minutes
  });

  const displayedMedicines = searchQuery.length >= 2 ? medicines : popularMedicines;

  const handleMedicineClick = (medicine: Medicine) => {
    setSelectedMedicine(medicine);
    onMedicineSelect?.(medicine);
  };

  const formatPrice = (price: number) => {
    return `${price.toLocaleString()} FCFA`;
  };

  const getCategoryColor = (category?: string) => {
    const colors: Record<string, string> = {
      'Antalgique': 'bg-blue-100 text-blue-800',
      'Antibiotique': 'bg-red-100 text-red-800',
      'Antispasmodique': 'bg-green-100 text-green-800',
      'Vitamine': 'bg-yellow-100 text-yellow-800',
      'Cardiovasculaire': 'bg-purple-100 text-purple-800',
      'Digestif': 'bg-orange-100 text-orange-800',
      'Respiratoire': 'bg-cyan-100 text-cyan-800',
    };
    return colors[category || ''] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="space-y-4" data-testid="medicine-search">
      {/* Search Input */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
        <Input
          placeholder={searchPlaceholder}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="pl-10"
          data-testid="input-medicine-search"
        />
      </div>

      {/* Loading State */}
      {isSearching && (
        <div className="flex items-center justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"></div>
        </div>
      )}

      {/* No results */}
      {searchQuery.length >= 2 && medicines.length === 0 && !isSearching && (
        <div className="text-center py-8 text-gray-500">
          <Package className="mx-auto h-12 w-12 mb-4" />
          <p>Aucun médicament trouvé pour "{searchQuery}"</p>
        </div>
      )}

      {/* Medicine Results */}
      <div className="grid gap-3" data-testid="medicine-results">
        {displayedMedicines.map((medicine: Medicine) => (
          <Card 
            key={medicine.id} 
            className={`cursor-pointer transition-all hover:shadow-md hover:border-red-300 ${
              selectedMedicine?.id === medicine.id ? 'border-red-500 bg-red-50' : ''
            }`}
            onClick={() => handleMedicineClick(medicine)}
            data-testid={`medicine-card-${medicine.id}`}
          >
            <CardContent className="p-4">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <h3 className="font-semibold text-gray-900" data-testid={`medicine-name-${medicine.id}`}>
                    {medicine.name}
                  </h3>
                  
                  {medicine.genericName && (
                    <p className="text-sm text-gray-600 mt-1">
                      DCI: {medicine.genericName}
                    </p>
                  )}
                  
                  <div className="flex items-center gap-2 mt-2">
                    {medicine.category && (
                      <Badge 
                        className={getCategoryColor(medicine.category)}
                        data-testid={`medicine-category-${medicine.id}`}
                      >
                        {medicine.category}
                      </Badge>
                    )}
                    
                    {medicine.form && (
                      <Badge variant="outline" data-testid={`medicine-form-${medicine.id}`}>
                        {medicine.form}
                      </Badge>
                    )}
                    
                    {medicine.dosage && (
                      <Badge variant="outline" data-testid={`medicine-dosage-${medicine.id}`}>
                        {medicine.dosage}
                      </Badge>
                    )}
                  </div>

                  {medicine.requiresPrescription && (
                    <div className="flex items-center gap-1 mt-2 text-orange-600">
                      <AlertCircle className="h-4 w-4" />
                      <span className="text-sm">Ordonnance requise</span>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Stock Information */}
      {showStockInfo && selectedMedicine && stockInfo.length > 0 && (
        <Card className="mt-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5" />
              Disponibilité en pharmacies
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {stockInfo.map((stock) => (
                <div 
                  key={stock.pharmacyId}
                  className="flex items-center justify-between p-3 border rounded-lg"
                  data-testid={`stock-info-${stock.pharmacyId}`}
                >
                  <div className="flex-1">
                    <h4 className="font-medium">{stock.pharmacy.name}</h4>
                    <p className="text-sm text-gray-600">{stock.pharmacy.address}</p>
                    <div className="flex items-center gap-4 mt-1">
                      <span className="text-sm flex items-center gap-1">
                        <Package className="h-4 w-4" />
                        {stock.stock} en stock
                      </span>
                      <span className="text-sm font-medium text-green-600">
                        {formatPrice(stock.unitPrice)}
                      </span>
                    </div>
                  </div>
                  
                  <div className="text-right">
                    {stock.pharmacy.verified && (
                      <Badge className="bg-green-100 text-green-800">
                        Vérifiée
                      </Badge>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Show section headers */}
      {searchQuery.length < 2 && popularMedicines.length > 0 && (
        <div className="pt-4">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Médicaments populaires
          </h3>
        </div>
      )}
    </div>
  );
}