import React, { useEffect, useRef, useState } from 'react'
import QRCode from 'qrcode'

interface QRModalProps {
  title: string
  iconUrl?: string
  headerColor?: string
  qrText?: string
  imageUrl?: string
  primaryText?: string
  emphasizePrimary?: boolean
  ctaUrl?: string
  ctaText?: string
  onClose: () => void
}

const QRModal: React.FC<QRModalProps> = ({
  title,
  iconUrl,
  headerColor,
  qrText,
  imageUrl,
  primaryText,
  ctaUrl,
  ctaText,
  onClose,
  emphasizePrimary,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [isLoading, setIsLoading] = useState<boolean>(false)

  useEffect(() => {
    // Start loading when modal mounts with an image or QR text provided
    setIsLoading(Boolean(imageUrl || qrText))
  }, [imageUrl, qrText])

  useEffect(() => {
    let cancelled = false
    if (!qrText) return
    const draw = async () => {
      try {
        const canvas = canvasRef.current
        if (!canvas) return
        await QRCode.toCanvas(canvas, qrText, { width: 260, margin: 1 })
        if (!cancelled) setIsLoading(false)
      } catch (e) {
        console.error(e)
        if (!cancelled) setIsLoading(false)
      }
    }
    void draw()
    return () => { cancelled = true }
  }, [qrText])

  return (
    <div className="lfc-fixed lfc-inset-0 lfc-z-50 lfc-flex lfc-items-center lfc-justify-center lfc-bg-black/40">
      <div className="lfc-bg-white lfc-rounded-xl lfc-shadow-xl lfc-w-[460px] lfc-max-w-[92vw]">
        {/* Header */}
        <div
          className="lfc-flex lfc-items-center lfc-justify-between lfc-px-5 lfc-py-3 lfc-rounded-t-xl"
          style={{ backgroundColor: headerColor || '#7c3aed', color: 'white' }}
        >
          <div className="lfc-flex lfc-items-center lfc-gap-3">
            {iconUrl ? (
              <img src={iconUrl} alt={title} className="lfc-w-5 lfc-h-5" />
            ) : (
              <span className="lfc-w-5 lfc-h-5" />
            )}
            <span className="lfc-text-lg lfc-font-medium">{title}</span>
          </div>
          <button
            onClick={onClose}
            className="lfc-p-1 lfc-rounded hover:lfc-bg-white/10 lfc-text-white"
            aria-label="Close"
          >
            <svg className="lfc-w-6 lfc-h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className={`lfc-px-6 ${emphasizePrimary ? 'lfc-pt-8 lfc-pb-10' : 'lfc-pt-5 lfc-pb-6'} lfc-text-center`}>
          {imageUrl || qrText ? (
            <div className="lfc-flex lfc-justify-center">
              <div className="lfc-relative lfc-w-[260px] lfc-h-[260px]">
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt={title}
                    className="lfc-w-full lfc-h-full lfc-object-contain"
                    onLoad={() => setIsLoading(false)}
                    onError={() => setIsLoading(false)}
                  />
                ) : (
                  <canvas ref={canvasRef} className="lfc-w-full lfc-h-full" />
                )}
                {isLoading && (
                  <div className="lfc-absolute lfc-inset-0 lfc-flex lfc-items-center lfc-justify-center">
                    <div className="lfc-w-8 lfc-h-8 lfc-border-2 lfc-border-gray-300 lfc-border-t-gray-700 lfc-rounded-full lfc-animate-spin" />
                  </div>
                )}
              </div>
            </div>
          ) : null}
          {(() => {
            if (!primaryText) return null
            const isHttp = /^https?:\/\//i.test(primaryText)
            const isTelOrSms = /^(tel:|sms:)/i.test(primaryText)
            const isViber = /viber/i.test(title)
            const baseSmall = 'lfc-text-xs lfc-text-gray-600 lfc-break-all'
            const baseNormal = 'lfc-text-sm lfc-text-gray-700 lfc-break-all'
            const emphasized = 'lfc-text-2xl lfc-font-semibold lfc-text-gray-800 lfc-break-all lfc-select-text'
            const normal = 'lfc-text-base lfc-text-gray-700 lfc-break-all lfc-select-text'
            const numberClass = emphasizePrimary ? emphasized : baseNormal
            const linkClass = emphasizePrimary ? 'lfc-text-sm lfc-text-gray-700 lfc-underline lfc-break-all' : 'lfc-text-xs lfc-text-gray-600 lfc-underline lfc-break-all'

            if (isViber) {
              if (/^viber:/i.test(primaryText)) {
                const match = primaryText.match(/number=([^&]+)/i)
                const number = match ? decodeURIComponent(match[1]) : primaryText.replace(/^viber:\/\//i, '')
                return <div className={`mt-3 ${numberClass}`}>{number}</div>
              }
              if (isHttp) {
                return (
                  <div className="lfc-mt-3">
                    <a href={primaryText} target="_blank" rel="noreferrer" className={linkClass}>
                      {primaryText}
                    </a>
                  </div>
                )
              }
              return <div className={`lfc-mt-3 ${emphasizePrimary ? normal : baseSmall}`}>{primaryText}</div>
            }
            if (isTelOrSms) {
              const number = primaryText.replace(/^\w+:/, '')
              return <div className={`lfc-mt-3 ${numberClass}`}>{number}</div>
            }
            if (isHttp) {
              return (
                <div className="lfc-mt-3">
                  <a href={primaryText} target="_blank" rel="noreferrer" className={linkClass}>
                    {primaryText}
                  </a>
                </div>
              )
            }
            return <div className={`lfc-mt-3 ${emphasizePrimary ? normal : baseSmall}`}>{primaryText}</div>
          })()}
          {ctaUrl && ctaText && (
            <div className="lfc-mt-2">
              <a
                href={ctaUrl}
                target="_blank"
                rel="noreferrer"
                className="lfc-text-xs lfc-text-gray-600 lfc-underline"
              >
                {ctaText}
              </a>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default QRModal


