"use client";

import { useCallback } from "react";
import { QRCodeSVG } from "qrcode.react";
import { X, Copy, Share2, QrCode } from "lucide-react";
import type { SceneType } from "@/types";
import { getSceneConfig } from "@/lib/sceneConfig";
import Modal from "@/components/Modal";
import Button from "@/components/Button";
import { useShare } from "@/hooks/useShare";

interface QrInviteModalProps {
  open: boolean;
  onClose: () => void;
  roomId: string;
  scene?: SceneType;
}

export default function QrInviteModal({
  open,
  onClose,
  roomId,
  scene = "eat",
}: QrInviteModalProps) {
  const { share, copyToClipboard } = useShare();
  const sceneConfig = getSceneConfig(scene);
  const inviteUrl =
    typeof window !== "undefined"
      ? `${window.location.origin}/invite/${roomId}`
      : "";

  const handleCopy = useCallback(
    () => copyToClipboard(inviteUrl, "邀请链接已复制，快去发给朋友吧！"),
    [inviteUrl, copyToClipboard],
  );

  const handleShare = useCallback(
    () => share({ title: sceneConfig.shareTitle, text: sceneConfig.shareText, url: inviteUrl }, handleCopy),
    [inviteUrl, sceneConfig, share, handleCopy],
  );

  return (
    <Modal open={open} onClose={onClose}>
      <button
        onClick={onClose}
        aria-label="关闭"
        className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle"
      >
        <X size={16} />
      </button>

      <div className="flex flex-col items-center">
        <div className="flex items-center gap-2 text-heading">
          <QrCode size={18} className="text-accent" />
          <h2 className="text-lg font-bold">邀请饭搭子</h2>
        </div>
        <p className="mt-1 text-xs text-muted">
          {sceneConfig.qrSubtitle}
        </p>

        <div className="mt-5 rounded-2xl border-2 border-dashed border-subtle bg-elevated/50 p-4">
          <QRCodeSVG
            value={inviteUrl}
            size={180}
            level="M"
            bgColor="transparent"
            fgColor="#e5e7eb"
          />
        </div>

        <div className="mt-4 flex items-center gap-2">
          <span className="text-xs text-muted">房间号</span>
          <span className="rounded-full bg-elevated px-3 py-1 font-mono text-base font-bold tracking-[0.2em] text-accent ring-1 ring-border">
            {roomId}
          </span>
        </div>

        <div className="mt-5 flex w-full gap-2.5">
          <Button
            onClick={handleCopy}
            variant="secondary"
            size="lg"
            icon={<Copy size={15} />}
            className="flex-1"
          >
            复制链接
          </Button>
          <Button
            onClick={handleShare}
            size="lg"
            icon={<Share2 size={15} />}
            className="flex-1"
          >
            发送邀请
          </Button>
        </div>
      </div>
    </Modal>
  );
}
