import { useRouter } from 'next/router'
import { useState, useEffect } from 'react'
import QRCode from 'qrcode'
import { Participant } from '@/lib/database'
import Pusher from 'pusher-js'

export default function QRCodePage() {
  const router = useRouter()
  const { accessCode } = router.query
  const [qrCodeUrl, setQrCodeUrl] = useState('')
  const [participant, setParticipant] = useState<Participant | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [pusherClient, setPusherClient] = useState<Pusher | null>(null)
  const [availableOverlays, setAvailableOverlays] = useState<string[]>([])
  const [selectedOverlay, setSelectedOverlay] = useState<string>('None')

  useEffect(() => {
    if (accessCode && typeof accessCode === 'string') {
      generateQRCode(accessCode)
      fetchParticipant(accessCode)
      setupPusher(accessCode)
      fetchAvailableOverlays()
    }
  }, [accessCode])

  const setupPusher = (code: string) => {
    try {
      // Skip Pusher setup if environment variables are not set
      if (!process.env.NEXT_PUBLIC_PUSHER_KEY || !process.env.NEXT_PUBLIC_PUSHER_CLUSTER) {
        console.log('Pusher environment variables not set, skipping real-time setup')
        console.log('NEXT_PUBLIC_PUSHER_KEY:', process.env.NEXT_PUBLIC_PUSHER_KEY)
        console.log('NEXT_PUBLIC_PUSHER_CLUSTER:', process.env.NEXT_PUBLIC_PUSHER_CLUSTER)
        return
      }

      console.log('Setting up Pusher client...')
      console.log('Pusher Key:', process.env.NEXT_PUBLIC_PUSHER_KEY)
      console.log('Pusher Cluster:', process.env.NEXT_PUBLIC_PUSHER_CLUSTER)

      // Initialize Pusher client
      const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY, {
        cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER,
      })

      console.log('Pusher client initialized, subscribing to channel:', `validation-${code}`)

      // Subscribe to validation channel
      const channel = pusher.subscribe(`validation-${code}`)
      
      // Listen for validation success
      channel.bind('validated', (data: any) => {
        console.log('✅ Access code validated, redirecting to photo session...', data)
        // Redirect to photo trigger page
        router.push(`/photo/${code}`)
      })

      console.log('Pusher client setup complete, listening for validation events')
      setPusherClient(pusher)

      // Cleanup on unmount
      return () => {
        pusher.unsubscribe(`validation-${code}`)
        pusher.disconnect()
      }
    } catch (error) {
      console.error('Pusher setup error:', error)
      // Continue without real-time features
    }
  }

  useEffect(() => {
    return () => {
      if (pusherClient) {
        pusherClient.disconnect()
      }
    }
  }, [pusherClient])

  const generateQRCode = async (code: string) => {
    try {
      const qrCodeDataUrl = await QRCode.toDataURL(code, {
        width: 300,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      })
      setQrCodeUrl(qrCodeDataUrl)
    } catch (error) {
      console.error('QR Code generation error:', error)
      setError('Failed to generate QR code')
    }
  }

  const fetchParticipant = async (code: string) => {
    try {
      const response = await fetch(`/api/participant/${code}`)
      if (response.ok) {
        const data = await response.json()
        setParticipant(data)
      } else {
        console.error('Participant fetch failed:', response.status)
        setError('Participant not found')
      }
    } catch (error) {
      console.error('Participant fetch error:', error)
      setError('Failed to fetch participant information')
    } finally {
      setLoading(false)
    }
  }

  const handleDownload = () => {
    if (qrCodeUrl) {
      const link = document.createElement('a')
      link.href = qrCodeUrl
      link.download = `qr-code-${accessCode}.png`
      link.click()
    }
  }

  const handlePrint = () => {
    window.print()
  }

  const fetchAvailableOverlays = async () => {
    try {
      const response = await fetch('/api/overlays')
      if (response.ok) {
        const data = await response.json()
        setAvailableOverlays(data.overlays)
      }
    } catch (error) {
      console.error('Failed to fetch overlays:', error)
    }
  }

  const handleOverlayChange = async (overlayName: string) => {
    setSelectedOverlay(overlayName)
    
    // Send overlay selection to server
    try {
      await fetch('/api/set-overlay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          accessCode,
          overlayName
        })
      })
    } catch (error) {
      console.error('Failed to set overlay:', error)
    }
  }

  if (loading) {
    return (
      <div style={{ 
        minHeight: '100vh', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        backgroundColor: '#f0f8ff'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '24px', marginBottom: '10px' }}>⏳</div>
          <div>Loading QR Code...</div>
          <div style={{ fontSize: '12px', color: '#666', marginTop: '10px' }}>
            Access Code: {accessCode}
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div style={{ 
        minHeight: '100vh', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        flexDirection: 'column'
      }}>
        <h2 style={{ color: '#dc3545', marginBottom: '20px' }}>Error</h2>
        <p style={{ color: '#666', marginBottom: '20px' }}>{error}</p>
        <button
          onClick={() => router.push('/register')}
          style={{
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Back to Registration
        </button>
      </div>
    )
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      backgroundColor: '#f5f5f5',
      padding: '20px'
    }}>
      <div style={{
        backgroundColor: 'white',
        padding: '40px',
        borderRadius: '8px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
        textAlign: 'center',
        maxWidth: '500px',
        width: '100%'
      }}>
        <h1 style={{ 
          marginBottom: '20px',
          color: '#333',
          fontSize: '24px'
        }}>
          Pendaftaran Berhasil!
        </h1>
        
        {participant && (
          <div style={{
            backgroundColor: '#f8f9fa',
            padding: '20px',
            borderRadius: '6px',
            marginBottom: '30px',
            textAlign: 'left'
          }}>
            <h3 style={{ marginBottom: '15px', color: '#555' }}>Informasi Peserta</h3>
            <p style={{ margin: '5px 0', color: '#666' }}>
              <strong>Nama Lengkap:</strong> {participant.name}
            </p>
            <p style={{ margin: '5px 0', color: '#666' }}>
              <strong>Tanggal pendaftaran:</strong> {new Date(participant.createdAt).toLocaleDateString()}
            </p>
          </div>
        )}

        <div style={{ marginBottom: '30px' }}>
          <h2 style={{ 
            marginBottom: '20px',
            color: '#555',
            fontSize: '20px'
          }}>
            Kode QR
          </h2>
          
          {qrCodeUrl && (
            <div style={{
              display: 'inline-block',
              padding: '20px',
              backgroundColor: '#fff',
              border: '2px solid #ddd',
              borderRadius: '8px',
              marginBottom: '20px'
            }}>
              <img 
                src={qrCodeUrl} 
                alt="QR Code" 
                style={{ display: 'block' }}
              />
            </div>
          )}
        </div>

        <div style={{
          backgroundColor: '#e3f2fd',
          padding: '20px',
          borderRadius: '6px',
          marginBottom: '30px'
        }}>
          <h3 style={{ 
            marginBottom: '15px',
            color: '#1976d2',
            fontSize: '18px'
          }}>
            Kode Akses
          </h3>
          <div style={{
            fontSize: '32px',
            fontWeight: 'bold',
            color: '#1976d2',
            letterSpacing: '4px',
            fontFamily: 'monospace',
            backgroundColor: 'white',
            padding: '15px',
            borderRadius: '4px',
            border: '2px solid #1976d2'
          }}>
            {accessCode}
          </div>
        </div>

        {/* Overlay Selection */}
        <div style={{
          backgroundColor: '#f8f9fa',
          padding: '20px',
          borderRadius: '6px',
          marginBottom: '30px',
          textAlign: 'left'
        }}>
          <h3 style={{ 
            marginBottom: '15px',
            color: '#555',
            fontSize: '18px'
          }}>
            Pilih Frame/Overlay
          </h3>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
            gap: '10px'
          }}>
            <div 
              key="None"
              onClick={() => handleOverlayChange('None')}
              style={{
                padding: '10px',
                border: selectedOverlay === 'None' ? '2px solid #1976d2' : '2px solid #ddd',
                borderRadius: '4px',
                cursor: 'pointer',
                backgroundColor: selectedOverlay === 'None' ? '#e3f2fd' : 'white',
                textAlign: 'center',
                fontSize: '14px',
                fontWeight: selectedOverlay === 'None' ? 'bold' : 'normal'
              }}
            >
              Tanpa Frame
            </div>
            {availableOverlays.map((overlay) => (
              <div 
                key={overlay}
                onClick={() => handleOverlayChange(overlay)}
                style={{
                  padding: '10px',
                  border: selectedOverlay === overlay ? '2px solid #1976d2' : '2px solid #ddd',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  backgroundColor: selectedOverlay === overlay ? '#e3f2fd' : 'white',
                  textAlign: 'center',
                  fontSize: '14px',
                  fontWeight: selectedOverlay === overlay ? 'bold' : 'normal'
                }}
              >
                {overlay.replace('.png', '').replace(/_/g, ' ')}
              </div>
            ))}
          </div>
          {selectedOverlay !== 'None' && (
            <div style={{
              marginTop: '15px',
              padding: '10px',
              backgroundColor: '#d4edda',
              border: '1px solid #c3e6cb',
              borderRadius: '4px',
              color: '#155724',
              fontSize: '14px'
            }}>
              ✅ Frame terpilih: {selectedOverlay.replace('.png', '').replace(/_/g, ' ')}
            </div>
          )}
        </div>


        <div style={{
          marginBottom: '30px',
          textAlign: 'left',
          fontSize: '14px',
          color: '#666'
        }}>
          <h4 style={{ color: '#333', marginBottom: '10px' }}>Instruksi:</h4>
          <ul style={{ paddingLeft: '20px', lineHeight: '1.6' }}>
            <li>Pilih frame/overlay yang diinginkan di atas</li>
            <li>Lakukan pemindaian kode QR</li>
            <li>Sesi 30 detik Anda akan dimulai setelah dilakukan pemindaian</li>
            <li>Satu sesi hanya dapat mengambil 2x foto selama 30 detik</li>
          </ul>
        </div>

        <div style={{
          display: 'flex',
          gap: '10px',
          justifyContent: 'center',
          flexWrap: 'wrap'
        }}>
          <button
            onClick={handleDownload}
            style={{
              padding: '10px 20px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            Download QR Code
          </button>
          
          <button
            onClick={handlePrint}
            style={{
              padding: '10px 20px',
              backgroundColor: '#6c757d',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            Print This Page
          </button>

          {/*<button*/}
          {/*  onClick={() => router.push('/register')}*/}
          {/*  style={{*/}
          {/*    padding: '10px 20px',*/}
          {/*    backgroundColor: '#007bff',*/}
          {/*    color: 'white',*/}
          {/*    border: 'none',*/}
          {/*    borderRadius: '4px',*/}
          {/*    cursor: 'pointer',*/}
          {/*    fontSize: '14px'*/}
          {/*  }}*/}
          {/*>*/}
          {/*  Register Another*/}
          {/*</button>*/}
        </div>
      </div>

      <style jsx>{`
        @media print {
          body { margin: 0; }
          * { -webkit-print-color-adjust: exact !important; }
        }
      `}</style>
    </div>
  )
}