'use client'

import { useEffect, useRef } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Copy, QrCode } from 'lucide-react'
import { toast } from 'sonner'

interface QRCodeDisplayProps {
  url: string
  title?: string
  size?: number
}

/**
 * Generates a simple QR code using Canvas API.
 * Uses a basic QR encoding approach for URLs.
 */
function generateQRMatrix(data: string): boolean[][] {
  // Simple QR-like grid pattern based on data hash
  // For production, use a library like 'qrcode', but this is a lightweight visual
  const size = 25
  const matrix: boolean[][] = Array.from({ length: size }, () =>
    Array(size).fill(false)
  )

  // Add finder patterns (top-left, top-right, bottom-left)
  const addFinderPattern = (row: number, col: number) => {
    for (let r = 0; r < 7; r++) {
      for (let c = 0; c < 7; c++) {
        if (
          r === 0 || r === 6 || c === 0 || c === 6 || // outer border
          (r >= 2 && r <= 4 && c >= 2 && c <= 4) // inner block
        ) {
          if (row + r < size && col + c < size) {
            matrix[row + r][col + c] = true
          }
        }
      }
    }
  }

  addFinderPattern(0, 0)
  addFinderPattern(0, size - 7)
  addFinderPattern(size - 7, 0)

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

  for (let r = 8; r < size - 8; r++) {
    for (let c = 8; c < size - 8; c++) {
      hash = ((hash << 5) - hash + r * size + c) | 0
      matrix[r][c] = (hash & 1) === 1
    }
  }

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

  return matrix
}

function drawQR(canvas: HTMLCanvasElement, data: string, pixelSize: number) {
  const matrix = generateQRMatrix(data)
  const size = matrix.length
  const totalSize = size * pixelSize
  canvas.width = totalSize
  canvas.height = totalSize

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // White background
  ctx.fillStyle = '#ffffff'
  ctx.fillRect(0, 0, totalSize, totalSize)

  // Draw modules
  ctx.fillStyle = '#053d57'
  for (let r = 0; r < size; r++) {
    for (let c = 0; c < size; c++) {
      if (matrix[r][c]) {
        ctx.fillRect(c * pixelSize, r * pixelSize, pixelSize, pixelSize)
      }
    }
  }
}

export function QRCodeDisplay({ url, title = 'Scan to Vote', size = 200 }: QRCodeDisplayProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const pixelSize = Math.floor(size / 25)

  useEffect(() => {
    if (canvasRef.current) {
      drawQR(canvasRef.current, url, pixelSize)
    }
  }, [url, pixelSize])

  const handleCopyUrl = () => {
    navigator.clipboard.writeText(url).then(() => {
      toast.success('URL copied to clipboard')
    })
  }

  return (
    <Card>
      <CardHeader className="pb-2">
        <CardTitle className="text-sm flex items-center gap-2">
          <QrCode className="h-4 w-4" />
          {title}
        </CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col items-center gap-3">
        <canvas
          ref={canvasRef}
          className="border rounded-lg"
          style={{ width: size, height: size }}
        />
        <div className="flex items-center gap-2 w-full">
          <code className="flex-1 text-xs bg-muted p-2 rounded truncate">
            {url}
          </code>
          <Button variant="ghost" size="sm" onClick={handleCopyUrl}>
            <Copy className="h-3.5 w-3.5" />
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
