import { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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 { Skeleton } from "@/components/ui/skeleton";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Calendar, AlertCircle, CheckCircle2, Clock, MapPin, Users, Shield, Car as CarIcon, Building2 } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { format } from "date-fns";
import { it } from "date-fns/locale";
import { useToast } from "@/hooks/use-toast";
import { useLocation } from "wouter";

interface Shift {
  id: string;
  startTime: string;
  endTime: string;
  assignedGuardsCount: number;
  requiredGuards: number;
  isCovered: boolean;
  isPartial: boolean;
}

interface UncoveredSite {
  id: string;
  name: string;
  address: string;
  location: string;
  shiftType: string;
  minGuards: number;
  requiresArmed: boolean;
  requiresDriverLicense: boolean;
  serviceStartTime: string | null;
  serviceEndTime: string | null;
  isCovered: boolean;
  isPartiallyCovered: boolean;
  totalAssignedGuards: number;
  requiredGuards: number;
  shiftsCount: number;
  shifts: Shift[];
}

interface UncoveredSitesData {
  date: string;
  uncoveredSites: UncoveredSite[];
  totalSites: number;
  totalUncovered: number;
}

interface Vehicle {
  id: string;
  licensePlate: string;
  brand: string;
  model: string;
  vehicleType: string;
  location: string;
  hasDriverLicense?: boolean;
  isAvailable: boolean;
}

interface Guard {
  id: string;
  badgeNumber: string;
  userId: string;
  firstName?: string;
  lastName?: string;
  location: string;
  isArmed: boolean;
  hasDriverLicense: boolean;
  isAvailable: boolean;
  availability: {
    weeklyHours: number;
    remainingWeeklyHours: number;
    consecutiveDaysWorked: number;
  };
}

interface ResourcesData {
  date: string;
  vehicles: Vehicle[];
  guards: Guard[];
}

const locationLabels: Record<string, string> = {
  roccapiemonte: "Roccapiemonte",
  milano: "Milano",
  roma: "Roma",
};

