import { LuDownload } from 'react-icons/lu'
import { QRCodeSVG } from 'qrcode.react'
import { useRef } from 'react'

import { ReferralLink } from '@/app/(dashboard)/referral-links/types'
import CopyLink from '@/lib/components/CopyLink'

export default function ReferralLinkCard({
  link,
  referralCode,
  onDownloadQR,
}: {
  link: ReferralLink
  referralCode?: string
  onDownloadQR: (linkName: string, qrRef: SVGSVGElement | null) => void
}) {
  const qrRef = useRef<SVGSVGElement>(null)

  return (
    <div className="rounded-xl border border-gray-200 bg-white p-5 space-y-4">
      {/* Link Name */}
      <h3 className="text-lg font-semibold text-gray-900">{link.link_name}</h3>

      {/* QR Code */}
      <div className="flex justify-center rounded-lg border border-gray-100 bg-gray-50 p-6">
        <QRCodeSVG
          ref={qrRef}
          value={`${link.link_url}?ref=${referralCode}`}
          size={180}
          marginSize={4}
          className="mx-auto"
        />
      </div>

      {/* Copy Link */}
      <CopyLink
        link={`${link.link_url}?ref=${referralCode}`}
        variant="default"
        size="md"
        successMessage="Link copied to clipboard!"
      />

      {/* Download QR */}
      <button
        type="button"
        onClick={() => onDownloadQR(link.link_name, qrRef.current)}
        className="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50"
      >
        <LuDownload className="h-4 w-4" />
        Download QR Code
      </button>
    </div>
  )
}
