import { useState, useCallback, useMemo } from 'react'
import { Camera, Play, Square, Wifi, WifiOff, AlertTriangle } from 'lucide-react'
import { useSSE } from './hooks/useSSE'
import { useCameraStore } from './store/useCameraStore'
import { api } from './services/api'
import CameraCard from './components/CameraCard'
import HistoryViewer from './components/HistoryViewer'

function App() {
  const [commandBusy, setCommandBusy] = useState(false)
  const [commandError, setCommandError] = useState<string | null>(null)
  const [historyCameraId, setHistoryCameraId] = useState<string | null>(null)
  const [historyCameraName, setHistoryCameraName] = useState<string>()

  // SSE connection + live store
  const { connectionState } = useSSE()

  // Subscribe to full camera state — dashboard needs every change
  const camerasMap = useCameraStore((s) => s.cameras)
  const cameras = useMemo(() => Array.from(camerasMap.values()), [camerasMap])
  const onlineCount = useMemo(() => cameras.filter((c) => c.online).length, [cameras])
  const recordingCount = useMemo(() => cameras.filter((c) => c.recording).length, [cameras])

  const cameraIds = cameras.map((c) => c.camera_id)

  // ── Command helpers ──

  const handleStart = useCallback(async (cameraId: string) => {
    setCommandBusy(true)
    setCommandError(null)
    try {
      await api.startRecording(cameraId)
    } catch (err) {
      setCommandError(err instanceof Error ? err.message : 'Command failed')
    } finally {
      setCommandBusy(false)
    }
  }, [])

  const handleStop = useCallback(async (cameraId: string) => {
    setCommandBusy(true)
    setCommandError(null)
    try {
      await api.stopRecording(cameraId)
    } catch (err) {
      setCommandError(err instanceof Error ? err.message : 'Command failed')
    } finally {
      setCommandBusy(false)
    }
  }, [])

  const handleStartAll = useCallback(async () => {
    setCommandBusy(true)
    setCommandError(null)
    try {
      await Promise.all(cameraIds.map((id) => api.startRecording(id)))
    } catch {
      // Individual failures are non-fatal — some may succeed
    } finally {
      setCommandBusy(false)
    }
  }, [cameraIds])

  const handleStopAll = useCallback(async () => {
    setCommandBusy(true)
    setCommandError(null)
    try {
      await Promise.all(cameraIds.map((id) => api.stopRecording(id)))
    } catch {
      // Individual failures are non-fatal
    } finally {
      setCommandBusy(false)
    }
  }, [cameraIds])

  const handleViewHistory = useCallback((cameraId: string) => {
    const cam = useCameraStore.getState().cameras.get(cameraId)
    setHistoryCameraId(cameraId)
    setHistoryCameraName(cam?.friendly_name ?? cameraId)
  }, [])

  const handleCloseHistory = useCallback(() => {
    setHistoryCameraId(null)
  }, [])

  // ── Connection badge ──

  const connectionBadge = {
    connected: { icon: Wifi, label: 'Live', class: 'bg-rig-success/15 text-rig-success' },
    connecting: { icon: Wifi, label: 'Connecting...', class: 'bg-rig-warning/15 text-rig-warning' },
    disconnected: { icon: WifiOff, label: 'Disconnected', class: 'bg-rig-danger/15 text-rig-danger' },
    error: { icon: AlertTriangle, label: 'Stream Error', class: 'bg-rig-danger/15 text-rig-danger' },
  }[connectionState] ?? {
    icon: WifiOff,
    label: 'Disconnected',
    class: 'bg-rig-danger/15 text-rig-danger',
  }

  const BadgeIcon = connectionBadge.icon

  // ── Render ──

  return (
    <div className="min-h-screen bg-rig-dark-900 flex flex-col">
      {/* Header */}
      <header className="shrink-0 border-b border-rig-dark-700 bg-rig-dark-800/50 backdrop-blur-sm">
        <div className="mx-auto max-w-7xl px-4 py-3 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-3 min-w-0">
              <Camera className="h-6 w-6 shrink-0 text-rig-accent" />
              <h1 className="text-lg font-bold tracking-tight text-rig-dark-50 truncate">
                RemoteRig
              </h1>
              <span className="hidden sm:inline rounded-full bg-rig-accent/10 px-2.5 py-0.5 text-xs font-medium text-rig-accent">
                Dashboard
              </span>
            </div>

            {/* Connection status */}
            <div className="flex items-center gap-3">
              {/* SSE badge */}
              <span
                className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium ${connectionBadge.class}`}
              >
                <BadgeIcon className="h-3 w-3" />
                {connectionBadge.label}
              </span>

              {/* Global controls */}
              <div className="flex items-center gap-1">
                <button
                  onClick={handleStartAll}
                  disabled={commandBusy || cameras.length === 0}
                  className="flex items-center gap-1 rounded-md bg-rig-success/20 px-3 py-1.5 text-xs font-medium text-rig-success hover:bg-rig-success/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  title="Start recording on all cameras"
                >
                  <Play className="h-3.5 w-3.5 fill-current" />
                  <span className="hidden sm:inline">Start All</span>
                </button>
                <button
                  onClick={handleStopAll}
                  disabled={commandBusy || cameras.length === 0}
                  className="flex items-center gap-1 rounded-md bg-rig-danger/20 px-3 py-1.5 text-xs font-medium text-rig-danger hover:bg-rig-danger/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  title="Stop recording on all cameras"
                >
                  <Square className="h-3.5 w-3.5 fill-current" />
                  <span className="hidden sm:inline">Stop All</span>
                </button>
              </div>
            </div>
          </div>

          {/* Stats strip */}
          <div className="mt-2 flex items-center gap-4 text-xs text-rig-dark-400">
            <span>
              <strong className="text-rig-dark-100">{cameras.length}</strong> camera{cameras.length !== 1 ? 's' : ''}
            </span>
            <span>
              <strong className="text-rig-success">{onlineCount}</strong> online
            </span>
            <span>
              <strong className={recordingCount > 0 ? 'text-rig-danger' : 'text-rig-dark-300'}>
                {recordingCount}
              </strong>{' '}
              recording
            </span>
          </div>
        </div>
      </header>

      {/* Command error toast */}
      {commandError && (
        <div className="shrink-0 border-b border-rig-danger/30 bg-rig-danger/10 px-4 py-2">
          <p className="mx-auto max-w-7xl text-xs text-rig-danger">
            <AlertTriangle className="inline h-3 w-3 mr-1" />
            {commandError}
          </p>
        </div>
      )}

      {/* Main Content */}
      <main className="flex-1 mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
        {cameras.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-rig-dark-600 bg-rig-dark-800/30 py-24 text-center">
            <Camera className="mb-4 h-12 w-12 text-rig-dark-500" />
            <h2 className="text-lg font-semibold text-rig-dark-200">
              No Cameras Connected
            </h2>
            <p className="mt-2 max-w-sm text-sm text-rig-dark-400">
              Waiting for camera nodes to connect. Ensure ESP32 bridges are powered on and connected to the network.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {cameras.map((cam) => (
              <CameraCard
                key={cam.camera_id}
                camera={cam}
                onStart={handleStart}
                onStop={handleStop}
                onViewHistory={handleViewHistory}
                disabled={commandBusy}
              />
            ))}
          </div>
        )}
      </main>

      {/* History modal */}
      <HistoryViewer
        cameraId={historyCameraId}
        cameraName={historyCameraName}
        onClose={handleCloseHistory}
      />

      {/* Footer */}
      <footer className="shrink-0 border-t border-rig-dark-700 bg-rig-dark-800/30">
        <div className="mx-auto max-w-7xl px-4 py-3 sm:px-6 lg:px-8">
          <p className="text-center text-xs text-rig-dark-500">
            RemoteRig v0.1.0 &mdash; Multi-Camera Remote Monitoring System
          </p>
        </div>
      </footer>
    </div>
  )
}

export default App
