import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Shield, Plus, Trash2, CheckCircle2, XCircle } from "lucide-react";
import { format } from "date-fns";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import type { Whitelist } from "@shared/schema";
import { insertWhitelistSchema } from "@shared/schema";
import { useToast } from "@/hooks/use-toast";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";

const whitelistFormSchema = insertWhitelistSchema.extend({
  ipAddress: z.string()
    .min(7, "Inserisci un IP valido")
    .regex(/^(\d{1,3}\.){3}\d{1,3}$/, "Formato IP non valido")
    .refine((ip) => {
      const parts = ip.split('.').map(Number);
      return parts.every(part => part >= 0 && part <= 255);
    }, "Ogni ottetto deve essere tra 0 e 255"),
});

export default function WhitelistPage() {
  const { toast } = useToast();
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);

  const form = useForm<z.infer<typeof whitelistFormSchema>>({
    resolver: zodResolver(whitelistFormSchema),
    defaultValues: {
      ipAddress: "",
      comment: "",
      reason: "",
      active: true,
    },
  });

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

  const addMutation = useMutation({
    mutationFn: async (data: z.infer<typeof whitelistFormSchema>) => {
      return await apiRequest("POST", "/api/whitelist", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/whitelist"] });
      toast({
        title: "IP aggiunto",
        description: "L'indirizzo IP è stato aggiunto alla whitelist",
      });
      setIsAddDialogOpen(false);
      form.reset();
    },
    onError: (error: any) => {
      toast({
        title: "Errore",
        description: error.message || "Impossibile aggiungere l'IP alla whitelist",
        variant: "destructive",
      });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await apiRequest("DELETE", `/api/whitelist/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/whitelist"] });
      toast({
        title: "IP rimosso",
        description: "L'indirizzo IP è stato rimosso dalla whitelist",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Errore",
        description: error.message || "Impossibile rimuovere l'IP dalla whitelist",
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: z.infer<typeof whitelistFormSchema>) => {
    addMutation.mutate(data);
  };

  return (
    <div className="flex flex-col gap-6 p-6" data-testid="page-whitelist">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-semibold" data-testid="text-page-title">Whitelist IP</h1>
          <p className="text-muted-foreground" data-testid="text-page-subtitle">
            Gestisci gli indirizzi IP fidati che non verranno bloccati
          </p>
        </div>

        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button data-testid="button-add-whitelist">
              <Plus className="h-4 w-4 mr-2" />
              Aggiungi IP
            </Button>
          </DialogTrigger>
          <DialogContent data-testid="dialog-add-whitelist">
            <DialogHeader>
              <DialogTitle>Aggiungi IP alla Whitelist</DialogTitle>
              <DialogDescription>
                Inserisci l'indirizzo IP che vuoi proteggere dal blocco automatico
              </DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 py-4">
                <FormField
                  control={form.control}
                  name="ipAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Indirizzo IP *</FormLabel>
                      <FormControl>
                        <Input placeholder="192.168.1.100" {...field} data-testid="input-ip" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="reason"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Motivo</FormLabel>
                      <FormControl>
                        <Input placeholder="Es: Server backup" {...field} data-testid="input-reason" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="comment"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Note</FormLabel>
                      <FormControl>
                        <Textarea placeholder="Note aggiuntive..." {...field} data-testid="input-comment" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <DialogFooter>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => setIsAddDialogOpen(false)} 
                    data-testid="button-cancel"
                  >
                    Annulla
                  </Button>
                  <Button type="submit" disabled={addMutation.isPending} data-testid="button-confirm-add">
                    {addMutation.isPending ? "Aggiunta..." : "Aggiungi"}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      <Card data-testid="card-whitelist">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            IP Protetti ({whitelist?.length || 0})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="text-center py-8 text-muted-foreground" data-testid="text-loading">
              Caricamento...
            </div>
          ) : whitelist && whitelist.length > 0 ? (
            <div className="space-y-3">
              {whitelist.map((item) => (
                <div
                  key={item.id}
                  className="p-4 rounded-lg border hover-elevate"
                  data-testid={`whitelist-item-${item.id}`}
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 space-y-1">
                      <div className="flex items-center gap-2">
                        <p className="font-mono font-medium" data-testid={`text-ip-${item.id}`}>
                          {item.ipAddress}
                        </p>
                        {item.active ? (
                          <CheckCircle2 className="h-4 w-4 text-green-500" data-testid={`icon-active-${item.id}`} />
                        ) : (
                          <XCircle className="h-4 w-4 text-muted-foreground" data-testid={`icon-inactive-${item.id}`} />
                        )}
                      </div>
                      {item.reason && (
                        <p className="text-sm text-muted-foreground" data-testid={`text-reason-${item.id}`}>
                          <span className="font-medium">Motivo:</span> {item.reason}
                        </p>
                      )}
                      {item.comment && (
                        <p className="text-sm text-muted-foreground" data-testid={`text-comment-${item.id}`}>
                          {item.comment}
                        </p>
                      )}
                      <p className="text-xs text-muted-foreground" data-testid={`text-created-${item.id}`}>
                        Aggiunto il {format(new Date(item.createdAt), "dd/MM/yyyy HH:mm")}
                        {item.createdBy && ` da ${item.createdBy}`}
                      </p>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => deleteMutation.mutate(item.id)}
                      disabled={deleteMutation.isPending}
                      data-testid={`button-delete-${item.id}`}
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-12 text-muted-foreground" data-testid="text-empty">
              <Shield className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p className="font-medium">Nessun IP in whitelist</p>
              <p className="text-sm mt-2">Aggiungi indirizzi IP fidati per proteggerli dal blocco automatico</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
