'use client';

import { useEffect, useRef, useState } from 'react';
import QRCode from 'qrcode';
import Button from '@/components/ui/button/Button';
import { Typography } from '@/components/atoms/typogrpahy';
import { TOP_UP_COMPLETION_PATH } from '../../topupFlow';
import Image from 'next/image';

interface QRPageProps {
  qrString: string;
  channelName: string;
  channelLogoUrl?: string;
  amount: number;
  onClose: () => void;
}

const QRPage: React.FC<QRPageProps> = ({
  qrString,
  channelName,
  channelLogoUrl,
  amount,
  onClose,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string>('');
  const [showConfirmModal, setShowConfirmModal] = useState(false);

  // Auto redirect if no required data (only runs on client-side)
  useEffect(() => {
    if (!qrString || !channelName) {
      onClose();
    }
  }, [qrString, channelName, onClose]);

  const handleClose = () => {
    setShowConfirmModal(true);
  };

  const handleConfirmClose = () => {
    window.location.href = TOP_UP_COMPLETION_PATH;
  };

  const handleCancelClose = () => {
    setShowConfirmModal(false);
  };

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

  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 = async () => {
    if (qrString && typeof navigator !== 'undefined' && navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(qrString);
        alert('QR string copied to clipboard!');
      } catch (err) {
        console.error('Failed to copy: ', err);
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = qrString;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        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();
    }
  };

  // This component will only be rendered client-side when currentView changes
  // So no need for SSR/hydration checks
  if (!qrString || !channelName) {
    return null;
  }

  const logoSrc = channelLogoUrl?.trim();

  const handleCopyQRImage = async () => {
  if (qrDataUrl && typeof navigator !== 'undefined' && navigator.clipboard) {
    try {
      const blob = await fetch(qrDataUrl).then((res) => res.blob());
      await navigator.clipboard.write([
        new ClipboardItem({ [blob.type]: blob })
      ]);
      alert('QR image copied to clipboard!');
    } catch (err) {
      console.error('Failed to copy QR image: ', err);
      alert('Failed to copy QR image. Your browser may not support this feature.');
    }
  } else {
    alert('Clipboard API not supported in this browser.');
  }
};


  return (
    <div className="flex flex-col min-h-screen bg-white dark:bg-gray-900">
      <div className="flex-shrink-0">
       <div className="p-6">
          <button
            onClick={handleClose}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-white transition-colors"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            <span className="font-medium">Back</span>
          </button>
        </div>
      </div>
      
      <div className="flex-1 flex items-center justify-center px-4">
        <div className="w-full max-w-md mx-auto">
          <div className="text-center text-black dark:text-white">
            {/* Payment Method Icon */}
            <div className="mx-auto w-24 h-16 md:w-40 md:h-24 bg-white dark:bg-gray-800 rounded-2xl flex items-center justify-center p-4 border-gray-100 dark:border-gray-700">
              {logoSrc ? (
                <Image
                  src={logoSrc}
                  alt={channelName}
                  width={64}
                  height={40}
                  className="w-full h-full object-contain"
                />
              ) : null}
            </div>

            <h1 className="mb-4 text-3xl font-bold text-brand-500">QR Code Payment</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
              Scan the QR code below with your {channelName} app to complete payment
            </p>

            {/* QR Code Display */}
            <div className="mb-8">
              <div className="bg-white p-6 rounded-2xl shadow-lg mx-auto inline-block">
                <canvas 
                  ref={canvasRef}
                  className="mx-auto rounded-lg"
                />
              </div>
            </div>

            {/* Payment Details Card */}
            <div className="bg-gray-50 dark:bg-gray-800 rounded-2xl p-6 mb-8">
              <div className="space-y-4">
                <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="h5" className="font-bold 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="h5" className="font-bold text-black dark:text-white">
                    Rp {amount?.toLocaleString('id-ID') || '0'}
                  </Typography>
                </div>
              </div>
            </div>

            {/* Instructions */}
            <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl p-4 mb-8 text-left">
              <div className="flex items-start">
                <div className="flex-shrink-0 mr-3">
                  <svg className="h-6 w-6 text-blue-400 mt-1" 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="flex-1">
                  <Typography variant="b3" className="text-blue-800 dark:text-blue-200 leading-relaxed">
                    <strong>How to pay:</strong>
                    <br />
                    1. Open your {channelName} app
                    <br />
                    2. Look for "Scan QR" or "Pay with QR" option
                    <br />
                    3. Point your camera at the QR code above
                    <br />
                    4. Confirm the payment amount
                    <br />
                    5. Complete the transaction
                    <br />
                    <br />
                    Your payment will be processed immediately and your wallet will be credited.
                  </Typography>
                </div>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="space-y-3">
              <Button 
                variant="primary"
                size="md"
                className="w-full text-lg font-bold bg-brand text-white hover:bg-brand/90 py-4"
                onClick={handleDownloadQR}
              >
                <Typography variant="s5">Download QR Code</Typography>
              </Button>
              
              {/* <Button 
                variant="outline"
                size="md"
                className="w-full text-lg font-semibold border border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
                onClick={handleCopyQRString}
              >
                Copy QR String
              </Button> */}

                <Button 
                    variant="outline"
                    size="md"
                    className="w-full text-lg font-semibold border border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
                    onClick={handleCopyQRImage}
                    >
                        <Typography variant="s5">Copy QR Image</Typography>
                </Button>

              
              <Button 
                variant="outline" 
                size="md"
                onClick={handleClose}
                className="w-full text-lg font-semibold border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
              >
                <Typography variant="s5">Done</Typography>
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      {showConfirmModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 w-full max-w-md mx-auto">
            <div className="text-center">
              {/* Warning Icon */}
              <div className="mx-auto mb-4 w-16 h-16 bg-yellow-100 dark:bg-yellow-900/20 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-yellow-600 dark:text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
              </div>

              <Typography variant="h4" className="font-bold text-black dark:text-white mb-3">
                Save Your Payment Information
              </Typography>
              
              <Typography variant="b2" className="text-gray-600 dark:text-gray-300 mb-6 leading-relaxed">
                Please make sure you have saved or copied your QR code before closing this page. 
                Once closed, this information cannot be retrieved and you'll need to create a new payment request.
              </Typography>

              <div className="space-y-3">
                <Button
                  variant="primary"
                  size="md"
                  onClick={handleConfirmClose}
                  className="w-full bg-brand text-white hover:bg-brand/90 py-3"
                >
                  <Typography variant="s5" className="text-white">Yes, I have saved it</Typography>
                </Button>
                
                <Button
                  variant="outline"
                  size="md"
                  onClick={handleCancelClose}
                  className="w-full border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-3"
                >
                  <Typography variant="s5">Not yet, go back</Typography>
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default QRPage;
