"use client";

import { useMemo, useState } from "react";
import Image from "next/image";
import Modal from "@/components/elements/Modal";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import RoundedButton from "@/components/elements/RoundedButton";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { copyTextToClipboard } from "@/lib/chat/getCopyableMessageText";

type ShareProductModalProps = {
  open: boolean;
  onClose: () => void;
  listingId: string;
  title?: string | null;
  image?: string | null;
};

export default function ShareProductModal({
  open,
  onClose,
  listingId,
  title,
  image,
}: ShareProductModalProps) {
  const { t } = useTranslation("common");
  const [copied, setCopied] = useState(false);

  const productUrl = useMemo(() => {
    if (!listingId) return "";
    if (typeof window !== "undefined") {
      return `${window.location.origin}/shops/listing/${listingId}`;
    }
    return `https://modstagram.com/shops/listing/${listingId}`;
  }, [listingId]);

  const qrSrc = useMemo(() => {
    if (!productUrl) return "";
    return `https://api.qrserver.com/v1/create-qr-code/?size=220x220&margin=12&data=${encodeURIComponent(productUrl)}`;
  }, [productUrl]);

  const handleCopy = async () => {
    if (!productUrl) return;
    const ok = await copyTextToClipboard(productUrl);
    if (ok) {
      setCopied(true);
      toast.success(t("shops.share.copied"));
      window.setTimeout(() => setCopied(false), 2000);
    } else {
      toast.error(t("shops.share.copyFailed"));
    }
  };

  return (
    <Modal
      isOpen={open}
      onClose={onClose}
      elevated
      height="fit"
      panelClassName="!p-0 max-h-[90dvh] w-full max-w-sm overflow-y-auto"
    >
      <div className="px-5 py-6 text-center">
        <h2 className="mb-5 text-base font-bold">{t("shops.share.title")}</h2>

        <div className="mb-4 flex flex-col items-center gap-2">
          <ProfileAvatar
            src={image || undefined}
            alt={title || "product"}
            size="md"
            rounded="2xl"
          />
          {title ? <p className="text-sm font-semibold">{title}</p> : null}
        </div>

        {qrSrc ? (
          <div className="mx-auto mb-5 flex h-[220px] w-[220px] items-center justify-center rounded-2xl bg-white p-3">
            <Image
              src={qrSrc}
              alt={t("shops.share.qrAlt")}
              width={196}
              height={196}
              unoptimized
              className="h-full w-full object-contain"
            />
          </div>
        ) : null}

        <p className="mb-2 text-xs text-neutral-500 dark:text-neutral-400">
          {t("shops.share.linkLabel")}
        </p>
        <div className="mb-4 break-all rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-xs dark:border-neutral-700 dark:bg-neutral-900">
          {productUrl || "—"}
        </div>

        <div className="mx-auto grid w-full max-w-sm grid-cols-2 gap-4">
          <RoundedButton
            type="button"
            onClick={onClose}
            className="!border-transparent h-9 w-full !bg-neutral-100 text-neutral-600 dark:!bg-neutral-800 dark:text-neutral-300"
          >
            {t("shops.share.close")}
          </RoundedButton>
          <RoundedButton
            type="button"
            onClick={() => void handleCopy()}
            className="!border-transparent h-9 w-full !bg-sky-100 text-sky-600"
          >
            {copied ? t("shops.share.copied") : t("shops.share.copyLink")}
          </RoundedButton>
        </div>
      </div>
    </Modal>
  );
}
