"use client";

import { Menu, MenuItem } from "components/Layout";
import { useReplicache, type PermissionToken } from "src/replicache";
import { hideDoc } from "../storage";
import { useState } from "react";
import { ButtonPrimary } from "components/Buttons";
import { useTemplateState } from "../Actions/CreateNewButton";
import { useSmoker, useToaster } from "components/Toast";
import { removeLeafletFromHome } from "actions/removeLeafletFromHome";
import { useIdentityData } from "components/IdentityProvider";
import { HideSmall } from "components/Icons/HideSmall";
import { MoreOptionsTiny } from "components/Icons/MoreOptionsTiny";
import { TemplateRemoveSmall } from "components/Icons/TemplateRemoveSmall";
import { TemplateSmall } from "components/Icons/TemplateSmall";
import { MoreOptionsVerticalTiny } from "components/Icons/MoreOptionsVerticalTiny";
import { addLeafletToHome } from "actions/addLeafletToHome";

export const LeafletOptions = (props: {
  leaflet: PermissionToken;
  isTemplate: boolean;
  loggedIn: boolean;
  added_at: string;
}) => {
  let { mutate: mutateIdentity } = useIdentityData();
  let [state, setState] = useState<"normal" | "template">("normal");
  let [open, setOpen] = useState(false);
  let smoker = useSmoker();
  let toaster = useToaster();
  return (
    <>
      <Menu
        open={open}
        align="end"
        onOpenChange={(o) => {
          setOpen(o);
          setState("normal");
        }}
        trigger={
          <div
            className="text-secondary shrink-0"
            onClick={(e) => {
              e.preventDefault;
              e.stopPropagation;
            }}
          >
            <MoreOptionsVerticalTiny />
          </div>
        }
      >
        {state === "normal" ? (
          <>
            {!props.isTemplate ? (
              <MenuItem
                onSelect={(e) => {
                  e.preventDefault();
                  setState("template");
                }}
              >
                <TemplateSmall /> Add as Template
              </MenuItem>
            ) : (
              <MenuItem
                onSelect={(e) => {
                  useTemplateState.getState().removeTemplate(props.leaflet);
                  let newLeafletButton =
                    document.getElementById("new-leaflet-button");
                  if (!newLeafletButton) return;
                  let rect = newLeafletButton.getBoundingClientRect();
                  smoker({
                    static: true,
                    text: <strong>Removed template!</strong>,
                    position: {
                      y: rect.top,
                      x: rect.right + 5,
                    },
                  });
                }}
              >
                <TemplateRemoveSmall /> Remove from Templates
              </MenuItem>
            )}
            <MenuItem
              onSelect={async () => {
                if (props.loggedIn) {
                  mutateIdentity(
                    (s) => {
                      if (!s) return s;
                      return {
                        ...s,
                        permission_token_on_homepage:
                          s.permission_token_on_homepage.filter(
                            (ptrh) =>
                              ptrh.permission_tokens.id !== props.leaflet.id,
                          ),
                      };
                    },
                    { revalidate: false },
                  );
                  await removeLeafletFromHome([props.leaflet.id]);
                  mutateIdentity();
                } else {
                  hideDoc(props.leaflet);
                }
                toaster({
                  content: (
                    <div className="font-bold">
                      Doc removed!{" "}
                      <UndoRemoveFromHomeButton
                        leaflet={props.leaflet}
                        added_at={props.added_at}
                      />
                    </div>
                  ),
                  type: "success",
                });
              }}
            >
              <HideSmall />
              Remove from Home
            </MenuItem>
          </>
        ) : state === "template" ? (
          <AddTemplateForm
            leaflet={props.leaflet}
            close={() => setOpen(false)}
          />
        ) : null}
      </Menu>
    </>
  );
};

const UndoRemoveFromHomeButton = (props: {
  leaflet: PermissionToken;
  added_at: string | undefined;
}) => {
  let toaster = useToaster();
  let { mutate } = useIdentityData();
  return (
    <button
      onClick={async (e) => {
        await mutate(
          (identity) => {
            if (!identity) return;
            return {
              ...identity,
              permission_token_on_homepage: [
                ...identity.permission_token_on_homepage,
                {
                  created_at: props.added_at || new Date().toISOString(),
                  permission_tokens: {
                    ...props.leaflet,
                    leaflets_in_publications: [],
                  },
                },
              ],
            };
          },
          { revalidate: false },
        );
        await addLeafletToHome(props.leaflet.id);
        await mutate();

        toaster({
          content: <div className="font-bold">Recovered Doc!</div>,
          type: "success",
        });
      }}
      className="underline"
    >
      Undo?
    </button>
  );
};

const AddTemplateForm = (props: {
  leaflet: PermissionToken;
  close: () => void;
}) => {
  let [name, setName] = useState("");
  let smoker = useSmoker();
  return (
    <div className="flex flex-col gap-2 px-3 py-1">
      <label className="font-bold flex flex-col gap-1 text-secondary">
        Template Name
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          type="text"
          className=" text-primary font-normal border border-border rounded-md outline-hidden px-2 py-1 w-64"
        />
      </label>

      <ButtonPrimary
        onClick={() => {
          useTemplateState.getState().addTemplate({
            name,
            id: props.leaflet.id,
          });
          let newLeafletButton = document.getElementById("new-leaflet-button");
          if (!newLeafletButton) return;
          let rect = newLeafletButton.getBoundingClientRect();
          smoker({
            static: true,
            text: <strong>Added {name}!</strong>,
            position: {
              y: rect.top,
              x: rect.right + 5,
            },
          });
          props.close();
        }}
        className="place-self-end"
      >
        Add Template
      </ButtonPrimary>
    </div>
  );
};
