import { useConfirm } from "@/components/confirm/hooks/useConfirm";
import { LoadingText } from "@/components/loading";
import Tooltip from "@/components/Tooltip";
import { Button } from "@/components/ui/button";
import { ServerRequest } from "@/lib/actions";
import { removeDownloadLinks } from "@/services/download/removelink";
import { socket } from "@/socket";
import { faTrashAlt } from "@fortawesome/free-regular-svg-icons";
import dayjs from "dayjs";
import { useEffect, useRef, useState, useTransition } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";

type Props = {
  row: DownloadLink;
};
const User = ({ row }: Props) => {
  const { user, email } = row;

  return (
    <Tooltip content={user ?? email}>
      <p className="max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap">
        {user ?? email}
      </p>
    </Tooltip>
  );
};

const Title = ({ row }: Props) => {
  const { title, href } = row;

  const handleCopyLinkToClipboard = () => {
    navigator.clipboard.writeText(href);
    toast.success("Link copied to clipboard!", {
      duration: 1000,
    });
  };

  return (
    <Tooltip content="Copy Link!">
      <p
        className="w-fit cursor-pointer text-blue-500 hover:underline"
        onClick={handleCopyLinkToClipboard}
      >
        {title}
      </p>
    </Tooltip>
  );
};

const Date = ({ row }: Props) => {
  return (
    <p className="text-center">
      {dayjs(row.created_at).format("DD/MM/YYYY HH:mm")}
    </p>
  );
};

const Actions = ({ row, dict }: Props & { dict: Dictionary }) => {
  const { confirm } = useConfirm();

  const ref = useRef<HTMLDivElement>(null);

  const [_, startTransition] = useTransition();

  const [toggling, setToggling] = useState(false);
  const [parent, setParent] = useState<HTMLElement>();

  const handleRemoveDownloadLink = async () => {
    const isConfirmed = await confirm({
      title: dict.components.confirm_box.default_title,
      message: dict.components.confirm_box.default_text,
    });
    if (!isConfirmed) return;

    setToggling(true);
    startTransition(async () => {
      const promise = new Promise(async (resolve, reject) => {
        const formData = new FormData();

        formData.append("id", row.id);

        const result = await ServerRequest(removeDownloadLinks(formData));

        if (!result.operation) {
          setToggling(false);
          return reject(result);
        }

        socket.emit("remove-download-link", { id: row.id });
        return resolve(result);
      });

      toast.promise(promise, {
        loading: dict.alerts.remove_download_link.loading,
        description: dayjs().format("DD/MM/YYYY HH:mm"),
        success: ({ message }) => message,
        error: ({ message }) => message,
      });
    });
  };

  useEffect(() => {
    if (!ref.current) return;

    setParent(ref.current.parentElement.parentElement);

    if (!parent) return;

    if (toggling) {
      parent.classList.add("relative");
    } else {
      parent.classList.remove("relative");
    }
  }, [toggling, ref.current]);

  return (
    <div className="flex justify-center" ref={ref}>
      <Button
        variant="soft"
        color="danger"
        size="sm"
        decorator={faTrashAlt}
        isIcon
        rounded
        onClick={handleRemoveDownloadLink}
      />
      {toggling && (
        <>
          createPortal(
          <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-neutral-200/50">
            <LoadingText text="Deleting..." />
          </div>
          , parent, )
        </>
      )}
    </div>
  );
};

export { Actions, Date, Title, User };
