'use client'

import { useState, useEffect, useCallback, useRef } from 'react'
import { cn } from '@/lib/utils'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { generateQrCodeDataUrl } from '@/lib/qrcode'
import { X, Copy, Download, Check, Link, QrCode } from 'lucide-react'
import type { InvitationListItem } from '@/lib/invite/types'
import {
  INVITATION_STATUS_LABELS,
  INVITATION_STATUS_COLORS,
} from '@/lib/invite/types'
import { formatRelativeTime } from '@/lib/format'

// ── Props ────────────────────────────────────────────────────────

interface InviteDialogProps {
  onClose: () => void
  onCreateInvite: () => Promise<{ link: string; token: string }>
  pendingInvites: InvitationListItem[]
  onCancelInvite: (inviteToken: string, dbId?: string) => void
}

// ── Component ────────────────────────────────────────────────────

export function InviteDialog({
  onClose,
  onCreateInvite,
  pendingInvites,
  onCancelInvite,
}: InviteDialogProps) {
  const [inviteLink, setInviteLink] = useState('')
  const [qrCodeUrl, setQrCodeUrl] = useState('')
  const [qrLoading, setQrLoading] = useState(false)
  const [copied, setCopied] = useState(false)
  const overlayRef = useRef<HTMLDivElement>(null)

  // Create invitation on mount
  useEffect(() => {
    let cancelled = false

    async function init() {
      setQrLoading(true)
      try {
        const { link } = await onCreateInvite()
        if (cancelled) return
        setInviteLink(link)

        // Generate QR code data URL
        const dataUrl = await generateQrCodeDataUrl(link, { cellSize: 6, margin: 2 })
        if (cancelled) return
        setQrCodeUrl(dataUrl)
      } catch (err) {
        if (!cancelled) {
          console.error('[InviteDialog] create failed:', err)
          setInviteLink('')  // stays as '生成中...'
        }
      } finally {
        if (!cancelled) setQrLoading(false)
      }
    }

    init()
    return () => { cancelled = true }
  }, [onCreateInvite])

  // Close on Escape
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [onClose])

  // Copy link
  const handleCopy = useCallback(async () => {
    if (!inviteLink) return
    try {
      await navigator.clipboard.writeText(inviteLink)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch {
      // Fallback
      const textarea = document.createElement('textarea')
      textarea.value = inviteLink
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }, [inviteLink])

  // Download QR code as PNG
  const handleDownload = useCallback(() => {
    if (!qrCodeUrl) return
    const a = document.createElement('a')
    a.href = qrCodeUrl
    a.download = 'invite-qr.png'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }, [qrCodeUrl])

  // Retry on failure
  const handleRetry = useCallback(async () => {
    setQrLoading(true)
    setInviteLink('')
    setQrCodeUrl('')
    try {
      const { link } = await onCreateInvite()
      setInviteLink(link)
      const dataUrl = await generateQrCodeDataUrl(link, { cellSize: 6, margin: 2 })
      setQrCodeUrl(dataUrl)
    } catch (err) {
      console.error('[InviteDialog] retry failed:', err)
    } finally {
      setQrLoading(false)
    }
  }, [onCreateInvite])

  // Close on backdrop click
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === overlayRef.current) onClose()
  }

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 animate-fade-in"
      onClick={handleBackdropClick}
    >
      <div className="bg-surface-1 border border-hairline rounded-xl shadow-forge-lg w-[520px] max-h-[90vh] overflow-y-auto animate-scale-in">
        {/* Header */}
        <div className="flex items-center justify-between px-5 pt-5 pb-3">
          <div>
            <h2 className="text-[18px] font-semibold text-ink font-heading">邀请成员</h2>
            <p className="text-[13px] text-ink-muted mt-0.5">
              将下方二维码或链接发送给对方，对方扫码后完成微信 Bot 连接即可使用
            </p>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-surface-2 text-ink-tertiary hover:text-ink transition-colors shrink-0"
          >
            <X size={16} />
          </button>
        </div>

        {/* QR Code */}
        <div className="flex justify-center py-4">
          {qrLoading ? (
            <div className="w-[180px] h-[180px] bg-surface-2 animate-pulse rounded-xl flex items-center justify-center">
              <QrCode size={32} className="text-ink-tertiary" />
            </div>
          ) : qrCodeUrl ? (
            <img
              src={qrCodeUrl}
              alt="邀请二维码"
              className="w-[180px] h-[180px] rounded-xl border border-hairline"
            />
          ) : (
            <div className="flex flex-col items-center gap-3">
              <div className="w-[180px] h-[180px] bg-surface-2 rounded-xl flex items-center justify-center">
                <span className="text-[13px] text-ink-tertiary">生成失败</span>
              </div>
              <button
                onClick={handleRetry}
                className="h-8 px-3 rounded-lg bg-indigo text-white text-[12px] font-medium hover:bg-indigo/90 transition-colors"
              >
                重新生成
              </button>
            </div>
          )}
        </div>

        {/* Link + Actions */}
        <div className="px-5 pb-4">
          <div className="flex gap-2">
            <div className="flex-1 flex items-center gap-2 px-3 py-2 rounded-lg bg-surface-2 border border-hairline text-[12px] text-ink-muted truncate">
              <Link size={14} className="shrink-0" />
              <span className="truncate">{inviteLink || '生成中...'}</span>
            </div>
            <Button
              size="sm"
              variant="secondary"
              onClick={handleCopy}
              disabled={!inviteLink}
              className="shrink-0"
            >
              {copied ? (
                <><Check size={14} className="mr-1 text-green" />已复制</>
              ) : (
                <><Copy size={14} className="mr-1" />复制</>
              )}
            </Button>
            <Button
              size="sm"
              variant="secondary"
              onClick={handleDownload}
              disabled={!qrCodeUrl}
              className="shrink-0"
            >
              <Download size={14} className="mr-1" />
              下载
            </Button>
          </div>
        </div>

        {/* Pending Invitations List */}
        {pendingInvites.length > 0 && (
          <div className="border-t border-hairline px-5 py-4">
            <h3 className="text-[13px] font-medium text-ink mb-3">
              已发出的邀请
              <span className="ml-1.5 text-[12px] text-ink-tertiary font-normal">
                ({pendingInvites.length})
              </span>
            </h3>
            <div className="space-y-1 max-h-[200px] overflow-y-auto">
              {pendingInvites.map((inv) => (
                <div
                  key={inv.id}
                  className="flex items-center justify-between p-2.5 rounded-lg hover:bg-surface-2 transition-colors"
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="text-[13px] text-ink truncate">
                      {inv.inviteePhone || inv.inviteeName || '未填写'}
                    </span>
                    <span className={cn(
                      'text-[11px] px-1.5 py-0.5 rounded-full bg-surface-2',
                      INVITATION_STATUS_COLORS[inv.status] ?? 'text-ink-tertiary'
                    )}>
                      {INVITATION_STATUS_LABELS[inv.status] ?? inv.status}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <span className="text-[11px] text-ink-tertiary">
                      {formatRelativeTime(inv.updatedAt)}
                    </span>
                    <button
                      onClick={() => onCancelInvite(inv.inviteToken, inv.id)}
                      className="w-5 h-5 flex items-center justify-center rounded hover:bg-surface-3 text-ink-tertiary hover:text-coral transition-colors"
                      title="取消邀请"
                    >
                      <X size={12} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
