import { toast } from "@/components/Toast";
import TrashWithConfrim from "@/components/TrashWithConfrim";
import { Paths } from "@/config/Paths";
import { extractErrorMessage } from "@/helpers/utils";
import { useGetBusiness } from "@/pages/business/hooks/useBusinessData";
import { useDleteCatalog } from "@/pages/catalogue/hooks/useCatalogueData";
import { requestViewerFullscreen } from "@/pages/viewer/utils/viewerFullscreen";
import { Edit, Eye, Share } from "iconsax-react";
import moment from "moment-jalaali";
import { type FC } from "react";
import { Link } from "react-router-dom";
import type { CatalogItemType } from "../types/Types";
import CatalogPreview from "./CatalogPreview";

type Props = {
  item: CatalogItemType;
  refetch: () => void;
  slug?: string;
  readOnly?: boolean;
};

const CatalogueItem: FC<Props> = ({ item, refetch, slug, readOnly }) => {
  const { data: business } = useGetBusiness();
  const deleteCatalog = useDleteCatalog();

  const shareUrl = `${window.location.origin}${Paths.viewerBySlug}/${business?.data?.slug}/${item.slug}`;

  const handleShare = async () => {
    try {
      if (typeof navigator.share === "function") {
        await navigator.share({
          title: item.name,
          text: item.name,
          url: shareUrl,
        });
        return;
      }
      await navigator.clipboard.writeText(shareUrl);
      toast("لینک در کلیپ‌بورد کپی شد", "success");
    } catch (err) {
      const isAbort = err instanceof DOMException ? err.name === "AbortError" : err instanceof Error && err.name === "AbortError";
      if (isAbort) return;
      toast(extractErrorMessage(err, "امکان اشتراک‌گذاری وجود ندارد"), "error");
    }
  };

  const handleDelete = () => {
    deleteCatalog.mutate(item.id, {
      onSuccess: () => {
        toast("با موفقیت حذف شد", "success");
        refetch();
      },
      onError: (error) => {
        toast(extractErrorMessage(error, "error"));
      },
    });
  };

  return (
    <div className="bg-white p-6 rounded-3xl w-full">
      <div className="flex gap-4 items-center">
        <CatalogPreview item={item} />
        <div>
          <h6>{item.name}</h6>
          <div className="mt-2 text-[#999999] text-xs">{moment(item.createdAt).format("jYYYY/jMM/jDD")}</div>
        </div>
      </div>
      <div className="flex justify-end gap-1 items-center mt-1">
        <Link to={Paths.viewerBySlug + `/${slug ?? business?.data?.slug}/${item.slug}`} onClick={requestViewerFullscreen}>
          <div className="size-6 bg-[#EAECF4] rounded-md flex justify-center items-center">
            <Eye size={18} color="#0047FF" />
          </div>
        </Link>
        {!readOnly && (
          <Link to={Paths.editor + `/${item.id}`}>
            <div className="size-6 bg-[#EAECF4] rounded-md flex justify-center items-center">
              <Edit size={18} color="#0047FF" />
            </div>
          </Link>
        )}
        <button type="button" onClick={handleShare} className="size-6 bg-[#EAECF4] rounded-md flex justify-center items-center border-0 p-0 cursor-pointer shrink-0" aria-label="اشتراک‌گذاری">
          <Share size={18} color="#000" />
        </button>
        {!readOnly && (
          <div className="size-6 bg-[#EAECF4] rounded-md flex justify-center items-center">
            <TrashWithConfrim onDelete={handleDelete} colorIcon="red" isloading={deleteCatalog.isPending} />
          </div>
        )}
      </div>
    </div>
  );
};

export default CatalogueItem;
