import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Vehicle, Site, ShiftWithDetails } from "@shared/schema";
import { Building2, Car, MapPin, Calendar } from "lucide-react";
import { format } from "date-fns";
import { it } from "date-fns/locale";

const locationLabels = {
  all: "Tutte le Sedi",
  roccapiemonte: "Roccapiemonte",
  milano: "Milano",
  roma: "Roma"
} as const;

const vehicleStatusLabels = {
  available: "Disponibile",
  in_use: "In uso",
  maintenance: "In manutenzione",
  out_of_service: "Fuori servizio",
};

const vehicleStatusColors = {
  available: "bg-green-500/10 text-green-500 border-green-500/20",
  in_use: "bg-blue-500/10 text-blue-500 border-blue-500/20",
  maintenance: "bg-orange-500/10 text-orange-500 border-orange-500/20",
  out_of_service: "bg-red-500/10 text-red-500 border-red-500/20",
};

export default function Planning() {
  const [selectedLocation, setSelectedLocation] = useState<string>("all");

  const { data: vehicles = [], isLoading: loadingVehicles } = useQuery<Vehicle[]>({
    queryKey: ["/api/vehicles"],
  });

  const { data: sites = [], isLoading: loadingSites } = useQuery<Site[]>({
    queryKey: ["/api/sites"],
  });

  const { data: shifts = [], isLoading: loadingShifts } = useQuery<ShiftWithDetails[]>({
    queryKey: ["/api/shifts/active"],
  });

  // Filter by location
  const filteredVehicles = selectedLocation === "all" 
    ? vehicles 
    : vehicles.filter(v => v.location === selectedLocation);

  const filteredSites = selectedLocation === "all"
    ? sites
    : sites.filter(s => s.location === selectedLocation);

  const filteredShifts = selectedLocation === "all"
    ? shifts
    : shifts.filter(s => {
        const site = sites.find(site => site.id === s.siteId);
        return site?.location === selectedLocation;
      });

  const isLoading = loadingVehicles || loadingSites || loadingShifts;

  // Calculate stats
  const availableVehicles = filteredVehicles.filter(v => v.status === "available").length;
  const inUseVehicles = filteredVehicles.filter(v => v.status === "in_use").length;
  const activeSites = filteredSites.filter(s => s.isActive).length;
  const activeShifts = filteredShifts.filter(s => s.status === "active").length;

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-semibold mb-2">Pianificazione Operativa</h1>
          <p className="text-muted-foreground">
            Vista per sede con gestione automezzi e turni attivi
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Building2 className="h-5 w-5 text-muted-foreground" />
          <Select value={selectedLocation} onValueChange={setSelectedLocation}>
            <SelectTrigger className="w-[200px]" data-testid="select-location">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Tutte le Sedi</SelectItem>
              <SelectItem value="roccapiemonte">Roccapiemonte</SelectItem>
              <SelectItem value="milano">Milano</SelectItem>
              <SelectItem value="roma">Roma</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-muted-foreground">Caricamento dati...</div>
      ) : (
        <>
          {/* Stats Summary */}
          <div className="grid gap-4 md:grid-cols-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Turni Attivi</CardTitle>
                <Calendar className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold" data-testid="text-active-shifts">{activeShifts}</div>
                <p className="text-xs text-muted-foreground">
                  {locationLabels[selectedLocation as keyof typeof locationLabels]}
                </p>
              </CardContent>
            </Card>
            
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Siti Attivi</CardTitle>
                <MapPin className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold" data-testid="text-active-sites">{activeSites}</div>
                <p className="text-xs text-muted-foreground">
                  su {filteredSites.length} totali
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Automezzi Disponibili</CardTitle>
                <Car className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-green-500" data-testid="text-available-vehicles">
                  {availableVehicles}
                </div>
                <p className="text-xs text-muted-foreground">
                  su {filteredVehicles.length} totali
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Automezzi in Uso</CardTitle>
                <Car className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-blue-500" data-testid="text-inuse-vehicles">
                  {inUseVehicles}
                </div>
                <p className="text-xs text-muted-foreground">
                  assegnati a turni
                </p>
              </CardContent>
            </Card>
          </div>

          {/* Vehicles List */}
          <Card>
            <CardHeader>
              <CardTitle>Automezzi - {locationLabels[selectedLocation as keyof typeof locationLabels]}</CardTitle>
              <CardDescription>
                Stato e disponibilità automezzi per sede selezionata
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {filteredVehicles.map((vehicle) => (
                  <div
                    key={vehicle.id}
                    className="flex items-center justify-between p-4 rounded-lg border bg-card hover-elevate"
                    data-testid={`card-vehicle-${vehicle.id}`}
                  >
                    <div className="flex items-center gap-4">
                      <div className="p-2 rounded-lg bg-muted">
                        <Car className="h-6 w-6" />
                      </div>
                      <div>
                        <p className="font-semibold" data-testid={`text-vehicle-${vehicle.id}`}>
                          {vehicle.brand} {vehicle.model}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {vehicle.licensePlate}
                          {vehicle.year && ` • Anno ${vehicle.year}`}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge variant="outline" className="capitalize">
                        {locationLabels[vehicle.location as keyof typeof locationLabels]}
                      </Badge>
                      <Badge
                        variant="outline"
                        className={vehicleStatusColors[vehicle.status]}
                        data-testid={`badge-status-${vehicle.id}`}
                      >
                        {vehicleStatusLabels[vehicle.status]}
                      </Badge>
                    </div>
                  </div>
                ))}
                {filteredVehicles.length === 0 && (
                  <div className="text-center py-8 text-muted-foreground">
                    <Car className="h-12 w-12 mx-auto mb-2 opacity-50" />
                    <p>Nessun automezzo disponibile per questa sede</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Active Shifts */}
          <Card>
            <CardHeader>
              <CardTitle>Turni Attivi - {locationLabels[selectedLocation as keyof typeof locationLabels]}</CardTitle>
              <CardDescription>
                Turni in corso per sede selezionata
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {filteredShifts.filter(s => s.status === "active").map((shift) => {
                  const site = sites.find(s => s.id === shift.siteId);
                  
                  return (
                    <div
                      key={shift.id}
                      className="flex items-center justify-between p-4 rounded-lg border bg-card hover-elevate"
                      data-testid={`card-shift-${shift.id}`}
                    >
                      <div className="flex items-center gap-4">
                        <div className="p-2 rounded-lg bg-muted">
                          <Calendar className="h-6 w-6" />
                        </div>
                        <div>
                          <p className="font-semibold" data-testid={`text-shift-site-${shift.id}`}>
                            {site?.name || "Sito sconosciuto"}
                          </p>
                          <p className="text-sm text-muted-foreground">
                            {format(new Date(shift.startTime), "HH:mm", { locale: it })} - 
                            {format(new Date(shift.endTime), "HH:mm", { locale: it })}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        <Badge variant="outline" className="capitalize">
                          {site && locationLabels[site.location as keyof typeof locationLabels]}
                        </Badge>
                        <Badge variant="default">
                          Attivo
                        </Badge>
                      </div>
                    </div>
                  );
                })}
                {filteredShifts.filter(s => s.status === "active").length === 0 && (
                  <div className="text-center py-8 text-muted-foreground">
                    <Calendar className="h-12 w-12 mx-auto mb-2 opacity-50" />
                    <p>Nessun turno attivo per questa sede</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
