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

export default function Admin() {
  const router = useRouter()
  const [participants, setParticipants] = useState<Participant[]>([])
  const [selectedAccessCode, setSelectedAccessCode] = useState('')
  const [loading, setLoading] = useState(false)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [pin, setPin] = useState('')
  const [pinError, setPinError] = useState('')
  const [sessionDuration, setSessionDuration] = useState(30)
  const [maxPhotos, setMaxPhotos] = useState(2)
  const [settingsLoading, setSettingsLoading] = useState(false)

  useEffect(() => {
    if (isAuthenticated) {
      fetchParticipants()
      fetchSettings()
      
      // Auto-refresh every 30 seconds
      const interval = setInterval(() => {
        fetchParticipants()
      }, 30000)
      
      return () => clearInterval(interval)
    }
  }, [isAuthenticated])

  const handlePinSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setPinError('')
    
    if (pin.length !== 6) {
      setPinError('PIN must be 6 digits')
      return
    }
    
    try {
      const response = await fetch('/api/admin/auth', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ pin })
      })
      
      if (response.ok) {
        setIsAuthenticated(true)
        setPin('')
      } else {
        setPinError('Invalid PIN')
      }
    } catch (error) {
      setPinError('Authentication error')
    }
  }

  const fetchParticipants = async () => {
    try {
      const response = await fetch('/api/participants')
      const data = await response.json()
      setParticipants(data)
    } catch (error) {
      console.error('Error fetching participants:', error)
    }
  }

  const fetchSettings = async () => {
    try {
      const response = await fetch('/api/admin/settings')
      if (response.ok) {
        const data = await response.json()
        setSessionDuration(data.sessionDuration || 30)
        setMaxPhotos(data.maxPhotos || 2)
      }
    } catch (error) {
      console.error('Error fetching settings:', error)
    }
  }

  const updateSettings = async () => {
    if (sessionDuration < 10 || sessionDuration > 300) {
      alert('Session duration must be between 10 and 300 seconds')
      return
    }
    if (maxPhotos < 1 || maxPhotos > 10) {
      alert('Max photos must be between 1 and 10')
      return
    }

    setSettingsLoading(true)
    try {
      const response = await fetch('/api/admin/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          sessionDuration,
          maxPhotos
        })
      })

      if (response.ok) {
        alert('Settings updated successfully!')
      } else {
        alert('Failed to update settings')
      }
    } catch (error) {
      console.error('Error updating settings:', error)
      alert('Error updating settings')
    } finally {
      setSettingsLoading(false)
    }
  }

  const sendTrigger = async (action: string = 'capture') => {
    if (!selectedAccessCode) {
      alert('Please select a participant')
      return
    }

    setLoading(true)
    try {
      const response = await fetch('/api/trigger', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          accessCode: selectedAccessCode,
          action,
          data: { timestamp: new Date().toISOString() }
        })
      })

      if (response.ok) {
        alert(`Trigger "${action}" sent successfully!`)
      } else {
        alert('Failed to send trigger')
      }
    } catch (error) {
      console.error('Error sending trigger:', error)
      alert('Error sending trigger')
    } finally {
      setLoading(false)
    }
  }

  // Show PIN authentication form if not authenticated
  if (!isAuthenticated) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#f5f5f5'
      }}>
        <div style={{
          backgroundColor: 'white',
          padding: '40px',
          borderRadius: '8px',
          boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
          width: '100%',
          maxWidth: '400px'
        }}>
          <div style={{ textAlign: 'center', marginBottom: '30px' }}>
            <div style={{ fontSize: '48px', marginBottom: '20px' }}>🔒</div>
            <h1 style={{ color: '#333', fontSize: '24px', marginBottom: '10px' }}>
              Admin Access Required
            </h1>
            <p style={{ color: '#666', fontSize: '14px' }}>
              Enter your 6-digit PIN to access the admin panel
            </p>
          </div>
          
          <form onSubmit={handlePinSubmit}>
            <div style={{ marginBottom: '20px' }}>
              <input
                type="password"
                value={pin}
                onChange={(e) => setPin(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="Enter 6-digit PIN"
                maxLength={6}
                style={{
                  width: '100%',
                  padding: '15px',
                  border: pinError ? '2px solid #dc3545' : '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '18px',
                  textAlign: 'center',
                  letterSpacing: '8px',
                  fontFamily: 'monospace',
                  boxSizing: 'border-box'
                }}
                autoFocus
              />
            </div>

            {pinError && (
              <div style={{
                backgroundColor: '#ffebee',
                color: '#c62828',
                padding: '12px',
                borderRadius: '4px',
                marginBottom: '20px',
                fontSize: '14px',
                textAlign: 'center'
              }}>
                {pinError}
              </div>
            )}

            <button
              type="submit"
              disabled={pin.length !== 6}
              style={{
                width: '100%',
                padding: '12px',
                backgroundColor: pin.length === 6 ? '#007bff' : '#ccc',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                fontSize: '16px',
                fontWeight: 'bold',
                cursor: pin.length === 6 ? 'pointer' : 'not-allowed',
                transition: 'background-color 0.2s'
              }}
            >
              🔓 Access Admin Panel
            </button>
          </form>
          
          <div style={{
            marginTop: '20px',
            textAlign: 'center',
            fontSize: '12px',
            color: '#999'
          }}>
            PIN is configured in server environment variables
          </div>
        </div>
      </div>
    )
  }

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
        <h1>🎛️ Photobooth Admin Panel</h1>
        <div style={{ display: 'flex', gap: '10px' }}>
          <button
            onClick={() => router.push('/register')}
            style={{
              padding: '10px 20px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            ➕ Register New Participant
          </button>
          <button
            onClick={() => router.push('/')}
            style={{
              padding: '10px 20px',
              backgroundColor: '#6c757d',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            🏠 Home
          </button>
          <button
            onClick={() => setIsAuthenticated(false)}
            style={{
              padding: '10px 20px',
              backgroundColor: '#dc3545',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            🔒 Logout
          </button>
        </div>
      </div>
      
      <div style={{ marginBottom: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
          <h2>📊 Registered Participants ({participants.length})</h2>
          <button
            onClick={fetchParticipants}
            style={{
              padding: '8px 16px',
              backgroundColor: '#6c757d',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            🔄 Refresh
          </button>
        </div>
        
        {participants.length === 0 ? (
          <div style={{
            textAlign: 'center',
            padding: '40px',
            backgroundColor: '#f8f9fa',
            borderRadius: '8px',
            color: '#6c757d'
          }}>
            <div style={{ fontSize: '48px', marginBottom: '20px' }}>📋</div>
            <h3>No participants registered yet</h3>
            <p>Click "Register New Participant" to add the first participant</p>
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '20px' }}>
            <thead>
              <tr style={{ backgroundColor: '#f0f0f0' }}>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Select</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Name</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Phone</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Access Code</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Registration Time</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Status</th>
                <th style={{ border: '1px solid #ddd', padding: '8px' }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {participants.map((participant) => (
                <tr key={participant.id} style={{ 
                  backgroundColor: selectedAccessCode === participant.accessCode ? '#e3f2fd' : 'white'
                }}>
                  <td style={{ border: '1px solid #ddd', padding: '8px', textAlign: 'center' }}>
                    <input
                      type="radio"
                      name="participant"
                      value={participant.accessCode}
                      checked={selectedAccessCode === participant.accessCode}
                      onChange={(e) => setSelectedAccessCode(e.target.value)}
                    />
                  </td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>{participant.name}</td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>{participant.phone}</td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                    <span style={{ 
                      fontFamily: 'monospace', 
                      fontSize: '14px', 
                      fontWeight: 'bold',
                      backgroundColor: '#e3f2fd',
                      padding: '2px 6px',
                      borderRadius: '3px'
                    }}>
                      {participant.accessCode}
                    </span>
                  </td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                    {new Date(participant.createdAt).toLocaleString('id-ID', {
                      day: '2-digit',
                      month: '2-digit', 
                      year: 'numeric',
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                    <span style={{ 
                      color: participant.isActive ? 'green' : 'red',
                      fontWeight: 'bold'
                    }}>
                      {participant.isActive ? '✅ Active' : '❌ Inactive'}
                    </span>
                  </td>
                  <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                    <button
                      onClick={() => window.open(`/qr/${participant.accessCode}`, '_blank')}
                      style={{
                        padding: '4px 8px',
                        backgroundColor: '#28a745',
                        color: 'white',
                        border: 'none',
                        borderRadius: '3px',
                        cursor: 'pointer',
                        fontSize: '12px',
                        marginRight: '5px'
                      }}
                    >
                      📱 View QR
                    </button>
                    <button
                      onClick={() => window.open(`/photo/${participant.accessCode}`, '_blank')}
                      style={{
                        padding: '4px 8px',
                        backgroundColor: '#007bff',
                        color: 'white',
                        border: 'none',
                        borderRadius: '3px',
                        cursor: 'pointer',
                        fontSize: '12px'
                      }}
                    >
                      📸 Photo Session
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Session Settings */}
      <div style={{ marginBottom: '20px' }}>
        <h2>⚙️ Session Settings</h2>
        <div style={{
          backgroundColor: '#f8f9fa',
          padding: '20px',
          borderRadius: '8px',
          border: '1px solid #dee2e6'
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px', marginBottom: '20px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold', color: '#333' }}>
                Session Duration (seconds)
              </label>
              <input
                type="number"
                min="10"
                max="300"
                value={sessionDuration}
                onChange={(e) => setSessionDuration(Number(e.target.value))}
                style={{
                  width: '100%',
                  padding: '10px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '16px',
                  boxSizing: 'border-box'
                }}
              />
              <small style={{ color: '#666', fontSize: '12px' }}>
                Range: 10-300 seconds
              </small>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold', color: '#333' }}>
                Max Photos per Session
              </label>
              <input
                type="number"
                min="1"
                max="10"
                value={maxPhotos}
                onChange={(e) => setMaxPhotos(Number(e.target.value))}
                style={{
                  width: '100%',
                  padding: '10px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '16px',
                  boxSizing: 'border-box'
                }}
              />
              <small style={{ color: '#666', fontSize: '12px' }}>
                Range: 1-10 photos
              </small>
            </div>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
            <button
              onClick={updateSettings}
              disabled={settingsLoading}
              style={{
                padding: '10px 20px',
                backgroundColor: settingsLoading ? '#ccc' : '#28a745',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: settingsLoading ? 'not-allowed' : 'pointer',
                fontSize: '14px',
                fontWeight: 'bold'
              }}
            >
              {settingsLoading ? 'Saving...' : '💾 Save Settings'}
            </button>
            
            <div style={{ 
              padding: '8px 12px',
              backgroundColor: '#e3f2fd',
              borderRadius: '4px',
              fontSize: '14px',
              color: '#1976d2'
            }}>
              Current: {sessionDuration}s duration, {maxPhotos} photos max
            </div>
          </div>
          
          <div style={{
            marginTop: '15px',
            padding: '10px',
            backgroundColor: '#fff3cd',
            border: '1px solid #ffeaa7',
            borderRadius: '4px',
            fontSize: '14px',
            color: '#856404'
          }}>
            ⚠️ <strong>Note:</strong> Settings will apply to all new photo sessions. Active sessions will continue with their original settings.
          </div>
        </div>
      </div>

      <div style={{ marginBottom: '20px' }}>
        <h2>🎮 Trigger Controls</h2>
        <div style={{
          backgroundColor: '#f8f9fa',
          padding: '20px',
          borderRadius: '8px',
          border: '1px solid #dee2e6'
        }}>
          {!selectedAccessCode ? (
            <div style={{ textAlign: 'center', color: '#6c757d' }}>
              <p>Please select a participant from the table above to send triggers</p>
            </div>
          ) : (
            <>
              <div style={{ marginBottom: '15px' }}>
                <strong>Selected Participant:</strong> {participants.find(p => p.accessCode === selectedAccessCode)?.name} ({selectedAccessCode})
              </div>
              <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                <button
                  onClick={() => sendTrigger('capture')}
                  disabled={loading}
                  style={{
                    padding: '10px 20px',
                    backgroundColor: loading ? '#ccc' : '#007bff',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: loading ? 'not-allowed' : 'pointer',
                    opacity: loading ? 0.6 : 1
                  }}
                >
                  {loading ? 'Sending...' : '📸 Capture Photo'}
                </button>
                
                <button
                  onClick={() => sendTrigger('start_session')}
                  disabled={loading}
                  style={{
                    padding: '10px 20px',
                    backgroundColor: loading ? '#ccc' : '#28a745',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: loading ? 'not-allowed' : 'pointer',
                    opacity: loading ? 0.6 : 1
                  }}
                >
                  ▶️ Start Session
                </button>
                
                <button
                  onClick={() => sendTrigger('stop_session')}
                  disabled={loading}
                  style={{
                    padding: '10px 20px',
                    backgroundColor: loading ? '#ccc' : '#dc3545',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: loading ? 'not-allowed' : 'pointer',
                    opacity: loading ? 0.6 : 1
                  }}
                >
                  ⏹️ Stop Session
                </button>
              </div>
            </>
          )}
        </div>
      </div>

      <div style={{ marginTop: '30px', padding: '20px', backgroundColor: '#e3f2fd', borderRadius: '8px' }}>
        <h3>ℹ️ Instructions</h3>
        <ul style={{ paddingLeft: '20px', lineHeight: '1.6' }}>
          <li>Use "Register New Participant" to add new participants</li>
          <li>Select a participant from the table to send triggers</li>
          <li>Click "View QR" to see participant's QR code</li>
          <li>Click "Photo Session" to open trigger page</li>
          <li>Use trigger controls to send commands to photobooth controller</li>
          <li>Data refreshes automatically every 30 seconds</li>
        </ul>
      </div>
    </div>
  )
}