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 { FormFlags, type initialValues } from "~/forms/FormFlags";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog";
import { Plus, RefreshCcw } from "lucide-react";
import { FlagsTable } from "~/components/tables/flags-table";
import { Status500 } from "~/components/status-page";
import { Button } from "~/components/ui/button";

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

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

  const handleEdit = (data: initialValues | 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-accent-foreground text-xl font-bold sm:text-2xl">
              Impostazioni
            </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>

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

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

const EditModal = ({
  initial,
  open,
  setOpen,
}: {
  initial: initialValues | null;
  open: boolean;
  setOpen: (status: boolean) => void;
}) => {
  const utils = api.useUtils();
  const { mutate: edit } = api.settings.EditFlag.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.GetFlags.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  const { mutate: add } = api.settings.AddFlag.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.GetFlags.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  const { mutate: remove } = api.settings.RemoveFlag.useMutation({
    onSuccess: async () => {
      toast.success("Successo");
      await utils.settings.GetFlags.invalidate();
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{initial ? "Modifica" : "Aggiungi"}</DialogTitle>
          <DialogDescription>
            {initial ? "Modifica i valori" : "Aggiungi un nuovo valore"}
          </DialogDescription>
        </DialogHeader>
        <div className="py-4">
          <FormFlags
            handleRemove={(id) =>
              remove({
                id,
              })
            }
            submitMutation={(fields) => {
              if (initial) {
                edit({
                  id: initial.id,
                  value: fields.value,
                });
              } else {
                add({
                  id: fields.id,
                  value: fields.value,
                });
              }
            }}
            initialValues={initial}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};
