"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 ResponseScheduleItem = {
  day: string;
  start_time?: string | null;
  end_time?: string | null;
};

type ShareShopModalProps = {
  open: boolean;
  onClose: () => void;
  shopId: string;
  shopName?: string | null;
  shopLogo?: string | null;
  responseSchedule?: ResponseScheduleItem[];
};

export default function ShareShopModal({
  open,
  onClose,
  shopId,
  shopName,
  shopLogo,
  responseSchedule,
}: ShareShopModalProps) {
  const { t } = useTranslation("common");
  const [copied, setCopied] = useState(false);

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

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

  const handleCopy = async () => {
    if (!shopUrl) return;
    const ok = await copyTextToClipboard(shopUrl);
    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={shopLogo || undefined}
            alt={shopName || "shop"}
            size="md"
            rounded="2xl"
          />
          {shopName ? <p className="text-sm font-semibold">{shopName}</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">
          {shopUrl || "—"}
        </div>

        {responseSchedule && responseSchedule.length > 0 && (
          <div className="mb-5 flex w-full flex-col gap-2 text-right">
            <p className="text-sm font-semibold">{t("shops.responseScheduleTitle")}</p>
            <div className="flex flex-col gap-1.5 rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
              {responseSchedule.map((item) => (
                <div key={item.day} className="flex items-center justify-between text-xs">
                  <span className="text-neutral-500" dir="ltr">
                    {item.start_time || "--:--"} - {item.end_time || "--:--"}
                  </span>
                  <span className="font-medium">{t(`shops.days.${item.day}`)}</span>
                </div>
              ))}
            </div>
          </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>
  );
}
