import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Calendar, MapPin, Navigation, ChevronLeft, ChevronRight } from "lucide-react";
import { format, addDays, startOfWeek, parseISO, isValid } from "date-fns";
import { it } from "date-fns/locale";

interface PatrolRouteStop {
  siteId: string;
  siteName: string;
  siteAddress: string;
  sequenceOrder: number;
  latitude: string | null;
  longitude: string | null;
}

interface PatrolRoute {
  id: string;
  shiftDate: string;
  startTime: string;
  endTime: string;
  location: string;
  status: string;
  vehicleId: string | null;
  vehiclePlate: string | null;
  stops: PatrolRouteStop[];
}

export default function MyShiftsMobile() {
  // Data iniziale: inizio settimana corrente
  const [currentWeekStart, setCurrentWeekStart] = useState(() => {
    const today = new Date();
    return startOfWeek(today, { weekStartsOn: 1 });
  });

  // Query per recuperare i turni mobile della guardia loggata
  const { data: user } = useQuery<any>({
    queryKey: ["/api/auth/user"],
  });

  const { data: myRoutes, isLoading } = useQuery<PatrolRoute[]>({
    queryKey: ["/api/my-shifts/mobile", currentWeekStart.toISOString()],
    queryFn: async () => {
      const weekEnd = addDays(currentWeekStart, 6);
      const response = await fetch(
        `/api/my-shifts/mobile?startDate=${currentWeekStart.toISOString()}&endDate=${weekEnd.toISOString()}`
      );
      if (!response.ok) throw new Error("Failed to fetch patrol routes");
      return response.json();
    },
    enabled: !!user,
  });

  // Naviga settimana precedente
  const handlePreviousWeek = () => {
    setCurrentWeekStart(addDays(currentWeekStart, -7));
  };

  // Naviga settimana successiva
  const handleNextWeek = () => {
    setCurrentWeekStart(addDays(currentWeekStart, 7));
  };

  // Raggruppa i patrol routes per giorno
  const routesByDay = myRoutes?.reduce((acc, route) => {
    const date = route.shiftDate;
    if (!acc[date]) acc[date] = [];
    acc[date].push(route);
    return acc;
  }, {} as Record<string, PatrolRoute[]>) || {};

  // Genera array di 7 giorni della settimana
  const weekDays = Array.from({ length: 7 }, (_, i) => addDays(currentWeekStart, i));

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

  const statusLabels: Record<string, string> = {
    planned: "Pianificato",
    in_progress: "In Corso",
    completed: "Completato",
    cancelled: "Annullato",
  };

  const statusColors: Record<string, string> = {
    planned: "bg-blue-500/10 text-blue-500 border-blue-500/20",
    in_progress: "bg-green-500/10 text-green-500 border-green-500/20",
    completed: "bg-gray-500/10 text-gray-500 border-gray-500/20",
    cancelled: "bg-red-500/10 text-red-500 border-red-500/20",
  };

  return (
    <div className="h-full flex flex-col p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold" data-testid="title-my-shifts-mobile">
            I Miei Turni Pattuglia
          </h1>
          <p className="text-sm text-muted-foreground">
            Visualizza i tuoi percorsi di pattuglia con sequenza tappe
          </p>
        </div>
      </div>

      {/* Navigazione settimana */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <Button
              variant="outline"
              size="sm"
              onClick={handlePreviousWeek}
              data-testid="button-prev-week"
            >
              <ChevronLeft className="h-4 w-4 mr-1" />
              Settimana Precedente
            </Button>
            <CardTitle className="text-center">
              {format(currentWeekStart, "dd MMMM", { locale: it })} -{" "}
              {format(addDays(currentWeekStart, 6), "dd MMMM yyyy", { locale: it })}
            </CardTitle>
            <Button
              variant="outline"
              size="sm"
              onClick={handleNextWeek}
              data-testid="button-next-week"
            >
              Settimana Successiva
              <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          </div>
        </CardHeader>
      </Card>

      {/* Loading state */}
      {isLoading && (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            Caricamento turni pattuglia...
          </CardContent>
        </Card>
      )}

      {/* Griglia giorni settimana */}
      {!isLoading && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {weekDays.map((day) => {
            const dateStr = format(day, "yyyy-MM-dd");
            const dayRoutes = routesByDay[dateStr] || [];

            return (
              <Card key={dateStr} data-testid={`day-card-${dateStr}`}>
                <CardHeader className="pb-3">
                  <CardTitle className="text-lg">
                    {format(day, "EEEE dd/MM", { locale: it })}
                  </CardTitle>
                  <CardDescription>
                    {dayRoutes.length === 0
                      ? "Nessuna pattuglia"
                      : `${dayRoutes.length} pattuglia${dayRoutes.length > 1 ? "e" : ""}`}
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-3">
                  {dayRoutes.length === 0 ? (
                    <div className="text-center py-4 text-sm text-muted-foreground">
                      Riposo
                    </div>
                  ) : (
                    dayRoutes.map((route) => (
                      <div
                        key={route.id}
                        className="border rounded-lg p-3 space-y-3"
                        data-testid={`patrol-route-${route.id}`}
                      >
                        {/* Header pattuglia */}
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1 space-y-1">
                            <div className="flex items-center gap-2">
                              <Navigation className="h-4 w-4 text-muted-foreground" />
                              <span className="font-semibold text-sm">
                                Pattuglia {locationLabels[route.location]}
                              </span>
                            </div>
                            <div className="flex items-center gap-1 text-xs text-muted-foreground">
                              <MapPin className="h-3 w-3" />
                              <span>{route.stops.length} tappe</span>
                            </div>
                          </div>
                          <Badge 
                            variant="outline" 
                            className={statusColors[route.status] || ""}
                          >
                            {statusLabels[route.status] || route.status}
                          </Badge>
                        </div>

                        {/* Sequenza tappe */}
                        <div className="space-y-2 pl-4 border-l-2 border-muted">
                          {route.stops
                            .sort((a, b) => a.sequenceOrder - b.sequenceOrder)
                            .map((stop, index) => (
                              <div
                                key={stop.siteId}
                                className="space-y-1"
                                data-testid={`stop-${index}`}
                              >
                                <div className="flex items-start gap-2">
                                  <Badge className="bg-green-600 h-5 w-5 p-0 flex items-center justify-center text-xs">
                                    {stop.sequenceOrder}
                                  </Badge>
                                  <div className="flex-1 space-y-0.5">
                                    <p className="text-sm font-medium leading-tight">
                                      {stop.siteName}
                                    </p>
                                    <p className="text-xs text-muted-foreground leading-tight">
                                      {stop.siteAddress}
                                    </p>
                                  </div>
                                </div>
                              </div>
                            ))}
                        </div>

                        {/* Info veicolo */}
                        {route.vehiclePlate && (
                          <div className="pt-2 border-t text-xs text-muted-foreground">
                            Automezzo: {route.vehiclePlate}
                          </div>
                        )}
                      </div>
                    ))
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
