'use client'

import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import { toast } from 'react-toastify'

import { useAuth } from '@/lib/context/AuthContext'
import { ReferralLink } from '@/lib/types/referral-link'
import ReferralLinkCard from './ReferralLinkCard'

interface CardGridProps {
  referralLinks: ReferralLink[]
  hasMore?: boolean
  isLoadingMore?: boolean
  isLoadingInitial?: boolean
  onLoadMore?: () => void
}

export default function CardGrid({
  referralLinks,
  hasMore = false,
  isLoadingMore = false,
  isLoadingInitial = false,
  onLoadMore,
}: CardGridProps) {
  const { user } = useAuth()
  const sentinelRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (!hasMore) return
    if (!sentinelRef.current) return

    const el = sentinelRef.current
    const io = new IntersectionObserver(
      (entries) => {
        const first = entries[0]
        if (first.isIntersecting && !isLoadingMore) {
          onLoadMore?.()
        }
      },
      { rootMargin: '200px 0px' },
    )

    io.observe(el)
    return () => io.unobserve(el)
  }, [hasMore, isLoadingMore, onLoadMore])

  const skeletonItems = useMemo(() => Array.from({ length: 8 }), [])

  const handleDownloadQR = useCallback(
    (linkName: string, qrRef: SVGSVGElement | null) => {
      if (!qrRef) {
        toast.error('QR code not available.')
        return
      }

      const svg = qrRef
      const svgData = new XMLSerializer().serializeToString(svg)
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')!
      const img = new Image()

      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        ctx.fillStyle = '#ffffff'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(img, 0, 0)

        const a = document.createElement('a')
        a.download = `qr-${linkName.toLowerCase().replace(/\s+/g, '-')}.png`
        a.href = canvas.toDataURL('image/png')
        a.click()
      }

      img.src = `data:image/svg+xml;base64,${btoa(svgData)}`
    },
    [],
  )

  return (
    <div className="mt-8">
      {isLoadingInitial ? (
        <div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
          role="list"
        >
          {skeletonItems.map((_, idx) => (
            <article
              key={idx}
              className="rounded-xl border border-gray-200 bg-white p-5 space-y-4 animate-pulse"
            >
              <div className="h-5 bg-slate-200 rounded w-2/3" />
              <div className="flex justify-center rounded-lg border border-gray-100 bg-gray-50 p-6">
                <div className="w-45 h-45 bg-slate-200 rounded" />
              </div>
              <div className="h-10 bg-slate-100 rounded-lg" />
              <div className="h-10 bg-slate-100 rounded-lg" />
            </article>
          ))}
        </div>
      ) : referralLinks?.length === 0 ? (
        <div className="text-center text-slate-500">No data available</div>
      ) : (
        <div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
          role="list"
        >
          {referralLinks?.map((link) => (
            <ReferralLinkCard
              key={link.id}
              link={link}
              referralCode={user?.referral_code}
              onDownloadQR={handleDownloadQR}
            />
          ))}

          {isLoadingMore && (
            <React.Fragment>
              {Array.from({ length: 4 }).map((_, idx) => (
                <article
                  key={idx}
                  className="rounded-xl border border-gray-200 bg-white p-5 space-y-4 animate-pulse h-min"
                >
                  <div className="h-5 bg-slate-200 rounded w-2/3" />
                  <div className="flex justify-center rounded-lg border border-gray-100 bg-gray-50 p-6">
                    <div className="w-45 h-45 bg-slate-200 rounded" />
                  </div>
                  <div className="h-10 bg-slate-100 rounded-lg" />
                  <div className="h-10 bg-slate-100 rounded-lg" />
                </article>
              ))}
            </React.Fragment>
          )}
        </div>
      )}

      {/* Infinite scroll sentinel */}
      <div className="mt-4 flex flex-col items-center">
        <div ref={sentinelRef} className="h-1 w-full" />
        {!hasMore && referralLinks.length > 0 && (
          <p className="text-xs text-slate-400 mt-2">No more results</p>
        )}
      </div>
    </div>
  )
}
