import { useState, useEffect } from 'react';
import { Plus, Package, Edit, Trash2, AlertTriangle, TrendingUp, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';
import { MedicineSearch } from './medicine-search';
import { apiRequest } from '@/lib/queryClient';

interface PharmacyStock {
  id: string;
  medicineId: string;
  stock: number;
  unitPrice: number;
  minimumStock: number;
  available: boolean;
  lastRestockedAt?: string;
  medicine: {
    id: string;
    name: string;
    genericName?: string;
    category?: string;
    form?: string;
    dosage?: string;
    requiresPrescription: boolean;
  };
}

interface PharmacyStockManagementProps {
  pharmacyId: string;
}

export function PharmacyStockManagement({ pharmacyId }: PharmacyStockManagementProps) {
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editingStock, setEditingStock] = useState<PharmacyStock | null>(null);
  const [selectedMedicine, setSelectedMedicine] = useState<any>(null);
  const [stockForm, setStockForm] = useState({
    stock: '',
    unitPrice: '',
    minimumStock: '5'
  });
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Get pharmacy stock
  const { data: stockData = [], isLoading } = useQuery<PharmacyStock[]>({
    queryKey: ['/api/pharmacy', pharmacyId, 'stock'],
    staleTime: 2 * 60 * 1000, // 2 minutes
  });

  // Get low stock items
  const { data: lowStockItems = [] } = useQuery({
    queryKey: ['/api/pharmacy', pharmacyId, 'low-stock'],
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Add stock mutation
  const addStockMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest(`/api/pharmacy/${pharmacyId}/stock`, {
        method: 'POST',
        body: JSON.stringify(data),
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'stock'] });
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'low-stock'] });
      setIsAddDialogOpen(false);
      setSelectedMedicine(null);
      setStockForm({ stock: '', unitPrice: '', minimumStock: '5' });
      toast({
        title: "Stock ajouté",
        description: "Le médicament a été ajouté à votre stock",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de l'ajout au stock",
        variant: "destructive",
      });
    },
  });

  // Update quantity mutation
  const updateQuantityMutation = useMutation({
    mutationFn: async ({ medicineId, quantity }: { medicineId: string; quantity: number }) => {
      return apiRequest(`/api/pharmacy/${pharmacyId}/stock/${medicineId}/quantity`, {
        method: 'PUT',
        body: JSON.stringify({ quantity }),
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'stock'] });
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'low-stock'] });
      toast({
        title: "Stock mis à jour",
        description: "La quantité a été mise à jour",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de la mise à jour",
        variant: "destructive",
      });
    },
  });

  // Update price mutation
  const updatePriceMutation = useMutation({
    mutationFn: async ({ medicineId, price }: { medicineId: string; price: number }) => {
      return apiRequest(`/api/pharmacy/${pharmacyId}/stock/${medicineId}/price`, {
        method: 'PUT',
        body: JSON.stringify({ price }),
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'stock'] });
      toast({
        title: "Prix mis à jour",
        description: "Le prix a été mis à jour",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de la mise à jour du prix",
        variant: "destructive",
      });
    },
  });

  // Remove from stock mutation
  const removeStockMutation = useMutation({
    mutationFn: async (medicineId: string) => {
      return apiRequest(`/api/pharmacy/${pharmacyId}/stock/${medicineId}`, {
        method: 'DELETE',
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'stock'] });
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy', pharmacyId, 'low-stock'] });
      toast({
        title: "Médicament retiré",
        description: "Le médicament a été retiré de votre stock",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de la suppression",
        variant: "destructive",
      });
    },
  });

  const handleAddStock = () => {
    if (!selectedMedicine || !stockForm.stock || !stockForm.unitPrice) {
      toast({
        title: "Erreur",
        description: "Veuillez remplir tous les champs requis",
        variant: "destructive",
      });
      return;
    }

    addStockMutation.mutate({
      medicineId: selectedMedicine.id,
      stock: parseInt(stockForm.stock),
      unitPrice: parseInt(stockForm.unitPrice),
      minimumStock: parseInt(stockForm.minimumStock),
    });
  };

  const handleQuickUpdate = (medicineId: string, field: 'quantity' | 'price', value: string) => {
    const numValue = parseInt(value);
    if (isNaN(numValue) || numValue < 0) return;

    if (field === 'quantity') {
      updateQuantityMutation.mutate({ medicineId, quantity: numValue });
    } else {
      updatePriceMutation.mutate({ medicineId, price: numValue });
    }
  };

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

  const getStockStatusColor = (stock: number, minimumStock: number) => {
    if (stock === 0) return 'bg-red-100 text-red-800';
    if (stock <= minimumStock) return 'bg-yellow-100 text-yellow-800';
    return 'bg-green-100 text-green-800';
  };

  const getStockStatusText = (stock: number, minimumStock: number) => {
    if (stock === 0) return 'Rupture';
    if (stock <= minimumStock) return 'Stock faible';
    return 'En stock';
  };

  if (isLoading) {
    return (
      <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>
    );
  }

  return (
    <div className="space-y-6" data-testid="pharmacy-stock-management">
      {/* Header with Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <Package className="h-5 w-5 text-blue-600" />
              <div>
                <p className="text-sm text-gray-600">Total produits</p>
                <p className="text-2xl font-bold" data-testid="total-products">
                  {stockData.length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-yellow-600" />
              <div>
                <p className="text-sm text-gray-600">Stock faible</p>
                <p className="text-2xl font-bold text-yellow-600" data-testid="low-stock-count">
                  {lowStockItems.length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5 text-green-600" />
              <div>
                <p className="text-sm text-gray-600">Valeur totale</p>
                <p className="text-2xl font-bold text-green-600" data-testid="total-value">
                  {formatPrice(stockData.reduce((total, item) => total + (item.stock * item.unitPrice), 0))}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Add Stock Dialog */}
      <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
        <DialogTrigger asChild>
          <Button className="bg-red-600 hover:bg-red-700" data-testid="button-add-stock">
            <Plus className="h-4 w-4 mr-2" />
            Ajouter au stock
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Ajouter un médicament au stock</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            {/* Medicine Search */}
            <div>
              <Label>Sélectionner un médicament</Label>
              <MedicineSearch
                onMedicineSelect={setSelectedMedicine}
                searchPlaceholder="Rechercher un médicament à ajouter..."
              />
              {selectedMedicine && (
                <div className="mt-2 p-3 bg-gray-50 rounded-lg">
                  <p className="font-medium">{selectedMedicine.name}</p>
                  {selectedMedicine.genericName && (
                    <p className="text-sm text-gray-600">DCI: {selectedMedicine.genericName}</p>
                  )}
                </div>
              )}
            </div>

            {/* Stock Form */}
            {selectedMedicine && (
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="stock">Quantité en stock *</Label>
                  <Input
                    id="stock"
                    type="number"
                    value={stockForm.stock}
                    onChange={(e) => setStockForm({ ...stockForm, stock: e.target.value })}
                    placeholder="Ex: 50"
                    data-testid="input-stock-quantity"
                  />
                </div>
                <div>
                  <Label htmlFor="unitPrice">Prix unitaire (FCFA) *</Label>
                  <Input
                    id="unitPrice"
                    type="number"
                    value={stockForm.unitPrice}
                    onChange={(e) => setStockForm({ ...stockForm, unitPrice: e.target.value })}
                    placeholder="Ex: 500"
                    data-testid="input-unit-price"
                  />
                </div>
                <div>
                  <Label htmlFor="minimumStock">Stock minimum</Label>
                  <Input
                    id="minimumStock"
                    type="number"
                    value={stockForm.minimumStock}
                    onChange={(e) => setStockForm({ ...stockForm, minimumStock: e.target.value })}
                    placeholder="Ex: 5"
                    data-testid="input-minimum-stock"
                  />
                </div>
              </div>
            )}

            <div className="flex justify-end gap-2">
              <Button 
                variant="outline" 
                onClick={() => setIsAddDialogOpen(false)}
                data-testid="button-cancel-add"
              >
                Annuler
              </Button>
              <Button 
                onClick={handleAddStock}
                disabled={addStockMutation.isPending}
                data-testid="button-confirm-add"
              >
                {addStockMutation.isPending ? 'Ajout...' : 'Ajouter au stock'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Stock Management Tabs */}
      <Tabs defaultValue="all-stock" className="w-full">
        <TabsList>
          <TabsTrigger value="all-stock">Tout le stock</TabsTrigger>
          <TabsTrigger value="low-stock">Stock faible ({lowStockItems.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="all-stock">
          <Card>
            <CardHeader>
              <CardTitle>Gestion du stock</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {stockData.map((item) => (
                  <div 
                    key={item.id}
                    className="flex items-center justify-between p-4 border rounded-lg"
                    data-testid={`stock-item-${item.medicineId}`}
                  >
                    <div className="flex-1">
                      <h4 className="font-medium">{item.medicine.name}</h4>
                      {item.medicine.genericName && (
                        <p className="text-sm text-gray-600">DCI: {item.medicine.genericName}</p>
                      )}
                      <div className="flex items-center gap-4 mt-2">
                        <Badge className={getStockStatusColor(item.stock, item.minimumStock)}>
                          {getStockStatusText(item.stock, item.minimumStock)}
                        </Badge>
                        {item.medicine.category && (
                          <Badge variant="outline">{item.medicine.category}</Badge>
                        )}
                        {item.medicine.form && (
                          <Badge variant="outline">{item.medicine.form}</Badge>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center gap-4">
                      {/* Quick edit fields */}
                      <div className="text-right">
                        <div className="flex items-center gap-2">
                          <span className="text-sm text-gray-600">Stock:</span>
                          <Input
                            type="number"
                            value={item.stock}
                            onChange={(e) => handleQuickUpdate(item.medicineId, 'quantity', e.target.value)}
                            className="w-20 h-8"
                            data-testid={`input-update-stock-${item.medicineId}`}
                          />
                        </div>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-sm text-gray-600">Prix:</span>
                          <Input
                            type="number"
                            value={item.unitPrice}
                            onChange={(e) => handleQuickUpdate(item.medicineId, 'price', e.target.value)}
                            className="w-24 h-8"
                            data-testid={`input-update-price-${item.medicineId}`}
                          />
                          <span className="text-xs text-gray-500">FCFA</span>
                        </div>
                      </div>

                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => removeStockMutation.mutate(item.medicineId)}
                        disabled={removeStockMutation.isPending}
                        data-testid={`button-remove-${item.medicineId}`}
                      >
                        <Trash2 className="h-4 w-4 text-red-600" />
                      </Button>
                    </div>
                  </div>
                ))}

                {stockData.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    <Package className="mx-auto h-12 w-12 mb-4" />
                    <p>Aucun médicament en stock</p>
                    <p className="text-sm">Commencez par ajouter des médicaments à votre stock</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="low-stock">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <AlertTriangle className="h-5 w-5 text-yellow-600" />
                Stock faible - Réapprovisionnement nécessaire
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {lowStockItems.map((item: any) => (
                  <div 
                    key={item.id}
                    className="flex items-center justify-between p-3 border-l-4 border-yellow-400 bg-yellow-50 rounded-lg"
                    data-testid={`low-stock-item-${item.id}`}
                  >
                    <div>
                      <h4 className="font-medium">{item.medicine.name}</h4>
                      <p className="text-sm text-gray-600">
                        Stock actuel: {item.stock} | Minimum: {item.minimumStock}
                      </p>
                    </div>
                    <Badge className="bg-yellow-100 text-yellow-800">
                      Action requise
                    </Badge>
                  </div>
                ))}

                {lowStockItems.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    <TrendingUp className="mx-auto h-12 w-12 mb-4" />
                    <p>Excellent ! Aucun stock faible</p>
                    <p className="text-sm">Tous vos médicaments sont bien approvisionnés</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}