import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { RefreshCw, Plus, Trash2, Edit, CheckCircle2, XCircle, AlertTriangle, Clock } from "lucide-react";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { formatDistanceToNow } from "date-fns";
import { it } from "date-fns/locale";
import { useState } from "react";

const listFormSchema = z.object({
  name: z.string().min(1, "Nome richiesto"),
  type: z.enum(["blacklist", "whitelist"], {
    required_error: "Tipo richiesto",
  }),
  url: z.string().url("URL non valida"),
  enabled: z.boolean().default(true),
  fetchIntervalMinutes: z.number().min(1).max(1440).default(10),
});

type ListFormValues = z.infer<typeof listFormSchema>;

export default function PublicLists() {
  const { toast } = useToast();
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [editingList, setEditingList] = useState<any>(null);

  const { data: lists, isLoading } = useQuery<any[]>({
    queryKey: ["/api/public-lists"],
  });

  const form = useForm<ListFormValues>({
    resolver: zodResolver(listFormSchema),
    defaultValues: {
      name: "",
      type: "blacklist",
      url: "",
      enabled: true,
      fetchIntervalMinutes: 10,
    },
  });

  const createMutation = useMutation({
    mutationFn: (data: ListFormValues) =>
      apiRequest("POST", "/api/public-lists", data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/public-lists"] });
      toast({
        title: "Lista creata",
        description: "La lista è stata aggiunta con successo",
      });
      setIsAddDialogOpen(false);
      form.reset();
    },
    onError: (error: any) => {
      toast({
        title: "Errore",
        description: error.message || "Impossibile creare la lista",
        variant: "destructive",
      });
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<ListFormValues> }) =>
      apiRequest("PATCH", `/api/public-lists/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/public-lists"] });
      toast({
        title: "Lista aggiornata",
        description: "Le modifiche sono state salvate",
      });
      setEditingList(null);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiRequest("DELETE", `/api/public-lists/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/public-lists"] });
      toast({
        title: "Lista eliminata",
        description: "La lista è stata rimossa",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Errore",
        description: error.message || "Impossibile eliminare la lista",
        variant: "destructive",
      });
    },
  });

  const syncMutation = useMutation({
    mutationFn: (id: string) =>
      apiRequest("POST", `/api/public-lists/${id}/sync`),
    onSuccess: () => {
      toast({
        title: "Sync avviato",
        description: "La sincronizzazione manuale è stata richiesta",
      });
    },
  });

  const toggleEnabled = (id: string, enabled: boolean) => {
    updateMutation.mutate({ id, data: { enabled } });
  };

  const onSubmit = (data: ListFormValues) => {
    createMutation.mutate(data);
  };

  const getStatusBadge = (list: any) => {
    if (!list.enabled) {
      return <Badge variant="outline" className="gap-1"><XCircle className="w-3 h-3" />Disabilitata</Badge>;
    }

    if (list.errorCount > 5) {
      return <Badge variant="destructive" className="gap-1"><AlertTriangle className="w-3 h-3" />Errori</Badge>;
    }

    if (list.lastSuccess) {
      return <Badge variant="default" className="gap-1 bg-green-600"><CheckCircle2 className="w-3 h-3" />OK</Badge>;
    }

    return <Badge variant="secondary" className="gap-1"><Clock className="w-3 h-3" />In attesa</Badge>;
  };

  const getTypeBadge = (type: string) => {
    if (type === "blacklist") {
      return <Badge variant="destructive">Blacklist</Badge>;
    }
    return <Badge variant="default" className="bg-blue-600">Whitelist</Badge>;
  };

  if (isLoading) {
    return (
      <div className="p-6">
        <Card>
          <CardHeader>
            <CardTitle>Caricamento...</CardTitle>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Liste Pubbliche</h1>
          <p className="text-muted-foreground mt-2">
            Gestione sorgenti blacklist e whitelist esterne (aggiornamento ogni 10 minuti)
          </p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button data-testid="button-add-list">
              <Plus className="w-4 h-4 mr-2" />
              Aggiungi Lista
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Aggiungi Lista Pubblica</DialogTitle>
              <DialogDescription>
                Configura una nuova sorgente blacklist o whitelist
              </DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Nome</FormLabel>
                      <FormControl>
                        <Input placeholder="es. Spamhaus DROP" {...field} data-testid="input-list-name" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Tipo</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger data-testid="select-list-type">
                            <SelectValue placeholder="Seleziona tipo" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="blacklist">Blacklist</SelectItem>
                          <SelectItem value="whitelist">Whitelist</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="url"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>URL</FormLabel>
                      <FormControl>
                        <Input placeholder="https://example.com/list.txt" {...field} data-testid="input-list-url" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="fetchIntervalMinutes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Intervallo Sync (minuti)</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          {...field}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                          data-testid="input-list-interval"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="enabled"
                  render={({ field }) => (
                    <FormItem className="flex items-center justify-between">
                      <FormLabel>Abilitata</FormLabel>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                          data-testid="switch-list-enabled"
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <div className="flex justify-end gap-2 pt-4">
                  <Button type="button" variant="outline" onClick={() => setIsAddDialogOpen(false)}>
                    Annulla
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending} data-testid="button-save-list">
                    {createMutation.isPending ? "Salvataggio..." : "Salva"}
                  </Button>
                </div>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Sorgenti Configurate</CardTitle>
          <CardDescription>
            {lists?.length || 0} liste configurate
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nome</TableHead>
                <TableHead>Tipo</TableHead>
                <TableHead>Stato</TableHead>
                <TableHead>IP Totali</TableHead>
                <TableHead>IP Attivi</TableHead>
                <TableHead>Ultimo Sync</TableHead>
                <TableHead className="text-right">Azioni</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {lists?.map((list: any) => (
                <TableRow key={list.id} data-testid={`row-list-${list.id}`}>
                  <TableCell className="font-medium">
                    <div>
                      <div>{list.name}</div>
                      <div className="text-xs text-muted-foreground truncate max-w-xs">
                        {list.url}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{getTypeBadge(list.type)}</TableCell>
                  <TableCell>{getStatusBadge(list)}</TableCell>
                  <TableCell data-testid={`text-total-ips-${list.id}`}>{list.totalIps?.toLocaleString() || 0}</TableCell>
                  <TableCell data-testid={`text-active-ips-${list.id}`}>{list.activeIps?.toLocaleString() || 0}</TableCell>
                  <TableCell>
                    {list.lastSuccess ? (
                      <span className="text-sm">
                        {formatDistanceToNow(new Date(list.lastSuccess), {
                          addSuffix: true,
                          locale: it,
                        })}
                      </span>
                    ) : (
                      <span className="text-sm text-muted-foreground">Mai</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Switch
                        checked={list.enabled}
                        onCheckedChange={(checked) => toggleEnabled(list.id, checked)}
                        data-testid={`switch-enable-${list.id}`}
                      />
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() => syncMutation.mutate(list.id)}
                        disabled={syncMutation.isPending}
                        data-testid={`button-sync-${list.id}`}
                      >
                        <RefreshCw className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="destructive"
                        size="icon"
                        onClick={() => {
                          if (confirm(`Eliminare la lista "${list.name}"?`)) {
                            deleteMutation.mutate(list.id);
                          }
                        }}
                        data-testid={`button-delete-${list.id}`}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {(!lists || lists.length === 0) && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                    Nessuna lista configurata. Aggiungi la prima lista.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
