import { useState } from "react";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Button } from "~/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import type { NextPageWithLayout } from "~/pages/_app";
import { RefreshCcw } from "lucide-react";
import { FormPrezzo } from "~/forms/FormPrezzo";
import toast from "react-hot-toast";
import { api } from "~/utils/api";
import { PrezzarioTable } from "~/components/tables/prezziario-tables";
import { Status500 } from "~/components/status-page";
import type {
  Prezziario,
  PrezziarioIdprezziario,
} from "~/schemas/public/Prezziario";

const Admin_Prezziario: NextPageWithLayout = () => {
  const { data, isLoading, refetch } = api.prezziario.getPrezziario.useQuery();
  const [openEdit, setOpenEdit] = useState(false);
  const [editData, setEditData] = useState<Prezziario | null>(null);

  const handleOpen = (status: boolean) => {
    setOpenEdit(status);
  };

  const handleEdit = (data: Prezziario | null) => {
    setEditData(data);
  };

  if (isLoading) return <LoadingPage />;
  if (!data) return <Status500 />;
  return (
    <div className="mx-1 flex-1 overflow-auto">
      <div className="mx-auto pt-4">
        <div className="mx-3 items-start justify-between md:flex">
          <div className="flex max-w-lg items-center gap-3">
            <h3 className="text-2xl font-bold">Prezziario</h3>
            <button onClick={async () => await refetch()}>
              <RefreshCcw className="size-6" />
            </button>
          </div>
          <div className="mt-3 md:mt-0">
            <NewPrezzoModal />

            <EditPrezzoModal
              initial={editData}
              open={openEdit}
              setOpen={handleOpen}
            />
          </div>
        </div>

        <PrezzarioTable
          data={data}
          setOpenEdit={handleOpen}
          setEditData={handleEdit}
        />
      </div>
    </div>
  );
};

export default Admin_Prezziario;

Admin_Prezziario.getLayout = function getLayout(page) {
  return <AreaRiservataLayout>{page}</AreaRiservataLayout>;
};

const NewPrezzoModal = () => {
  const utils = api.useUtils();
  const { mutate } = api.prezziario.addPrezziario.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.prezziario.getPrezziario.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  const [open, setOpen] = useState(false);
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline">Aggiungi Servizio</Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Aggiungi Servizio</DialogTitle>
          <DialogDescription className="sr-only">Edit</DialogDescription>
        </DialogHeader>
        <div className="py-4">
          <FormPrezzo
            submitMutation={(fields) => {
              mutate({
                data: {
                  ...fields,
                },
              });
            }}
            initialValues={{
              idprezziario: "" as PrezziarioIdprezziario,
              nome_it: "Nuovo servizio",
              nome_en: "New service",
              desc_it: "traduzioni da inserire",
              desc_en: "translations to be inserted",
              prezzo_cent: 0,
              testo_condizioni: "",
              isAcconto: false,
              isSaldo: false,
              isConsulenza: false,
              isActive: true,
              sconto: 0,
              isTransitorio: false,
              isStabile: false,
            }}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};
const EditPrezzoModal = ({
  initial,
  open,
  setOpen,
}: {
  initial: Prezziario | null;
  open: boolean;
  setOpen: (status: boolean) => void;
}) => {
  const utils = api.useUtils();
  const { mutate } = api.prezziario.updatePrezziario.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.prezziario.getPrezziario.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  if (!initial) return null;

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Modifica Servizio</DialogTitle>
          <DialogDescription className="sr-only">
            Modifica i dettagli del servizio
          </DialogDescription>
        </DialogHeader>
        <div className="max-h-[80vh] overflow-auto py-4">
          <FormPrezzo
            submitMutation={(fields) => {
              mutate({
                idprezziario: fields.idprezziario,
                data: {
                  ...fields,
                },
              });
            }}
            initialValues={{
              ...initial,
            }}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};
