'use client';

import { useEffect, useRef, useState } from 'react';
import QRCode from 'qrcode';
import { Modal } from '@/components/ui/modal';
import Button from '@/components/ui/button/Button';
import { Typography } from '@/components/atoms/typogrpahy';

interface QRModalProps {
  isOpen: boolean;
  onClose: () => void;
  qrString: string;
  channelName: string;
  amount: number;
}

const QRModal: React.FC<QRModalProps> = ({
  isOpen,
  onClose,
  qrString,
  channelName,
  amount,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string>('');

  useEffect(() => {
    if (qrString && isOpen) {
      generateQRCode();
    }
  }, [qrString, isOpen]);

  const generateQRCode = async () => {
    try {
      if (canvasRef.current) {
        // Generate QR code to canvas
        await QRCode.toCanvas(canvasRef.current, qrString, {
          width: 256,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#FFFFFF'
          }
        });

        // Also generate data URL for copying
        const dataUrl = await QRCode.toDataURL(qrString, {
          width: 256,
          margin: 2,
        });
        setQrDataUrl(dataUrl);
      }
    } catch (error) {
      console.error('Error generating QR code:', error);
    }
  };

  const handleCopyQRString = () => {
    if (qrString) {
      navigator.clipboard.writeText(qrString);
      alert('QR string copied to clipboard!');
    }
  };

  const handleDownloadQR = () => {
    if (qrDataUrl) {
      const link = document.createElement('a');
      link.download = `qr-payment-${Date.now()}.png`;
      link.href = qrDataUrl;
      link.click();
    }
  };

  const handleClose = () => {
    onClose();
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      className="max-w-md mx-auto p-6 rounded-xl shadow-lg dark:bg-gray-900"
    >
      <div className="text-center text-black dark:text-white">
        <h2 className="mb-4 text-2xl font-bold text-brand-500">QR Code Payment</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
          Scan the QR code below with your {channelName} app to complete payment.
        </p>

        {/* QR Code Display */}
        <div className="flex justify-center mb-6">
          <div className="bg-white p-4 rounded-lg shadow-sm">
            <canvas 
              ref={canvasRef}
              className="mx-auto"
            />
          </div>
        </div>

        <div className="space-y-4 mb-8 text-left">
          <div className="flex justify-between items-center py-2 border-b border-gray-200 dark:border-gray-700">
            <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Payment Method:</Typography>
            <Typography variant="s1" className="font-semibold text-lg text-black dark:text-white">
              {channelName}
            </Typography>
          </div>
          <div className="flex justify-between items-center py-2">
            <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount to Pay:</Typography>
            <Typography variant="s1" className="font-semibold text-lg text-black dark:text-white">
              Rp {amount?.toLocaleString('id-ID') || '0'}
            </Typography>
          </div>
        </div>

        <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4 mb-6">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <Typography variant="b2" className="text-blue-800 dark:text-blue-200">
                <strong>How to pay:</strong> Open your {channelName} app, scan this QR code, 
                and confirm the payment. Transaction will be processed immediately.
              </Typography>
            </div>
          </div>
        </div>

        <div className="flex flex-col gap-3">
          <Button 
            variant="primary"
            className="w-full justify-center rounded-md px-6 py-3 bg-brand text-white hover:bg-brand/90 text-lg font-semibold"
            onClick={handleDownloadQR}
          >
            Download QR Code
          </Button>
          <Button 
            variant="outline"
            className="w-full justify-center rounded-md px-6 py-3 border border-slate-300 text-black dark:border-strokedark dark:text-white hover:bg-slate-100 dark:hover:bg-gray-800"
            onClick={handleCopyQRString}
          >
            Copy QR String
          </Button>
          <Button 
            variant="outline" 
            onClick={handleClose}
            className="w-full justify-center rounded-md px-6 py-3 border border-slate-300 text-black dark:border-strokedark dark:text-white hover:bg-slate-100 dark:hover:bg-gray-800 text-lg font-semibold"
          >
            Done
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default QRModal;
