import { useRouter } from 'next/router'
import { useState, useEffect } from 'react'
import { Participant, PhotoSession } from '@/lib/database'

export default function PhotoGallery() {
  const router = useRouter()
  const { accessCode } = router.query
  const [participant, setParticipant] = useState<Participant | null>(null)
  const [session, setSession] = useState<PhotoSession | null>(null)
  const [photos, setPhotos] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (accessCode && typeof accessCode === 'string') {
      fetchParticipantAndPhotos(accessCode)
    }
  }, [accessCode])

  const fetchParticipantAndPhotos = async (code: string) => {
    try {
      const response = await fetch(`/api/participant/${code}`)
      if (response.ok) {
        const data = await response.json()
        setParticipant(data)
        setSession(data.session)
        
        // Fetch photos for this participant
        if (data.session && data.session.photosTaken > 0) {
          const photosResponse = await fetch(`/api/photos/${code}`)
          if (photosResponse.ok) {
            const photosData = await photosResponse.json()
            setPhotos(photosData.photos || [])
          }
        }
      } else {
        setError('Access code not found or invalid')
      }
    } catch (error) {
      setError('Failed to load gallery')
    } finally {
      setLoading(false)
    }
  }

  const downloadPhoto = (photoUrl: string, filename: string) => {
    const link = document.createElement('a')
    link.href = photoUrl
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const downloadAllPhotos = () => {
    photos.forEach((photo, index) => {
      setTimeout(() => {
        downloadPhoto(photo, `photo_${accessCode}_${index + 1}.jpg`)
      }, index * 500) // Delay each download by 500ms
    })
  }

  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 gallery...</div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div style={{ 
        minHeight: '100vh', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        flexDirection: 'column',
        backgroundColor: '#fff5f5'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '48px', marginBottom: '20px' }}>❌</div>
          <h2 style={{ color: '#dc3545', marginBottom: '20px' }}>Gallery Not Found</h2>
          <p style={{ color: '#666', marginBottom: '30px' }}>{error}</p>
          <button
            onClick={() => router.push('/register')}
            style={{
              padding: '12px 24px',
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '16px'
            }}
          >
            Register New Session
          </button>
        </div>
      </div>
    )
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      backgroundColor: '#f0f8ff',
      padding: '20px'
    }}>
      <div style={{
        maxWidth: '1200px',
        margin: '0 auto'
      }}>
        {/* Header */}
        <div style={{
          backgroundColor: 'white',
          padding: '30px',
          borderRadius: '12px',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
          textAlign: 'center',
          marginBottom: '30px'
        }}>
          <h1 style={{ 
            fontSize: '32px',
            color: '#333',
            marginBottom: '10px'
          }}>
            📸 Photo Gallery
          </h1>
          
          {participant && (
            <div style={{ marginBottom: '20px' }}>
              <h2 style={{ 
                fontSize: '24px',
                color: '#1976d2',
                marginBottom: '10px'
              }}>
                {participant.name}
              </h2>
              <div style={{ 
                fontSize: '16px', 
                color: '#666',
                display: 'flex',
                justifyContent: 'center',
                gap: '30px',
                flexWrap: 'wrap'
              }}>
                <div>
                  <strong>Access Code:</strong> {participant.accessCode}
                </div>
                <div>
                  <strong>Phone:</strong> {participant.phone}
                </div>
                {session && (
                  <div>
                    <strong>Photos Taken:</strong> {session.photosTaken}/{session.maxPhotos}
                  </div>
                )}
              </div>
            </div>
          )}

          {photos.length > 0 && (
            <button
              onClick={downloadAllPhotos}
              style={{
                padding: '12px 24px',
                backgroundColor: '#28a745',
                color: 'white',
                border: 'none',
                borderRadius: '8px',
                cursor: 'pointer',
                fontSize: '16px',
                fontWeight: 'bold',
                boxShadow: '0 2px 10px rgba(40, 167, 69, 0.3)'
              }}
            >
              📥 Download All Photos
            </button>
          )}
        </div>

        {/* Photos Grid */}
        {photos.length > 0 ? (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
            gap: '20px',
            marginBottom: '30px'
          }}>
            {photos.map((photo, index) => (
              <div
                key={index}
                style={{
                  backgroundColor: 'white',
                  borderRadius: '12px',
                  overflow: 'hidden',
                  boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)'
                }}
              >
                <img
                  src={photo}
                  alt={`Photo ${index + 1}`}
                  style={{
                    width: '100%',
                    height: '300px',
                    objectFit: 'cover'
                  }}
                  onError={(e) => {
                    (e.target as HTMLImageElement).src = '/placeholder-photo.jpg'
                  }}
                />
                <div style={{ padding: '15px' }}>
                  <h3 style={{ 
                    fontSize: '18px',
                    color: '#333',
                    marginBottom: '10px'
                  }}>
                    Photo {index + 1}
                  </h3>
                  <button
                    onClick={() => downloadPhoto(photo, `photo_${accessCode}_${index + 1}.jpg`)}
                    style={{
                      width: '100%',
                      padding: '10px',
                      backgroundColor: '#007bff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 'bold'
                    }}
                  >
                    📥 Download
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            backgroundColor: 'white',
            padding: '40px',
            borderRadius: '12px',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
            textAlign: 'center'
          }}>
            <div style={{ fontSize: '48px', marginBottom: '20px' }}>📷</div>
            <h3 style={{ color: '#666', marginBottom: '20px' }}>No Photos Available</h3>
            <p style={{ color: '#999' }}>
              {session && session.photosTaken === 0 
                ? 'No photos have been taken yet.' 
                : 'Photos are being processed...'}
            </p>
          </div>
        )}

        {/* Navigation */}
        <div style={{
          backgroundColor: 'white',
          padding: '20px',
          borderRadius: '12px',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
          textAlign: 'center'
        }}>
          <div style={{
            display: 'flex',
            gap: '15px',
            justifyContent: 'center',
            flexWrap: 'wrap'
          }}>
            <button
              onClick={() => router.push(`/photo/${accessCode}`)}
              style={{
                padding: '12px 24px',
                backgroundColor: '#6c757d',
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '16px'
              }}
            >
              ← Back to Photo Session
            </button>
            
            <button
              onClick={() => router.push('/')}
              style={{
                padding: '12px 24px',
                backgroundColor: '#007bff',
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '16px'
              }}
            >
              🏠 Home
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}