import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import {
  Package,
  Plus,
  Edit,
  Trash2,
  AlertTriangle,
  TrendingUp,
  TrendingDown,
  Search,
  Filter,
  Calendar,
  BarChart3,
  Eye,
  ShoppingCart,
  Clock,
  CheckCircle
} from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface InventoryItem {
  id: string;
  medicineId: string;
  medicineName: string;
  category: string;
  currentStock: number;
  minStock: number;
  maxStock: number;
  unitPrice: number;
  batchNumber: string;
  expiryDate: string;
  supplier: string;
  lastRestocked: string;
  status: 'available' | 'low_stock' | 'out_of_stock' | 'expired';
  soldToday: number;
  soldThisWeek: number;
  soldThisMonth: number;
}

interface InventoryStats {
  totalItems: number;
  lowStockItems: number;
  expiredItems: number;
  totalValue: number;
  topSelling: InventoryItem[];
  recentMovements: Array<{
    id: string;
    type: 'in' | 'out' | 'adjustment';
    medicineName: string;
    quantity: number;
    reason: string;
    timestamp: string;
  }>;
}

interface PharmacyInventoryManagementProps {
  pharmacyId: string;
}

export function PharmacyInventoryManagement({ pharmacyId }: PharmacyInventoryManagementProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [selectedItem, setSelectedItem] = useState<InventoryItem | null>(null);
  
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Fetch inventory data
  const { data: inventory = [], isLoading } = useQuery<InventoryItem[]>({
    queryKey: ['/api/pharmacy/inventory', pharmacyId],
    initialData: [
      {
        id: '1',
        medicineId: 'med_1',
        medicineName: 'Paracétamol 500mg',
        category: 'Antalgiques',
        currentStock: 150,
        minStock: 50,
        maxStock: 300,
        unitPrice: 250,
        batchNumber: 'PAR2024001',
        expiryDate: '2025-12-31',
        supplier: 'Pharma Supply CI',
        lastRestocked: '2024-11-15',
        status: 'available',
        soldToday: 8,
        soldThisWeek: 45,
        soldThisMonth: 180
      },
      {
        id: '2',
        medicineId: 'med_2',
        medicineName: 'Amoxicilline 500mg',
        category: 'Antibiotiques',
        currentStock: 25,
        minStock: 30,
        maxStock: 200,
        unitPrice: 450,
        batchNumber: 'AMX2024002',
        expiryDate: '2025-08-30',
        supplier: 'MediDistrib',
        lastRestocked: '2024-10-20',
        status: 'low_stock',
        soldToday: 3,
        soldThisWeek: 22,
        soldThisMonth: 95
      },
      {
        id: '3',
        medicineId: 'med_3',
        medicineName: 'Ibuprofène 400mg',
        category: 'Anti-inflammatoires',
        currentStock: 0,
        minStock: 40,
        maxStock: 250,
        unitPrice: 350,
        batchNumber: 'IBU2024003',
        expiryDate: '2025-06-15',
        supplier: 'Pharma Supply CI',
        lastRestocked: '2024-09-10',
        status: 'out_of_stock',
        soldToday: 0,
        soldThisWeek: 0,
        soldThisMonth: 45
      },
      {
        id: '4',
        medicineId: 'med_4',
        medicineName: 'Aspirine 500mg',
        category: 'Antalgiques',
        currentStock: 75,
        minStock: 25,
        maxStock: 150,
        unitPrice: 200,
        batchNumber: 'ASP2023001',
        expiryDate: '2024-12-20',
        supplier: 'MediDistrib',
        lastRestocked: '2024-08-05',
        status: 'expired',
        soldToday: 0,
        soldThisWeek: 2,
        soldThisMonth: 8
      }
    ]
  });

  // Fetch inventory statistics
  const { data: stats } = useQuery<InventoryStats>({
    queryKey: ['/api/pharmacy/inventory/stats', pharmacyId],
    initialData: {
      totalItems: inventory.length,
      lowStockItems: inventory.filter(item => item.status === 'low_stock' || item.status === 'out_of_stock').length,
      expiredItems: inventory.filter(item => item.status === 'expired').length,
      totalValue: inventory.reduce((sum, item) => sum + (item.currentStock * item.unitPrice), 0),
      topSelling: inventory.slice(0, 5).sort((a, b) => b.soldThisMonth - a.soldThisMonth),
      recentMovements: [
        {
          id: '1',
          type: 'out',
          medicineName: 'Paracétamol 500mg',
          quantity: 10,
          reason: 'Vente client',
          timestamp: '2024-12-03T14:30:00Z'
        },
        {
          id: '2',
          type: 'in',
          medicineName: 'Paracétamol 500mg',
          quantity: 100,
          reason: 'Réapprovisionnement',
          timestamp: '2024-12-02T09:15:00Z'
        },
        {
          id: '3',
          type: 'out',
          medicineName: 'Amoxicilline 500mg',
          quantity: 5,
          reason: 'Commande SOS',
          timestamp: '2024-12-02T16:45:00Z'
        }
      ]
    }
  });

  // Update stock mutation
  const updateStockMutation = useMutation({
    mutationFn: async (data: { itemId: string; quantity: number; type: 'add' | 'remove'; reason: string }) => {
      return await apiRequest('/api/pharmacy/inventory/update-stock', {
        method: 'POST',
        body: JSON.stringify(data)
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy/inventory', pharmacyId] });
      toast({
        title: "Stock mis à jour",
        description: "Le stock a été mis à jour avec succès.",
      });
    },
    onError: () => {
      toast({
        title: "Erreur",
        description: "Impossible de mettre à jour le stock.",
        variant: "destructive",
      });
    },
  });

  // Add new medicine mutation
  const addMedicineMutation = useMutation({
    mutationFn: async (data: Partial<InventoryItem>) => {
      return await apiRequest('/api/pharmacy/inventory', {
        method: 'POST',
        body: JSON.stringify(data)
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/pharmacy/inventory', pharmacyId] });
      toast({
        title: "Médicament ajouté",
        description: "Le médicament a été ajouté à l'inventaire.",
      });
      setShowAddDialog(false);
    },
    onError: () => {
      toast({
        title: "Erreur",
        description: "Impossible d'ajouter le médicament.",
        variant: "destructive",
      });
    },
  });

  const getStatusBadge = (status: string) => {
    const variants = {
      available: 'bg-green-100 text-green-800',
      low_stock: 'bg-yellow-100 text-yellow-800',
      out_of_stock: 'bg-red-100 text-red-800',
      expired: 'bg-gray-100 text-gray-800'
    };
    
    const labels = {
      available: 'Disponible',
      low_stock: 'Stock faible',
      out_of_stock: 'Rupture',
      expired: 'Expiré'
    };
    
    return (
      <Badge className={variants[status as keyof typeof variants] || 'bg-gray-100 text-gray-800'}>
        {labels[status as keyof typeof labels] || status}
      </Badge>
    );
  };

  const getStockLevel = (current: number, min: number, max: number) => {
    const percentage = (current / max) * 100;
    return Math.min(100, Math.max(0, percentage));
  };

  const getStockColor = (current: number, min: number) => {
    if (current === 0) return 'bg-red-500';
    if (current <= min) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  // Filter inventory based on search and filters
  const filteredInventory = inventory.filter(item => {
    const matchesSearch = item.medicineName.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;
    const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
    return matchesSearch && matchesCategory && matchesStatus;
  });

  const categories = [...new Set(inventory.map(item => item.category))];

  if (isLoading) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="p-6">
              <div className="animate-pulse space-y-4">
                <div className="h-4 bg-gray-200 rounded w-1/3"></div>
                <div className="h-32 bg-gray-200 rounded"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total articles</p>
                <p className="text-2xl font-bold text-primary">{stats?.totalItems || 0}</p>
              </div>
              <Package className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Stock faible</p>
                <p className="text-2xl font-bold text-yellow-600">{stats?.lowStockItems || 0}</p>
                <p className="text-xs text-yellow-600 flex items-center mt-1">
                  <AlertTriangle className="h-3 w-3 mr-1" />
                  Attention requise
                </p>
              </div>
              <AlertTriangle className="h-8 w-8 text-yellow-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Expirés</p>
                <p className="text-2xl font-bold text-red-600">{stats?.expiredItems || 0}</p>
                <p className="text-xs text-red-600 flex items-center mt-1">
                  <Clock className="h-3 w-3 mr-1" />
                  À retirer
                </p>
              </div>
              <Clock className="h-8 w-8 text-red-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Valeur totale</p>
                <p className="text-2xl font-bold text-green-600">
                  {((stats?.totalValue || 0) / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-green-600 flex items-center mt-1">
                  <TrendingUp className="h-3 w-3 mr-1" />
                  +5% ce mois
                </p>
              </div>
              <BarChart3 className="h-8 w-8 text-green-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters and Actions */}
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              Gestion d'Inventaire
            </CardTitle>
            <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
              <DialogTrigger asChild>
                <Button data-testid="button-add-medicine">
                  <Plus className="h-4 w-4 mr-1" />
                  Ajouter médicament
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Ajouter un médicament</DialogTitle>
                  <DialogDescription>
                    Ajoutez un nouveau médicament à votre inventaire.
                  </DialogDescription>
                </DialogHeader>
                {/* Add medicine form would go here */}
                <div className="space-y-4">
                  <p className="text-sm text-muted-foreground">
                    Formulaire d'ajout de médicament à implémenter
                  </p>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Rechercher un médicament..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                  data-testid="input-search-medicine"
                />
              </div>
            </div>
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Catégorie" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toutes catégories</SelectItem>
                {categories.map(category => (
                  <SelectItem key={category} value={category}>{category}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Statut" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Tous statuts</SelectItem>
                <SelectItem value="available">Disponible</SelectItem>
                <SelectItem value="low_stock">Stock faible</SelectItem>
                <SelectItem value="out_of_stock">Rupture</SelectItem>
                <SelectItem value="expired">Expiré</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Inventory Table */}
          <div className="border rounded-lg overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Médicament</TableHead>
                  <TableHead>Catégorie</TableHead>
                  <TableHead>Stock</TableHead>
                  <TableHead>Niveau</TableHead>
                  <TableHead>Prix unitaire</TableHead>
                  <TableHead>Statut</TableHead>
                  <TableHead>Ventes (mois)</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredInventory.map((item) => (
                  <TableRow key={item.id} data-testid={`inventory-item-${item.id}`}>
                    <TableCell>
                      <div>
                        <div className="font-medium">{item.medicineName}</div>
                        <div className="text-sm text-muted-foreground">
                          Lot: {item.batchNumber}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>{item.category}</TableCell>
                    <TableCell>
                      <div className="text-center">
                        <div className="font-medium">{item.currentStock}</div>
                        <div className="text-xs text-muted-foreground">
                          Min: {item.minStock} | Max: {item.maxStock}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="w-24">
                        <Progress 
                          value={getStockLevel(item.currentStock, item.minStock, item.maxStock)} 
                          className="h-2"
                        />
                        <div className="text-xs text-muted-foreground text-center mt-1">
                          {Math.round(getStockLevel(item.currentStock, item.minStock, item.maxStock))}%
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="font-medium">{item.unitPrice} F</TableCell>
                    <TableCell>{getStatusBadge(item.status)}</TableCell>
                    <TableCell>
                      <div className="text-center">
                        <div className="font-medium">{item.soldThisMonth}</div>
                        <div className="text-xs text-muted-foreground">
                          Cette semaine: {item.soldThisWeek}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSelectedItem(item);
                            setShowEditDialog(true);
                          }}
                          data-testid={`button-edit-${item.id}`}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          data-testid={`button-view-${item.id}`}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {filteredInventory.length === 0 && (
            <div className="text-center py-8">
              <Package className="h-16 w-16 mx-auto text-gray-300 mb-4" />
              <h3 className="text-lg font-medium text-gray-600 mb-2">
                Aucun médicament trouvé
              </h3>
              <p className="text-muted-foreground">
                Essayez de modifier vos filtres de recherche
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Top Selling Medicines */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Médicaments les plus vendus
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {stats?.topSelling.slice(0, 5).map((item, index) => (
              <div key={item.id} className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <span className="text-sm font-medium text-primary">{index + 1}</span>
                  </div>
                  <div>
                    <p className="font-medium">{item.medicineName}</p>
                    <p className="text-sm text-muted-foreground">{item.category}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <p className="font-medium">{item.soldThisMonth} vendus</p>
                    <p className="text-sm text-muted-foreground">
                      {(item.soldThisMonth * item.unitPrice).toLocaleString()} F
                    </p>
                  </div>
                  <Progress 
                    value={(item.soldThisMonth / (stats.topSelling[0]?.soldThisMonth || 1)) * 100} 
                    className="w-20"
                  />
                </div>
              </div>
            )) || []}
          </div>
        </CardContent>
      </Card>

      {/* Recent Movements */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            Mouvements récents
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {stats?.recentMovements.map((movement) => (
              <div key={movement.id} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex items-center gap-3">
                  {movement.type === 'in' ? (
                    <div className="p-2 rounded-full bg-green-100">
                      <TrendingUp className="h-4 w-4 text-green-600" />
                    </div>
                  ) : movement.type === 'out' ? (
                    <div className="p-2 rounded-full bg-red-100">
                      <TrendingDown className="h-4 w-4 text-red-600" />
                    </div>
                  ) : (
                    <div className="p-2 rounded-full bg-blue-100">
                      <Edit className="h-4 w-4 text-blue-600" />
                    </div>
                  )}
                  <div>
                    <p className="font-medium">{movement.medicineName}</p>
                    <p className="text-sm text-muted-foreground">{movement.reason}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="font-medium">
                    {movement.type === 'in' ? '+' : '-'}{movement.quantity}
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {new Date(movement.timestamp).toLocaleString('fr-FR')}
                  </p>
                </div>
              </div>
            )) || []}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}