"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 ShareProfileModalProps = {
  open: boolean;
  onClose: () => void;
  userName?: string | null;
  displayName?: string | null;
  profileImage?: string | null;
};

export default function ShareProfileModal({
  open,
  onClose,
  userName,
  displayName,
  profileImage,
}: ShareProfileModalProps) {
  const { t } = useTranslation("common");
  const [copied, setCopied] = useState(false);

  const profileUrl = useMemo(() => {
    const handle = String(userName || "").trim();
    if (!handle) return "";
    if (typeof window !== "undefined") {
      return `${window.location.origin}/users/${encodeURIComponent(handle)}`;
    }
    return `https://modstagram.com/users/${encodeURIComponent(handle)}`;
  }, [userName]);

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

  const handleCopy = async () => {
    if (!profileUrl) return;
    const ok = await copyTextToClipboard(profileUrl);
    if (ok) {
      setCopied(true);
      toast.success(t("models.shareProfile.copied"));
      window.setTimeout(() => setCopied(false), 2000);
    } else {
      toast.error(t("models.shareProfile.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("models.shareProfile.title")}
        </h2>

        <div className="mb-4 flex flex-col items-center gap-2">
          <ProfileAvatar
            src={profileImage || undefined}
            alt={userName || "profile"}
            size="md"
            rounded="2xl"
          />
          {displayName ? (
            <p className="text-sm font-semibold">{displayName}</p>
          ) : null}
          {userName ? (
            <p className="text-xs text-neutral-500 dark:text-neutral-400">
              @{userName}
            </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("models.shareProfile.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("models.shareProfile.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">
          {profileUrl || "—"}
        </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("models.shareProfile.close")}
          </RoundedButton>
          <RoundedButton
            type="button"
            onClick={() => void handleCopy()}
            className="!border-transparent h-9 w-full !bg-sky-100 text-sky-600"
          >
            {copied
              ? t("models.shareProfile.copied")
              : t("models.shareProfile.copyLink")}
          </RoundedButton>
        </div>
      </div>
    </Modal>
  );
}
