'use client'

import { useState, useEffect } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Loader2, Download, Printer, CheckCircle } from 'lucide-react'
import { toast } from 'sonner'
import { generateProductQRCode } from '@/lib/qr-code'

interface QRCodeDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  produit?: any
}

export function QRCodeDialog({ open, onOpenChange, produit }: QRCodeDialogProps) {
  const [qrCodeData, setQrCodeData] = useState<string>('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (open && produit) {
      generateQR()
    }
  }, [open, produit])

  const generateQR = async () => {
    if (!produit) return

    try {
      setLoading(true)
      const qrData = await generateProductQRCode(produit.reference, produit.designation)
      setQrCodeData(qrData)
    } catch (error) {
      console.error('Error generating QR code:', error)
      toast.error('Erreur lors de la génération du QR code')
    } finally {
      setLoading(false)
    }
  }

  const handleDownload = () => {
    if (!qrCodeData) return

    const link = document.createElement('a')
    link.href = qrCodeData
    link.download = `qr-${produit?.reference || 'produit'}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    toast.success('QR code téléchargé')
  }

  const handlePrint = () => {
    if (!qrCodeData) return

    const printWindow = window.open('', '_blank')
    if (!printWindow) return

    const printContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <title>QR Code - ${produit?.reference}</title>
          <style>
            body {
              font-family: Arial, sans-serif;
              display: flex;
              justify-content: center;
              align-items: center;
              min-height: 100vh;
              margin: 0;
              padding: 20px;
            }
            .qr-label {
              border: 2px solid #000;
              padding: 20px;
              text-align: center;
              width: 300px;
            }
            .qr-label img {
              width: 200px;
              height: 200px;
            }
            .qr-label h2 {
              margin: 10px 0 5px;
              font-size: 18px;
            }
            .qr-label p {
              margin: 5px 0;
              font-size: 14px;
            }
            .qr-label .reference {
              font-weight: bold;
              font-size: 16px;
            }
          </style>
        </head>
        <body>
          <div class="qr-label">
            <img src="${qrCodeData}" alt="QR Code" />
            <h2>${produit?.designation || 'Produit'}</h2>
            <p class="reference">${produit?.reference || ''}</p>
            ${produit?.codeBarre ? `<p>Code-barres: ${produit.codeBarre}</p>` : ''}
            ${produit?.prixVenteTTC ? `<p>Prix: ${new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(produit.prixVenteTTC)}</p>` : ''}
          </div>
        </body>
      </html>
    `

    printWindow.document.write(printContent)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    toast.success('Impression lancée')
  }

  if (!produit) return null

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>QR Code du Produit</DialogTitle>
          <DialogDescription>
            Générez et imprimez le QR code pour l'étiquetage
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : (
            <Card>
              <CardContent className="p-6">
                <div className="flex flex-col items-center space-y-4">
                  {qrCodeData && (
                    <img
                      src={qrCodeData}
                      alt="QR Code"
                      className="border-2 border-gray-200 rounded-lg p-2"
                    />
                  )}
                  <div className="text-center space-y-1">
                    <p className="font-semibold text-lg">{produit.designation}</p>
                    <p className="text-sm text-gray-500">Réf: {produit.reference}</p>
                    {produit.codeBarre && (
                      <p className="text-xs text-gray-400">EAN: {produit.codeBarre}</p>
                    )}
                    {produit.prixVenteTTC && (
                      <p className="text-lg font-bold text-green-600 mt-2">
                        {new Intl.NumberFormat('fr-FR', {
                          style: 'currency',
                          currency: 'EUR',
                        }).format(produit.prixVenteTTC)}
                      </p>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        <DialogFooter className="flex gap-2">
          <Button
            variant="outline"
            onClick={handleDownload}
            disabled={!qrCodeData || loading}
            className="flex-1"
          >
            <Download className="mr-2 h-4 w-4" />
            Télécharger
          </Button>
          <Button
            onClick={handlePrint}
            disabled={!qrCodeData || loading}
            className="flex-1"
          >
            <Printer className="mr-2 h-4 w-4" />
            Imprimer
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
