import { Confirm } from "~/components/confirm";
import { Button, buttonVariants } from "~/components/ui/button";
import {
  Check,
  ChevronsUpDown,
  CircleCheck,
  ClipboardPaste,
  Cog,
  ExternalLink,
  FolderKanban,
  Pen,
  Plus,
  Trash2,
  Wrench,
} from "lucide-react";
import type {
  Storageindex,
  StorageindexId,
} from "~/schemas/public/Storageindex";
import { Label } from "~/components/ui/label";
import { UploadModal } from "~/components/upload_modal";
import { ExtIcon } from "~/components/area-riservata/allegati";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "~/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "~/components/ui/command";
import { api } from "~/utils/api";
import toast from "react-hot-toast";
import {
  Credenza,
  CredenzaBody,
  CredenzaClose,
  CredenzaContent,
  CredenzaDescription,
  CredenzaFooter,
  CredenzaHeader,
  CredenzaTitle,
  CredenzaTrigger,
} from "~/components/custom_ui/credenza";
import { LoadingPage } from "~/components/loading";
import Link from "next/link";
import { cn } from "~/lib/utils";
import { useRef, useState } from "react";
import { z } from "zod";
import { Separator } from "~/components/ui/separator";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import type { ServizioAnnunciUpdate } from "~/schemas/public/ServizioAnnunci";
import { Switch } from "~/components/ui/switch";
import { useServizio, useServizioAnnuncio } from "~/providers/ServizioProvider";
import {
  AnimatedButton,
  type AnimatedButtonRef,
} from "~/components/custom_ui/animated-button";
import type { AnnunciId } from "~/schemas/public/Annunci";

export const AnnuncioActions = () => {
  const { servizioId, userId, isAdmin } = useServizio();
  const { data, annuncioId } = useServizioAnnuncio();

  const utils = api.useUtils();
  const { mutate } = api.servizio.removeAnnuncioServizio.useMutation({
    onSuccess: async () => {
      await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
      await utils.servizio.getCompatibileAnnunci.invalidate({
        servizioId,
      });
      toast.success("Annuncio rimosso");
    },
    onError: (error) => {
      console.error(error);
      toast.error("Errore durante la rimozione dell'annuncio");
    },
  });

  if ((!isAdmin && data.open_contatti_at == null) || isAdmin) {
    return (
      <div className="flex w-full flex-wrap justify-start gap-3 sm:justify-end">
        {isAdmin && data.user_confirmed_at != null && <AdminLavoraConferma />}
        {isAdmin && data.accettato_conferma_at != null && (
          <>
            <AdminContratto />
            {data.gestionale_id && (
              <Link
                aria-label="Open Gestionale"
                href={`https://win-jk822fggr6b:480/id/${data.gestionale_id}`}
                target="_blank"
              >
                <Button className="flex items-center gap-2">
                  <FolderKanban /> Apri in gestionale
                </Button>
              </Link>
            )}
          </>
        )}
        {isAdmin && (
          <Link
            href={`/area-riservata/admin/edit-annuncio/${annuncioId}`}
            target="_blank"
          >
            <Button
              aria-label="Edit Annuncio"
              variant="secondary"
              className="flex w-full items-center gap-2"
              size="sm"
            >
              <Cog className="size-6" /> Modifica
            </Button>
          </Link>
        )}

        <Confirm
          title="Elimina annuncio"
          description="Sei sicuro di voler eliminare l'annuncio?"
          onConfirm={() => {
            mutate({
              servizioId,
              annuncioId,
            });
          }}
        >
          <Button
            aria-label="Delete Annuncio"
            variant="secondary"
            className="flex items-center gap-2"
            size="sm"
          >
            <Trash2 className="size-6" />
            Elimina
          </Button>
        </Confirm>
      </div>
    );
  }
  return null;
};

