import type { Options } from 'qr-code-styling'

import { FullscreenOutlined } from '@ant-design/icons'
import { useEffect, useRef, useState } from 'react'

const sharedOptions: Options = {
  cornersSquareOptions: { color: '#000000', type: 'square' },
  dotsOptions: { type: 'classy-rounded' },
  qrOptions: { errorCorrectionLevel: 'L' },
}

const smallQROptions: Options = {
  ...sharedOptions,
  height: 150,
  imageOptions: { hideBackgroundDots: true, imageSize: 0.5, margin: 0 },
  width: 150,
}

export const MalwareCheckQRCode = ({ url }: { url: string }) => {
  const smallQrRef = useRef<HTMLDivElement>(null)
  const modalRef = useRef<HTMLDivElement>(null)
  const [isModalOpen, setIsModalOpen] = useState(false)

  // Render small QR on initial load
  useEffect(() => {
    if (typeof window === 'undefined') return // Client-side only

    import('qr-code-styling').then(({ default: QRCodeStyling }) => {
      if (!smallQrRef.current) return console.warn('Missing QR container smallQrRef')
      const qrCode = new QRCodeStyling({ ...smallQROptions, data: url })
      if (smallQrRef.current.firstChild) smallQrRef.current.removeChild(smallQrRef.current.firstChild)
      qrCode.append(smallQrRef.current)
    })
  }, [url])

  // Render big QR when modal opened or window resized
  useEffect(() => {
    if (typeof window === 'undefined') return

    const renderQR = () => {
      import('qr-code-styling').then(({ default: QRCodeStyling }) => {
        if (!modalRef.current) return console.warn('Missing modal QR container smallQrRef')

        // Calculate responsive size: use 400px or 80vw, whichever is smaller
        const maxSize = Math.min(400, window.innerWidth * 0.8)

        const qrCode = new QRCodeStyling({
          ...sharedOptions,
          data: url,
          height: maxSize,
          margin: 10,
          width: maxSize,
        })
        if (modalRef.current.firstChild) modalRef.current.removeChild(modalRef.current.firstChild)
        qrCode.append(modalRef.current)
      })
    }

    renderQR()

    // Re-render on window resize
    window.addEventListener('resize', renderQR)
    return () => window.removeEventListener('resize', renderQR)
  }, [isModalOpen, url])

  const handleClose = () => setIsModalOpen(false)

  return (
    <>
      {/* Small QR Code */}
      <div
        className="flex flex-col items-center rounded-md border border-solid cursor-pointer group w-fit border-black/25 hover:border-black/40 hover:shadow-lg"
        onClick={() => setIsModalOpen(true)}
      >
        <h4 className="mt-4 mb-0 text-sm font-semibold">Scan to Begin</h4>

        <div className="p-2.5 w-[170px] h-[175px]" ref={smallQrRef} />

        <div className="flex mb-2 text-gray-500 transition-colors group-hover:text-gray-900">
          <FullscreenOutlined className="text-[14px] mr-1.5" />
          <span className="text-xs">Tap for fullscreen</span>
        </div>
      </div>

      {/* Modal */}
      <div
        className={`flex fixed inset-0 z-50 justify-center items-center bg-black bg-opacity-50 ${
          isModalOpen ? '':'hidden'}`}
        onClick={(e: React.MouseEvent) => {
          if (e.target === e.currentTarget) handleClose()
        }}
      >
        <div className="relative p-4 sm:p-8 mx-4 max-w-[90vw] bg-white rounded-lg">
          {/* Close button */}
          <button
            aria-label="Close modal"
            className="flex absolute top-2 right-2 justify-center items-center w-10 h-10 text-gray-500 bg-transparent rounded-full border-none cursor-pointer hover:text-gray-700 hover:bg-gray-900/10"
            onClick={handleClose}
          >
            <span className="relative bottom-px text-2xl font-bold">×</span>
          </button>

          <h3 className="mb-3 text-2xl text-center">Scan to Begin</h3>

          {/* Warning */}
          <p className="mt-4 text-sm text-center text-black/60">⚠️ Contains your private vote selections</p>

          {/* Big QR code */}
          <div className="flex justify-center" ref={modalRef} />

          {/* Text link */}
          <p className="mt-4 text-sm text-left break-all">
            Or open this link on your 2nd device:
            <a className="block text-blue-600 hover:underline" href={url} rel="noreferrer" target="_blank">
              {url}
            </a>
          </p>
        </div>
      </div>
    </>
  )
}
