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

const AdminBanners: NextPageWithLayout = () => {
  const { data, isLoading, refetch } = api.settings.getBannerAllData.useQuery();
  const [openEdit, setOpenEdit] = useState(false);
  const [editData, setEditData] = useState<Banners | null>(null);

  const handleOpen = (status: boolean) => {
    setOpenEdit(status);
  };
  const handleEdit = (data: Banners | 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-auto items-start justify-between px-2 md:flex">
          <div className="flex items-center gap-3">
            <h3 className="text-accent-foreground text-xl font-bold sm:text-2xl">
              Banners
            </h3>
            <button onClick={async () => await refetch()}>
              <RefreshCcw className="size-6" />
            </button>
          </div>

          <div className="mt-3 md:mt-0">
            <EditModal
              initial={editData}
              open={openEdit}
              setOpen={handleOpen}
            />
          </div>
          <div className="mt-3 md:mt-0">
            <Button
              onClick={() => {
                handleEdit(null);
                handleOpen(true);
              }}
              variant="outline"
              className="flex items-center gap-2 font-semibold"
            >
              <Plus className="size-6" />
              Nuovo
            </Button>
          </div>
        </div>

        <BannersTable
          data={data}
          setOpenEdit={handleOpen}
          setEditData={handleEdit}
        />
      </div>
    </div>
  );
};
export default AdminBanners;

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

const EditModal = ({
  initial,
  open,
  setOpen,
}: {
  initial: Banners | null;
  open: boolean;
  setOpen: (status: boolean) => void;
}) => {
  const utils = api.useUtils();
  const { mutate: edit } = api.settings.updateBanner.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.getBannerAllData.invalidate();
      await utils.settings.getBannerData.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  const { mutate: add } = api.settings.addBanner.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.getBannerAllData.invalidate();
      await utils.settings.getBannerData.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  const { mutate: del } = api.settings.deleteBanner.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.getBannerAllData.invalidate();
      await utils.settings.getBannerData.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild />
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>
            {!initial ? "Aggiungi Banner" : "Modifica Valori"}
          </DialogTitle>
          <DialogDescription className="sr-only">Edit</DialogDescription>
        </DialogHeader>
        {!initial ? (
          <div className="py-4">
            <FormBanners
              submitMutation={(fields) => {
                add({
                  ...fields,
                });
              }}
              initialValues={null}
            />
          </div>
        ) : (
          <div className="py-4">
            <FormBanners
              submitMutation={(fields) => {
                edit({
                  ...fields,
                });
              }}
              initialValues={{
                ...initial,
              }}
              del={(v) => del({ idbanner: v })}
            />
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};
