import { useEffect } from 'react'
import { RefreshCw, MonitorSmartphone, Radio } from 'lucide-react'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { useDevices } from '../hooks/use-devices'
import { DeviceCard } from './DeviceCard'
import { ConnectDialog } from './ConnectDialog'
import { DeviceInfoPanel } from './DeviceInfoPanel'
import { useAppStore } from '@/store/app-store'

export function DevicePanel() {
  const { devices, loading, connect, disconnect } = useDevices()
  const {
    selectedDeviceId, setSelectedDeviceId,
    profiledDeviceId, setProfiledDeviceId,
  } = useAppStore()

  // Clear selected/profiled IDs when a device disconnects or goes offline
  useEffect(() => {
    const isOnline = (id: string | null) =>
      id !== null && devices.some((d) => d.id === id && d.status === 'online')

    if (!isOnline(selectedDeviceId)) setSelectedDeviceId(null)
    if (!isOnline(profiledDeviceId)) setProfiledDeviceId(null)
  }, [devices])

  const profiledDevice = devices.find((d) => d.id === profiledDeviceId)

  return (
    <div className="flex h-full">
      {/* Device list */}
      <div className="w-96 flex flex-col border-r border-border shrink-0">

        {/* Active profiling indicator */}
        {profiledDevice ? (
          <div className="flex items-center gap-2 px-4 py-2 bg-green-500/10 border-b border-green-500/20 shrink-0">
            <Radio size={12} className="text-green-400 animate-pulse shrink-0" />
            <div className="min-w-0 flex-1">
              <p className="text-xs font-medium text-green-400 truncate">
                Profiling: {profiledDevice.model || profiledDevice.id}
              </p>
            </div>
            <button
              onClick={() => setProfiledDeviceId(null)}
              className="text-xs text-green-400/70 hover:text-green-400 transition-colors shrink-0"
            >
              Stop
            </button>
          </div>
        ) : (
          <div className="flex items-center gap-2 px-4 py-2 bg-muted/30 border-b border-border shrink-0">
            <Radio size={12} className="text-muted-foreground shrink-0" />
            <p className="text-xs text-muted-foreground">No device being profiled</p>
          </div>
        )}

        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-border shrink-0">
          <div>
            <h2 className="font-semibold text-sm">Devices</h2>
            <p className="text-xs text-muted-foreground">
              {devices.length} {devices.length === 1 ? 'device' : 'devices'} detected
            </p>
          </div>
          <div className="flex items-center gap-2">
            <ConnectDialog onConnect={connect} />
            {loading && <RefreshCw size={14} className="animate-spin text-muted-foreground" />}
          </div>
        </div>

        {/* List */}
        <ScrollArea className="flex-1">
          <div className="p-3 space-y-2">
            {devices.length === 0 && !loading ? (
              <div className="text-center py-10 text-muted-foreground">
                <p className="text-sm">No devices connected.</p>
                <p className="text-xs mt-1">Connect via USB or use wireless ADB.</p>
              </div>
            ) : (
              devices.map((d) => (
                <DeviceCard
                  key={d.id}
                  device={d}
                  isSelected={d.id === selectedDeviceId}
                  isProfiled={d.id === profiledDeviceId}
                  onSelect={setSelectedDeviceId}
                  onProfile={setProfiledDeviceId}
                  onDisconnect={disconnect}
                />
              ))
            )}
          </div>
        </ScrollArea>
      </div>

      <Separator orientation="vertical" />

      {/* Device info */}
      <div className="flex-1 overflow-hidden">
        {selectedDeviceId ? (
          <DeviceInfoPanel deviceId={selectedDeviceId} />
        ) : (
          <div className="flex flex-col items-center justify-center h-full gap-3 text-muted-foreground">
            <MonitorSmartphone size={40} strokeWidth={1.25} />
            <div className="text-center">
              <p className="text-sm font-medium">No device selected</p>
              <p className="text-xs mt-1">Click a device to view its details.</p>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
