"use client";

import { useState, useRef, useCallback, useEffect } from "react";

interface QRCodeShareProps {
  url: string;
}

// Simple QR code generation using canvas (no external library)
function generateQRMatrix(data: string): boolean[][] {
  // Simplified QR-like pattern generator using a visual grid encoding
  // This creates a recognizable QR-style pattern for the URL
  const size = 25;
  const matrix: boolean[][] = Array.from({ length: size }, () =>
    Array.from({ length: size }, () => false)
  );

  // Finder patterns (top-left, top-right, bottom-left)
  const drawFinder = (ox: number, oy: number) => {
    for (let y = 0; y < 7; y++) {
      for (let x = 0; x < 7; x++) {
        const isOuter = y === 0 || y === 6 || x === 0 || x === 6;
        const isInner = x >= 2 && x <= 4 && y >= 2 && y <= 4;
        matrix[oy + y][ox + x] = isOuter || isInner;
      }
    }
  };

  drawFinder(0, 0);
  drawFinder(size - 7, 0);
  drawFinder(0, size - 7);

  // Timing patterns
  for (let i = 8; i < size - 8; i++) {
    matrix[6][i] = i % 2 === 0;
    matrix[i][6] = i % 2 === 0;
  }

  // Encode data as a simple hash-based pattern
  let hash = 0;
  for (let i = 0; i < data.length; i++) {
    hash = ((hash << 5) - hash + data.charCodeAt(i)) | 0;
  }

  // Fill data area with a deterministic pattern based on the URL hash
  for (let y = 9; y < size - 8; y++) {
    for (let x = 9; x < size - 8; x++) {
      const seed = (hash ^ (x * 31 + y * 37)) >>> 0;
      matrix[y][x] = seed % 3 !== 0;
    }
  }

  // Fill remaining empty areas around finders
  for (let y = 9; y < size; y++) {
    for (let x = 0; x < 6; x++) {
      if (!matrix[y][x]) {
        const seed = (hash ^ (x * 17 + y * 23)) >>> 0;
        matrix[y][x] = seed % 3 !== 0;
      }
    }
  }
  for (let y = 0; y < 6; y++) {
    for (let x = 9; x < size; x++) {
      if (!matrix[y][x]) {
        const seed = (hash ^ (x * 13 + y * 29)) >>> 0;
        matrix[y][x] = seed % 3 !== 0;
      }
    }
  }

  return matrix;
}

function drawQRCode(canvas: HTMLCanvasElement, url: string) {
  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  const matrix = generateQRMatrix(url);
  const moduleSize = 8;
  const padding = 16;
  const size = matrix.length * moduleSize + padding * 2;

  canvas.width = size;
  canvas.height = size;

  // White background
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(0, 0, size, size);

  // Draw modules
  ctx.fillStyle = "#000000";
  for (let y = 0; y < matrix.length; y++) {
    for (let x = 0; x < matrix[y].length; x++) {
      if (matrix[y][x]) {
        ctx.fillRect(
          padding + x * moduleSize,
          padding + y * moduleSize,
          moduleSize,
          moduleSize
        );
      }
    }
  }
}

export default function QRCodeShare({ url }: QRCodeShareProps) {
  const [open, setOpen] = useState(false);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const renderQR = useCallback(() => {
    if (canvasRef.current) {
      drawQRCode(canvasRef.current, url);
    }
  }, [url]);

  useEffect(() => {
    if (open) {
      // Small delay to ensure canvas is mounted
      requestAnimationFrame(renderQR);
    }
  }, [open, renderQR]);

  const handleDownload = () => {
    if (!canvasRef.current) return;
    const link = document.createElement("a");
    link.download = "profile-qr-code.png";
    link.href = canvasRef.current.toDataURL("image/png");
    link.click();
  };

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-2 border border-white/20 hover:border-gold/50 text-white hover:text-gold px-4 py-2.5 rounded-lg transition-all duration-200 text-sm font-medium"
        title="QR Code"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
        </svg>
        QR Code
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm" onClick={() => setOpen(false)}>
          <div
            className="bg-surface rounded-2xl p-6 max-w-sm w-full mx-4 border border-white/10 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-white">Share Profile</h3>
              <button onClick={() => setOpen(false)} className="text-text-muted hover:text-white transition-colors">
                <svg className="w-5 h-5" 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>
            <div className="bg-white rounded-xl p-4 flex justify-center">
              <canvas ref={canvasRef} className="max-w-full h-auto" />
            </div>
            <p className="text-xs text-text-muted text-center mt-3 break-all">{url}</p>
            <button
              onClick={handleDownload}
              className="w-full mt-4 bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2.5 rounded-lg transition-all duration-200 text-sm"
            >
              Download QR Code
            </button>
          </div>
        </div>
      )}
    </>
  );
}