const ContrattoImportSchema = z.object({
  gestionale_id: z.number().nullable(),
  contratto_decorrenza: z.coerce.date().nullable(),
  contratto_scadenza: z.coerce.date().nullable(),
  contratto_tipo: z
    .enum([
      "Transitorio",
      "Agevolato",
      "4 + 4",
      "30 Giorni",
      "Transi.Age",
      "Foresteria",
      "Commerciale",
    ])
    .nullable(),
});

type ContrattoImportObj = z.infer<typeof ContrattoImportSchema>;

const parseContrattoImport = (ingest: string) => {
  let parsedJson: unknown;
  try {
    parsedJson = JSON.parse(ingest);
  } catch {
    toast.error(
      'Stringa non valida, clicca "copia stringa" nel gestionale e poi questo pulsante',
    );
    return undefined;
  }
  const parsed = ContrattoImportSchema.safeParse(parsedJson);
  if (parsed.success) {
    return parsed.data;
  } else {
    console.error("Invalid format:", parsed.error);
    return undefined;
  }
};

const ContrattoImport = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { data } = useServizioAnnuncio();
  const [contratto, setContratto] = useState<ContrattoImportObj | undefined>({
    gestionale_id: data.gestionale_id,
    contratto_decorrenza: data.contratto_decorrenza,
    contratto_scadenza: data.contratto_scadenza,
    contratto_tipo: data.contratto_tipo as ContrattoImportObj["contratto_tipo"],
  });
  const handleSave = () => {
    handleUpdate({
      ...contratto,
    });
  };
  return (
    <Card>
      <CardHeader>
        <CardTitle>Dati Contratto</CardTitle>
        <CardDescription className="sr-only">desc</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex items-center gap-3">
          <Button
            aria-label="Import Contratto"
            onClick={async () => {
              const clipboardText = await navigator.clipboard.readText();

              setContratto(parseContrattoImport(clipboardText));
            }}
            className="flex items-center gap-2"
            variant="info"
          >
            <ClipboardPaste className="size-4" />
            Clicca qui per importare la stringa dal gestionale
          </Button>
          <Button
            aria-label="Reset Contratto"
            onClick={async () => {
              setContratto({
                gestionale_id: null,
                contratto_decorrenza: null,
                contratto_scadenza: null,
                contratto_tipo: null,
              });
            }}
            className="flex items-center gap-2"
            variant="destructive"
          >
            <Trash2 className="size-4" />
            Reset
          </Button>
        </div>
        {contratto ? (
          <div className="flex flex-col gap-2">
            <p>
              <span className="font-semibold">ID Gestionale: </span>
              {contratto.gestionale_id}{" "}
              <Button
                aria-label="Edit Gestionale ID"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica l'ID gestionale del contratto:",
                    contratto.gestionale_id?.toString() || "",
                  );
                  if (newValue !== null) {
                    setContratto((prev) =>
                      prev
                        ? { ...prev, gestionale_id: parseInt(newValue) }
                        : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">Decorrenza: </span>
              {contratto.contratto_decorrenza &&
                new Date(contratto.contratto_decorrenza).toLocaleDateString(
                  "it-IT",
                )}{" "}
              <Button
                aria-label="Edit Decorrenza"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica la decorrenza del contratto (DD/MM/YYYY):",
                    contratto.contratto_decorrenza
                      ? new Date(
                          contratto.contratto_decorrenza,
                        ).toLocaleDateString("it-IT")
                      : "",
                  );
                  if (newValue !== null) {
                    setContratto((prev) =>
                      prev
                        ? {
                            ...prev,
                            contratto_decorrenza: new Date(newValue),
                          }
                        : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">Scadenza: </span>
              {contratto.contratto_scadenza &&
                new Date(contratto.contratto_scadenza).toLocaleDateString(
                  "it-IT",
                )}{" "}
              <Button
                aria-label="Edit Scadenza"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica la scadenza del contratto (DD/MM/YYYY):",
                    contratto.contratto_scadenza
                      ? new Date(
                          contratto.contratto_scadenza,
                        ).toLocaleDateString("it-IT")
                      : "",
                  );
                  if (newValue !== null) {
                    setContratto((prev) =>
                      prev
                        ? {
                            ...prev,
                            contratto_scadenza: new Date(newValue),
                          }
                        : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">Tipo di contratto: </span>
              {contratto.contratto_tipo}{" "}
              <Button
                aria-label="Edit Tipo di contratto"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica il tipo di contratto:",
                    contratto.contratto_tipo || "",
                  );
                  if (
                    newValue !== null &&
                    ContrattoImportSchema.shape.contratto_tipo.safeParse(
                      newValue,
                    ).success
                  ) {
                    setContratto((prev) =>
                      prev
                        ? {
                            ...prev,
                            contratto_tipo:
                              newValue as ContrattoImportObj["contratto_tipo"],
                          }
                        : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
          </div>
        ) : (
          <p>Inserisci la stringa dal gestionale e elabora</p>
        )}
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Contratto"
          onClick={() => {
            handleSave();
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

const AdminContratto = () => {
  const { userId, servizioId } = useServizio();
  const { data, annuncioId } = useServizioAnnuncio();

  const [open, setOpen] = useState(false);

  const utils = api.useUtils();

  const { mutate: updateServizio } =
    api.servizio.updateServizioAnnunci.useMutation({
      onSuccess: async () => {
        await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
        await utils.servizio.getServizio.invalidate({
          servizioId,
        });

        toast.success("Dati salvati con successo");
      },
      onError: (error) => {
        toast.error(error.message);
      },
    });

  const handleUpdate = (upd: ServizioAnnunciUpdate) => {
    updateServizio({
      servizioId,
      annuncioId,
      data: {
        ...upd,
      },
    });
  };

  return (
    <Credenza open={open} onOpenChange={setOpen}>
      <CredenzaTrigger asChild>
        <Button
          variant="secondary"
          className="flex w-fit items-center gap-2"
          aria-label="Open Contratto Section"
        >
          {data.doc_contratto_added ? (
            <CircleCheck className="size-7" />
          ) : (
            <Wrench className="size-7" />
          )}
          Sezione Contratto
        </Button>
      </CredenzaTrigger>
      <CredenzaContent className="max-h-[90vh] max-w-4xl px-3">
        <CredenzaHeader>
          <CredenzaTitle>Sezione Contratto</CredenzaTitle>
          <CredenzaDescription className="sr-only">
            Contratto modal
          </CredenzaDescription>
        </CredenzaHeader>
        <CredenzaBody className="max-h-[80vh] overflow-auto pb-5">
          <div className="flex flex-col gap-8">
            <ContrattoSection handleUpdate={handleUpdate} />
            <Separator />
            <ContrattoImport handleUpdate={handleUpdate} />
            <Separator />
            <RicevutaSection handleUpdate={handleUpdate} />
          </div>
        </CredenzaBody>

        <CredenzaFooter>
          <CredenzaClose asChild>
            <Button variant="outline" aria-label="Close Credenza">
              Chiudi
            </Button>
          </CredenzaClose>
        </CredenzaFooter>
      </CredenzaContent>
    </Credenza>
  );
};

const ContrattoSection = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { userId } = useServizio();
  const { data } = useServizioAnnuncio();
  const [selectedDoc, setSelectedDoc] = useState<StorageindexId | null>(
    data.doc_contratto_ref,
  );

  const utils = api.useUtils();

  const { data: files, isLoading } = api.storage.getAll.useQuery();

  const { mutate: setUserStorage } = api.storage.addUserStorage.useMutation({
    onSuccess: async () => {
      await utils.storage.getUserStorage.invalidate({
        userId,
      });
      await utils.storage.getAll.invalidate();
    },
  });

  const handleSave = () => {
    handleUpdate({
      doc_contratto_ref: selectedDoc,
      doc_contratto_added: selectedDoc != null,
    });
    if (selectedDoc) {
      setUserStorage({
        userId,
        fileId: selectedDoc,
      });
    }
  };

  if (isLoading) return <LoadingPage />;
  if (files == undefined) {
    return <p>Errore nel caricamento dei documenti</p>;
  }
  return (
    <Card>
      <CardHeader>
        <CardTitle>Documento del Contratto</CardTitle>
        <CardDescription>contratto di locazione</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {selectedDoc && (
          <div className="flex flex-wrap items-center gap-3">
            <DocInfo storageId={selectedDoc} />
            <Button
              aria-label="Reset Contratto"
              variant="destructive"
              className="flex items-center gap-3"
              onClick={() => {
                handleUpdate({
                  doc_contratto_ref: null,
                  doc_contratto_added: false,
                });
                setSelectedDoc(null);
              }}
            >
              <Trash2 /> Reset
            </Button>
          </div>
        )}
        <DocCombo
          files={files}
          onSelect={(f) => {
            setSelectedDoc(f.id);
          }}
          current={selectedDoc}
        />
        <UploadModal isAdmin userId={userId} />
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Contratto"
          onClick={() => {
            handleSave();
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

const RicevutaSection = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { userId } = useServizio();
  const { data } = useServizioAnnuncio();
  const [selectedDoc, setSelectedDoc] = useState<StorageindexId | null>(
    data.doc_registrazione_ref,
  );

  const utils = api.useUtils();

  const { data: files, isLoading } = api.storage.getAll.useQuery();

  const { mutate: setUserStorage } = api.storage.addUserStorage.useMutation({
    onSuccess: async () => {
      await utils.storage.getUserStorage.invalidate({
        userId,
      });
      await utils.storage.getAll.invalidate();
    },
  });

  const handleSave = () => {
    handleUpdate({
      doc_registrazione_ref: selectedDoc,
      doc_registrazione_added: selectedDoc != null,
    });
    if (selectedDoc) {
      setUserStorage({
        userId,
        fileId: selectedDoc,
      });
    }
  };

  if (isLoading) return <LoadingPage />;
  if (files == undefined) {
    return <p>Errore nel caricamento dei documenti</p>;
  }
  return (
    <Card>
      <CardHeader>
        <CardTitle>Ricevuta di Registrazione</CardTitle>
        <CardDescription className="sr-only">desc</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {selectedDoc && (
          <div className="flex flex-wrap items-center gap-3">
            <DocInfo storageId={selectedDoc} />
            <Button
              aria-label="Reset Ricevuta"
              variant="destructive"
              className="flex items-center gap-3"
              onClick={() => {
                handleUpdate({
                  doc_registrazione_ref: null,
                  doc_registrazione_added: false,
                });
                setSelectedDoc(null);
              }}
            >
              <Trash2 /> Reset
            </Button>
          </div>
        )}
        <DocCombo
          files={files}
          onSelect={(f) => {
            setSelectedDoc(f.id);
          }}
          current={selectedDoc}
        />
        <UploadModal isAdmin userId={userId} />
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Ricevuta"
          onClick={() => {
            handleSave();
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

const AdminLavoraConferma = () => {
  const { userId, servizioId } = useServizio();
  const { data, annuncioId } = useServizioAnnuncio();

  const [open, setOpen] = useState(false);

  const utils = api.useUtils();

  const { mutate: updateServizio } =
    api.servizio.updateServizioAnnunci.useMutation({
      onSuccess: async () => {
        await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
        await utils.servizio.getServizio.invalidate({
          servizioId,
        });

        toast.success("Dati salvati con successo");
      },
      onError: (error) => {
        toast.error(error.message);
      },
    });

  const handleUpdate = (upd: ServizioAnnunciUpdate) => {
    updateServizio({
      servizioId,
      annuncioId,
      data: {
        ...upd,
      },
    });
  };

  return (
    <Credenza open={open} onOpenChange={setOpen}>
      <CredenzaTrigger asChild>
        <Button
          variant="secondary"
          className="flex w-fit items-center gap-2"
          aria-label="Open Lavora Conferma Section"
        >
          {data.hasConfermaAdmin ? (
            <CircleCheck className="size-7" />
          ) : (
            <Wrench className="size-7" />
          )}
          Lavora conferma
        </Button>
      </CredenzaTrigger>
      <CredenzaContent className="max-h-[90vh] w-full px-3 sm:max-w-4xl">
        <CredenzaHeader>
          <CredenzaTitle>Lavorazione conferma</CredenzaTitle>
          <CredenzaDescription className="sr-only">
            Consegna status modal
          </CredenzaDescription>
        </CredenzaHeader>
        <CredenzaBody className="max-h-[80vh] w-full overflow-y-auto pb-5">
          <div className="flex flex-col gap-8">
            <DocSection handleUpdate={handleUpdate} />
            <Separator />
            <Caparra handleUpdate={handleUpdate} />
            <Separator />
            <SendConferma handleUpdate={handleUpdate} />
          </div>
        </CredenzaBody>

        <CredenzaFooter>
          <CredenzaClose asChild>
            <Button variant="outline" aria-label="Close Credenza">
              Chiudi
            </Button>
          </CredenzaClose>
        </CredenzaFooter>
      </CredenzaContent>
    </Credenza>
  );
};

const DocSection = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { userId } = useServizio();
  const { data } = useServizioAnnuncio();
  const [selectedDoc, setSelectedDoc] = useState<StorageindexId | null>(
    data.doc_conferma_ref,
  );

  const utils = api.useUtils();

  const { data: files, isLoading } = api.storage.getAll.useQuery();

  const { mutate: setUserStorage } = api.storage.addUserStorage.useMutation({
    onSuccess: async () => {
      await utils.storage.getUserStorage.invalidate({
        userId,
      });
      await utils.storage.getAll.invalidate();
    },
  });

  const handleSave = () => {
    handleUpdate({
      doc_conferma_ref: selectedDoc,
      doc_conferma_added: selectedDoc != null,
    });
    if (selectedDoc) {
      setUserStorage({
        userId,
        fileId: selectedDoc,
      });
    }
  };

  if (isLoading) return <LoadingPage />;
  if (files == undefined) {
    return <p>Errore nel caricamento dei documenti</p>;
  }
  return (
    <Card>
      <CardHeader>
        <CardTitle>Documento di Conferma</CardTitle>
        <CardDescription>
          documento che l&apos;utente vedra alla conferma
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {selectedDoc && (
          <div className="flex flex-wrap items-center gap-3">
            <DocInfo storageId={selectedDoc} />

            <Button
              aria-label="Reset Conferma"
              variant="destructive"
              className="flex items-center gap-3"
              onClick={() => {
                handleUpdate({
                  doc_conferma_ref: null,
                  doc_conferma_added: false,
                });
              }}
            >
              <Trash2 /> Reset
            </Button>
          </div>
        )}
        <DocCombo
          files={files}
          onSelect={(f) => {
            setSelectedDoc(f.id);
          }}
          current={selectedDoc}
        />
        <UploadModal isAdmin userId={userId} />
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Conferma"
          onClick={() => {
            handleSave();
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

const DocInfo = ({ storageId }: { storageId: StorageindexId }) => {
  const { data: file_info } = api.storage.getStorageFromId.useQuery({
    storageId,
  });
  if (!file_info) return null;
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Label htmlFor="selected-file">File Selezionato: </Label>
      <Link
        aria-label="Open Selected File"
        href={`/area-riservata/allegato-view/${storageId}`}
        target="_blank"
        className={cn(
          buttonVariants({
            variant: "outline",
          }),
          "flex w-fit items-center justify-center gap-2",
        )}
        id="selected-file"
      >
        {file_info.ext && <ExtIcon ext={file_info.ext} />}
        {file_info.filename}
        <ExternalLink className="size-4" />
      </Link>
    </div>
  );
};

const DocCombo = ({
  files,
  onSelect,
  current,
}: {
  files: Storageindex[];
  onSelect: (file: Storageindex) => void;
  current: StorageindexId | null;
}) => {
  const [open, setOpen] = useState(false);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          aria-label="Select Existing File"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-auto justify-between"
        >
          Seleziona file esistente...
          <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0">
        <Command>
          <CommandInput placeholder="Cerca Documento..." />
          <CommandList>
            <CommandEmpty>Nessun file.</CommandEmpty>
            <CommandGroup>
              {files.map((file) => (
                <CommandItem
                  key={file.id}
                  value={file.id}
                  onSelect={(currentValue) => {
                    if (currentValue !== current) {
                      onSelect(files.find((f) => f.id === currentValue)!);
                    }
                    setOpen(false);
                  }}
                >
                  <span className="flex items-center gap-2">
                    {file.ext && <ExtIcon ext={file.ext} />}
                    <span className="block font-medium">{file.filename}</span>
                    {current === file.id && (
                      <Check className="text-accent-foreground size-4" />
                    )}
                  </span>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};

const CaparraSchema = z.object({
  caparra_causale: z.string().nullable(),
  caparra_iban: z.string().nullable(),
  caparra_importo: z.string().nullable(),
  caparra_intestazione: z.string().nullable(),
});

type CaparraObj = z.infer<typeof CaparraSchema>;

const parseCaparra = (ingest: string) => {
  let parsedJson: unknown;
  try {
    parsedJson = JSON.parse(ingest);
  } catch {
    toast.error(
      'Stringa non valida, clicca "copia stringa" nel gestionale e poi questo pulsante',
    );
    return undefined;
  }
  const parsed = CaparraSchema.safeParse(parsedJson);
  if (parsed.success) {
    return parsed.data;
  } else {
    console.error("Invalid caparra format:", parsed.error);
    return undefined;
  }
};

const Caparra = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { data } = useServizioAnnuncio();
  const [caparra, setCaparra] = useState<CaparraObj | undefined>({
    caparra_causale: data.caparra_causale,
    caparra_iban: data.caparra_iban,
    caparra_importo: data.caparra_importo,
    caparra_intestazione: data.caparra_intestazione,
  });
  const handleSave = () => {
    handleUpdate({
      ...caparra,
    });
  };
  return (
    <Card>
      <CardHeader>
        <CardTitle>Dati Pagamento Caparra</CardTitle>
        <CardDescription>
          dati per il pagamento della caparra, da mostrare all&apos;utente
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex items-center gap-3">
          <Button
            aria-label="Import Caparra"
            onClick={async () => {
              const clipboardText = await navigator.clipboard.readText();

              setCaparra(parseCaparra(clipboardText));
            }}
            className="flex items-center gap-2"
            variant="info"
          >
            <ClipboardPaste className="size-4" />
            Clicca qui per importare la stringa dal gestionale
          </Button>
          <Button
            aria-label="Reset Caparra"
            onClick={async () => {
              setCaparra({
                caparra_causale: null,
                caparra_iban: null,
                caparra_importo: null,
                caparra_intestazione: null,
              });
            }}
            className="flex items-center gap-2"
            variant="destructive"
          >
            <Trash2 className="size-4" />
            Reset
          </Button>
        </div>
        {caparra ? (
          <div className="flex flex-col gap-2">
            <p>
              <span className="font-semibold">Intestazione: </span>
              {caparra.caparra_intestazione}{" "}
              <Button
                aria-label="Edit Intestazione"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica l'intestazione della caparra:",
                    caparra.caparra_intestazione || "",
                  );
                  if (newValue !== null) {
                    setCaparra((prev) =>
                      prev
                        ? { ...prev, caparra_intestazione: newValue }
                        : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">IBAN: </span>
              {caparra.caparra_iban}{" "}
              <Button
                aria-label="Edit IBAN"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica l'IBAN della caparra:",
                    caparra.caparra_iban || "",
                  );
                  if (newValue !== null) {
                    setCaparra((prev) =>
                      prev ? { ...prev, caparra_iban: newValue } : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">Importo: </span>
              {caparra.caparra_importo}{" "}
              <Button
                aria-label="Edit Importo"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica l'importo della caparra:",
                    caparra.caparra_importo || "",
                  );
                  if (newValue !== null) {
                    setCaparra((prev) =>
                      prev ? { ...prev, caparra_importo: newValue } : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
            <p>
              <span className="font-semibold">Causale: </span>
              {caparra.caparra_causale}{" "}
              <Button
                aria-label="Edit Causale"
                onClick={() => {
                  const newValue = prompt(
                    "Modifica la causale della caparra:",
                    caparra.caparra_causale || "",
                  );
                  if (newValue !== null) {
                    setCaparra((prev) =>
                      prev ? { ...prev, caparra_causale: newValue } : undefined,
                    );
                  }
                }}
                className="h-6 px-1.5 [&_svg]:size-4"
                size="sm"
              >
                <Pen />
              </Button>
            </p>
          </div>
        ) : (
          <p>Inserisci la stringa dal gestionale e elabora</p>
        )}
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Caparra"
          onClick={() => {
            handleSave();
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

const SendConferma = ({
  handleUpdate,
}: {
  handleUpdate: (upd: ServizioAnnunciUpdate) => void;
}) => {
  const { data } = useServizioAnnuncio();
  const [check, setCheck] = useState(data.hasConfermaAdmin);

  return (
    <Card>
      <CardHeader>
        <CardTitle>Lavorazione Conferma</CardTitle>
        <CardDescription>
          Se accettare la conferma, controlla i parametri di ricerca prima!
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="flex items-center gap-3">
          <Switch
            aria-label="Conferma Lavorata"
            id="conferma"
            checked={check}
            onCheckedChange={(c) => {
              setCheck(c);
            }}
          />
          <Label htmlFor="conferma">Conferma lavorata</Label>
        </div>
      </CardContent>
      <CardFooter>
        <Button
          aria-label="Save Conferma Status"
          onClick={() => {
            handleUpdate({
              hasConfermaAdmin: check,
            });
          }}
          variant="success"
        >
          Salva
        </Button>
      </CardFooter>
    </Card>
  );
};

export const AddButton = ({ annuncioId }: { annuncioId: AnnunciId }) => {
  const { servizioId, userId } = useServizio();
  const utils = api.useUtils();
  const { mutate } = api.servizio.addServizioAnnunci.useMutation({
    onSuccess: async () => {
      await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
      await utils.servizio.getAnnunciAvailableToAdd.invalidate({
        servizioId,
      });
      await utils.servizio.AnnuncioServizioTipologiaMatch.invalidate({
        userId,
      });
      await utils.servizio.getCompatibileAnnunci.invalidate({
        servizioId,
      });

      toast.success("Annuncio aggiunto alla ricerca");
    },
    onError: (error) => {
      console.error(error);
      toast.error("Errore durante l'aggiunta dell'annuncio");
    },
  });

  const buttonRef = useRef<AnimatedButtonRef>(null);
  return (
    <AnimatedButton
      ref={buttonRef}
      sparklesIcon="thumbs-up"
      sparklesNumber={15}
      sparklesRadius={60}
      sparklesClassName="fill-yellow-500 stroke-transparent"
      sparklesScale={[1, 1.5]}
      onClick={async () => {
        buttonRef.current?.sparkle();
        //wait for the animation to finish
        await new Promise((resolve) => setTimeout(resolve, 1000));
        mutate({ servizioId, annunci: [annuncioId] });
      }}
      variant="info"
      className="group flex w-full gap-2"
    >
      <Plus className="size-5" />
      <span>Aggiungi agli annunci da contattare</span>
    </AnimatedButton>
  );
};