export default function OperationalPlanning() {
  const { toast } = useToast();
  const [location] = useLocation();
  
  // Leggi parametri dalla URL
  const searchParams = new URLSearchParams(location.split('?')[1] || '');
  const urlDate = searchParams.get('date');
  const urlLocation = searchParams.get('location');
  
  const [selectedLocation, setSelectedLocation] = useState<string>(
    urlLocation && ['roccapiemonte', 'milano', 'roma'].includes(urlLocation) 
      ? urlLocation 
      : "roccapiemonte"
  );
  const [selectedDate, setSelectedDate] = useState<string>(
    urlDate || format(new Date(), "yyyy-MM-dd")
  );
  const [selectedSite, setSelectedSite] = useState<UncoveredSite | null>(null);
  const [selectedGuards, setSelectedGuards] = useState<string[]>([]);
  const [selectedVehicle, setSelectedVehicle] = useState<string | null>(null);
  const [createShiftDialogOpen, setCreateShiftDialogOpen] = useState(false);
  
  // Aggiorna stato quando cambiano i parametri URL
  useEffect(() => {
    if (urlDate) setSelectedDate(urlDate);
    if (urlLocation && ['roccapiemonte', 'milano', 'roma'].includes(urlLocation)) {
      setSelectedLocation(urlLocation);
    }
  }, [urlDate, urlLocation]);

  // Query per siti non coperti (filtrati per sede e data)
  const { data: uncoveredData, isLoading } = useQuery<UncoveredSitesData>({
    queryKey: ['/api/operational-planning/uncovered-sites', selectedDate, selectedLocation],
    queryFn: async ({ queryKey }) => {
      const [, date, location] = queryKey;
      const res = await fetch(`/api/operational-planning/uncovered-sites?date=${date}&location=${location}`, {
        credentials: 'include'
      });
      if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
      return res.json();
    },
    enabled: !!selectedDate && !!selectedLocation,
  });

  // Query per risorse (veicoli e guardie) - solo quando c'è un sito selezionato
  const { data: resourcesData, isLoading: isLoadingResources } = useQuery<ResourcesData>({
    queryKey: ['/api/operational-planning/availability', selectedDate, selectedLocation, selectedSite?.id],
    queryFn: async ({ queryKey }) => {
      const [, date, location] = queryKey;
      const res = await fetch(`/api/operational-planning/availability?date=${date}&location=${location}`, {
        credentials: 'include'
      });
      if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
      return res.json();
    },
    enabled: !!selectedDate && !!selectedLocation && !!selectedSite,
  });

  const handleLocationChange = (location: string) => {
    setSelectedLocation(location);
    setSelectedSite(null);
    setSelectedGuards([]);
    setSelectedVehicle(null);
  };

  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedDate(e.target.value);
    setSelectedSite(null);
    setSelectedGuards([]);
    setSelectedVehicle(null);
  };

  const handleSelectSite = (site: UncoveredSite) => {
    setSelectedSite(site);
    setSelectedGuards([]);
    setSelectedVehicle(null);
    setCreateShiftDialogOpen(true);
  };

  const toggleGuardSelection = (guardId: string) => {
    setSelectedGuards((prev) =>
      prev.includes(guardId)
        ? prev.filter((id) => id !== guardId)
        : [...prev, guardId]
    );
  };

  // Filtra risorse per requisiti del sito
  const filteredVehicles = resourcesData?.vehicles.filter((v) => {
    if (!selectedSite) return false;
    // Filtra per sede e disponibilità
    if (v.location !== selectedSite.location) return false;
    if (!v.isAvailable) return false;
    return true;
  }) || [];

  const filteredGuards = resourcesData?.guards.filter((g) => {
    if (!selectedSite) return false;
    // Filtra per sede
    if (g.location !== selectedSite.location) return false;
    // Filtra per disponibilità
    if (!g.isAvailable) return false;
    // Filtra per requisiti
    if (selectedSite.requiresArmed && !g.isArmed) return false;
    if (selectedSite.requiresDriverLicense && !g.hasDriverLicense) return false;
    return true;
  }) || [];

  // Mutation per creare turno
  const createShiftMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest("POST", "/api/shifts", data);
    },
    onSuccess: () => {
      // Invalida tutte le query che iniziano con /api/operational-planning/uncovered-sites
      queryClient.invalidateQueries({ 
        predicate: (query) => query.queryKey[0]?.toString().startsWith('/api/operational-planning/uncovered-sites') || false 
      });
      toast({
        title: "Turno creato",
        description: "Il turno è stato creato con successo.",
      });
      setCreateShiftDialogOpen(false);
      setSelectedSite(null);
      setSelectedGuards([]);
      setSelectedVehicle(null);
    },
    onError: (error: any) => {
      toast({
        title: "Errore",
        description: error.message || "Impossibile creare il turno.",
        variant: "destructive",
      });
    },
  });

  const handleCreateShift = () => {
    if (!selectedSite) return;
    
    // Valida che ci siano abbastanza guardie selezionate
    if (selectedGuards.length < selectedSite.minGuards) {
      toast({
        title: "Guardie insufficienti",
        description: `Seleziona almeno ${selectedSite.minGuards} guardie per questo sito.`,
        variant: "destructive",
      });
      return;
    }

    // TODO: Qui bisognerà chiedere l'orario del turno
    // Per ora creiamo un turno di default basato su serviceStartTime/serviceEndTime del sito
    const today = selectedDate;
    const startTime = selectedSite.serviceStartTime || "08:00";
    const endTime = selectedSite.serviceEndTime || "16:00";

    const shiftData = {
      siteId: selectedSite.id,
      startTime: new Date(`${today}T${startTime}:00.000Z`),
      endTime: new Date(`${today}T${endTime}:00.000Z`),
      status: "planned",
      vehicleId: selectedVehicle || null,
      guardIds: selectedGuards,
    };

    createShiftMutation.mutate(shiftData);
  };

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold flex items-center gap-2">
            <Calendar className="h-8 w-8" />
            Pianificazione Operativa
          </h1>
          <p className="text-muted-foreground mt-1">
            Assegna turni ai siti non coperti
          </p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            Seleziona Sede e Data
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4 items-end">
            <div className="flex-1 max-w-xs">
              <Label htmlFor="planning-location">Sede</Label>
              <Select value={selectedLocation} onValueChange={handleLocationChange}>
                <SelectTrigger id="planning-location" data-testid="select-planning-location" className="mt-1">
                  <Building2 className="h-4 w-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="roccapiemonte">Roccapiemonte</SelectItem>
                  <SelectItem value="milano">Milano</SelectItem>
                  <SelectItem value="roma">Roma</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex-1 max-w-xs">
              <Label htmlFor="planning-date">Data</Label>
              <Input
                id="planning-date"
                data-testid="input-planning-date"
                type="date"
                value={selectedDate}
                onChange={handleDateChange}
                className="mt-1"
              />
            </div>
          </div>
          {uncoveredData && (
            <div className="mt-4 flex items-center gap-4 text-sm">
              <p className="text-muted-foreground">
                {format(new Date(selectedDate), "dd MMMM yyyy", { locale: it })}
              </p>
              <Badge variant="outline" className="gap-1">
                <AlertCircle className="h-3 w-3" />
                {uncoveredData.totalUncovered} siti da coprire
              </Badge>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Lista siti non coperti */}
      {isLoading ? (
        <div className="space-y-4">
          <Skeleton className="h-32" />
          <Skeleton className="h-32" />
        </div>
      ) : uncoveredData && uncoveredData.uncoveredSites.length > 0 ? (
        <div className="space-y-4">
          <h2 className="text-xl font-semibold">Siti Non Coperti</h2>
          {uncoveredData.uncoveredSites.map((site) => (
            <Card key={site.id} data-testid={`site-card-${site.id}`}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <CardTitle className="flex items-center gap-2">
                      {site.name}
                      {site.isPartiallyCovered ? (
                        <Badge variant="secondary" className="gap-1">
                          <AlertCircle className="h-3 w-3" />
                          Parzialmente Coperto
                        </Badge>
                      ) : (
                        <Badge variant="destructive" className="gap-1">
                          <AlertCircle className="h-3 w-3" />
                          Non Coperto
                        </Badge>
                      )}
                    </CardTitle>
                    <CardDescription className="mt-2 space-y-1">
                      <div className="flex items-center gap-1 text-sm">
                        <MapPin className="h-3 w-3" />
                        {site.address} - {site.location}
                      </div>
                      {site.serviceStartTime && site.serviceEndTime && (
                        <div className="flex items-center gap-1 text-sm">
                          <Clock className="h-3 w-3" />
                          Orario: {site.serviceStartTime} - {site.serviceEndTime}
                        </div>
                      )}
                    </CardDescription>
                  </div>
                  <Button
                    onClick={() => handleSelectSite(site)}
                    data-testid={`button-select-site-${site.id}`}
                  >
                    Assegna Turno
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">Turni Pianificati</p>
                    <p className="text-lg font-semibold">{site.shiftsCount}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Guardie Richieste</p>
                    <p className="text-lg font-semibold">{site.requiredGuards}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Guardie Assegnate</p>
                    <p className="text-lg font-semibold">{site.totalAssignedGuards}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Requisiti</p>
                    <div className="flex gap-1 mt-1">
                      {site.requiresArmed && (
                        <Badge variant="outline" className="text-xs">
                          <Shield className="h-3 w-3 mr-1" />
                          Armato
                        </Badge>
                      )}
                      {site.requiresDriverLicense && (
                        <Badge variant="outline" className="text-xs">
                          <CarIcon className="h-3 w-3 mr-1" />
                          Patente
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>

                {site.shifts.length > 0 && (
                  <div className="mt-4 pt-4 border-t">
                    <p className="text-sm font-medium mb-2">Dettagli Turni:</p>
                    <div className="space-y-2">
                      {site.shifts.map((shift) => (
                        <div key={shift.id} className="flex items-center justify-between text-sm p-2 rounded bg-muted/50">
                          <div className="flex items-center gap-2">
                            <Clock className="h-4 w-4" />
                            {format(new Date(shift.startTime), "HH:mm")} - {format(new Date(shift.endTime), "HH:mm")}
                          </div>
                          <div className="flex items-center gap-2">
                            <Users className="h-4 w-4" />
                            {shift.assignedGuardsCount}/{shift.requiredGuards}
                            {shift.isCovered ? (
                              <CheckCircle2 className="h-4 w-4 text-green-500" />
                            ) : shift.isPartial ? (
                              <AlertCircle className="h-4 w-4 text-orange-500" />
                            ) : (
                              <AlertCircle className="h-4 w-4 text-red-500" />
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <Card>
          <CardContent className="py-12 text-center">
            <CheckCircle2 className="h-12 w-12 mx-auto text-green-500 mb-4" />
            <h3 className="text-lg font-semibold mb-2">Tutti i siti sono coperti!</h3>
            <p className="text-muted-foreground">
              Non ci sono siti che richiedono assegnazioni per questa data.
            </p>
          </CardContent>
        </Card>
      )}

      {/* Dialog per assegnare risorse e creare turno */}
      <Dialog open={createShiftDialogOpen} onOpenChange={setCreateShiftDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Assegna Risorse - {selectedSite?.name}</DialogTitle>
            <DialogDescription>
              Seleziona le guardie e il veicolo per creare il turno
            </DialogDescription>
          </DialogHeader>

          {isLoadingResources ? (
            <div className="space-y-4">
              <Skeleton className="h-24" />
              <Skeleton className="h-24" />
            </div>
          ) : (
            <div className="space-y-6">
              {/* Veicoli Disponibili */}
              <div>
                <h3 className="font-semibold mb-3 flex items-center gap-2">
                  <CarIcon className="h-5 w-5" />
                  Veicoli Disponibili ({filteredVehicles.length})
                </h3>
                {filteredVehicles.length > 0 ? (
                  <div className="grid grid-cols-2 gap-3">
                    {filteredVehicles.map((vehicle) => (
                      <Card
                        key={vehicle.id}
                        className={`cursor-pointer transition-colors ${
                          selectedVehicle === vehicle.id ? "border-primary bg-primary/5" : ""
                        }`}
                        onClick={() => setSelectedVehicle(vehicle.id)}
                        data-testid={`vehicle-card-${vehicle.id}`}
                      >
                        <CardContent className="p-4">
                          <div className="flex items-center justify-between">
                            <div>
                              <p className="font-medium">{vehicle.licensePlate}</p>
                              <p className="text-sm text-muted-foreground">
                                {vehicle.brand} {vehicle.model}
                              </p>
                            </div>
                            <div onClick={(e) => e.stopPropagation()}>
                              <Checkbox
                                checked={selectedVehicle === vehicle.id}
                                onCheckedChange={() => setSelectedVehicle(vehicle.id)}
                              />
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">Nessun veicolo disponibile per questa sede</p>
                )}
              </div>

              {/* Guardie Disponibili */}
              <div>
                <h3 className="font-semibold mb-3 flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  Guardie Disponibili ({filteredGuards.length})
                  <Badge variant="outline" className="ml-auto">
                    Selezionate: {selectedGuards.length}/{selectedSite?.minGuards || 0}
                  </Badge>
                </h3>
                {filteredGuards.length > 0 ? (
                  <div className="space-y-2">
                    {filteredGuards.map((guard) => (
                      <Card
                        key={guard.id}
                        className={`cursor-pointer transition-colors ${
                          selectedGuards.includes(guard.id) ? "border-primary bg-primary/5" : ""
                        }`}
                        onClick={() => toggleGuardSelection(guard.id)}
                        data-testid={`guard-card-${guard.id}`}
                      >
                        <CardContent className="p-4">
                          <div className="flex items-center justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <p className="font-medium">
                                  {guard.firstName} {guard.lastName} - #{guard.badgeNumber}
                                </p>
                                {guard.isArmed && (
                                  <Badge variant="outline" className="text-xs">
                                    <Shield className="h-3 w-3 mr-1" />
                                    Armato
                                  </Badge>
                                )}
                                {guard.hasDriverLicense && (
                                  <Badge variant="outline" className="text-xs">
                                    <CarIcon className="h-3 w-3 mr-1" />
                                    Patente
                                  </Badge>
                                )}
                              </div>
                              <p className="text-sm text-muted-foreground mt-1">
                                Ore sett.: {guard.availability.weeklyHours}h | Rimaste: {guard.availability.remainingWeeklyHours}h
                              </p>
                            </div>
                            <div onClick={(e) => e.stopPropagation()}>
                              <Checkbox
                                checked={selectedGuards.includes(guard.id)}
                                onCheckedChange={() => toggleGuardSelection(guard.id)}
                              />
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">
                    Nessuna guardia disponibile che soddisfa i requisiti del sito
                  </p>
                )}
              </div>
            </div>
          )}

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setCreateShiftDialogOpen(false);
                setSelectedSite(null);
                setSelectedGuards([]);
                setSelectedVehicle(null);
              }}
              data-testid="button-cancel-shift"
            >
              Annulla
            </Button>
            <Button
              onClick={handleCreateShift}
              disabled={
                !selectedSite ||
                selectedGuards.length < (selectedSite?.minGuards || 0) ||
                createShiftMutation.isPending
              }
              data-testid="button-create-shift"
            >
              {createShiftMutation.isPending ? "Creazione..." : "Crea Turno"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
