"use client"

import { useRef } from "react"
import { usePathname } from "next/navigation"
import { QRCodeSVG } from "qrcode.react"
import html2canvas from "html2canvas"
import { Download } from "lucide-react"

interface MemberData {
  nameAr: string
  nameEn: string
  membershipNumber: string
  memberType: string
  photo?: string
  faculty?: string
  department?: string
  graduationYear?: number
  phone?: string
  email?: string
  issueDate?: string
  expiryDate?: string
}

interface MembershipCardProps {
  member: MemberData
  showDownload?: boolean
}

export default function MembershipCard({ member, showDownload = false }: MembershipCardProps) {
  const cardRef = useRef<HTMLDivElement>(null)
  const pathname = usePathname()
  const lang = pathname?.split("/")[1] || "ar"

  const verificationUrl = `${typeof window !== "undefined" ? window.location.origin : ""}/${lang}/verify?id=${member.membershipNumber}`

  const handleDownload = async () => {
    if (!cardRef.current) return

    try {
      const canvas = await html2canvas(cardRef.current, {
        scale: 2,
        useCORS: true,
        backgroundColor: null,
        logging: false,
      })

      const link = document.createElement("a")
      link.download = `membership-card-${member.membershipNumber}.png`
      link.href = canvas.toDataURL("image/png")
      link.click()
    } catch (err) {
      console.error("Failed to download card:", err)
    }
  }

  return (
    <div className="space-y-4">
      <div ref={cardRef} className="flex flex-col xl:flex-row gap-10 items-center justify-center p-8">
        {/* ═══════════════════════ FRONT SIDE ═══════════════════════ */}
        <div>
          <h3 className="text-base font-bold text-gray-500 mb-3 text-center uppercase tracking-widest">الوجه الأمامي</h3>
          <div
            className="membership-card-front"
            style={{
              width: "386px",
              height: "192px",
              borderRadius: "12px",
              overflow: "hidden",
              position: "relative",
              boxShadow: "0 20px 60px rgba(0,0,0,0.4), 0 0 0 1px rgba(0,0,0,0.1)",
            }}
          >
            <img
              src="/uploads/Front.svg"
              alt="Card Front"
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
            />
            {member.photo && (
              <div style={{ position: "absolute", top: "30px", left: "20px", width: "60px", height: "75px", borderRadius: "4px", overflow: "hidden" }}>
                <img src={member.photo} alt={member.nameAr} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </div>
            )}
          </div>
        </div>

        {/* ═══════════════════════ BACK SIDE ═══════════════════════ */}
        <div>
          <h3 className="text-base font-bold text-gray-500 mb-3 text-center uppercase tracking-widest">الوجه الخلفي</h3>
          <div
            className="membership-card-back"
            style={{
              width: "386px",
              height: "192px",
              borderRadius: "12px",
              overflow: "hidden",
              position: "relative",
              boxShadow: "0 20px 60px rgba(0,0,0,0.4), 0 0 0 1px rgba(0,0,0,0.1)",
            }}
          >
            <img
              src="/uploads/Back.svg"
              alt="Card Back"
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
            />
            {/* QR Code - positioned at bottom-right area of the back */}
            <div style={{ position: "absolute", bottom: "20px", right: "20px", background: "white", padding: "4px", borderRadius: "4px" }}>
              <QRCodeSVG
                value={verificationUrl}
                size={50}
                level="M"
                includeMargin={false}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Download Button */}
      {showDownload && (
        <div className="flex justify-center">
          <button
            onClick={handleDownload}
            className="flex items-center gap-2 px-6 py-3 bg-[#1A3A6B] text-white rounded-xl hover:bg-[#0f2547] transition-colors text-sm font-medium"
          >
            <Download className="w-4 h-4" />
            تحميل البطاقة
          </button>
        </div>
      )}
    </div>
  )
}
