import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { api, endpoints } from '../../api'
import type { SystemSettings, DirectorySettings, Aircraft } from '../../types'

export default function SettingsPage() {
  const { t } = useTranslation()
  const [system, setSystem] = useState<SystemSettings | null>(null)
  const [dirs, setDirs] = useState<DirectorySettings | null>(null)
  const [aircrafts, setAircrafts] = useState<Aircraft[]>([])
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    api.get<SystemSettings>(endpoints.annotations.settingsSystem()).then(setSystem).catch(() => {})
    api.get<DirectorySettings>(endpoints.annotations.settingsDirectories()).then(setDirs).catch(() => {})
    api.get<Aircraft[]>(endpoints.flights.aircrafts()).then(setAircrafts).catch(() => {})
  }, [])

  const saveSystem = async () => {
    if (!system) return
    setSaving(true)
    await api.put(endpoints.annotations.settingsSystem(), system)
    setSaving(false)
  }

  const saveDirs = async () => {
    if (!dirs) return
    setSaving(true)
    await api.put(endpoints.annotations.settingsDirectories(), dirs)
    setSaving(false)
  }

  const handleToggleDefault = async (a: Aircraft) => {
    await api.patch(endpoints.flights.aircraft(a.id), { isDefault: !a.isDefault })
    setAircrafts(prev => prev.map(x => x.id === a.id ? { ...x, isDefault: !x.isDefault } : x))
  }

  const field = (label: string, value: string | number | null | undefined, onChange: (v: string) => void, type = 'text') => (
    <div>
      <label className="text-az-muted text-xs block mb-0.5">{label}</label>
      <input
        type={type}
        value={value ?? ''}
        onChange={e => onChange(e.target.value)}
        className="w-full bg-az-bg border border-az-border rounded px-2 py-1 text-xs text-az-text outline-none focus:border-az-orange"
      />
    </div>
  )

  return (
    <div className="flex h-full overflow-y-auto p-4 gap-6">
      {/* Tenant config */}
      <div className="w-[300px] shrink-0">
        <h2 className="text-sm font-semibold text-white mb-2">{t('settings.tenant')}</h2>
        {system && (
          <div className="bg-az-panel border border-az-border rounded p-3 space-y-2">
            {field('Military Unit', system.militaryUnit, v => setSystem(p => p ? { ...p, militaryUnit: v } : p))}
            {field('Name', system.name, v => setSystem(p => p ? { ...p, name: v } : p))}
            {field('Default Camera Width', system.defaultCameraWidth, v => setSystem(p => p ? { ...p, defaultCameraWidth: parseInt(v) || 0 } : p), 'number')}
            {field('Default Camera FoV', system.defaultCameraFoV, v => setSystem(p => p ? { ...p, defaultCameraFoV: parseFloat(v) || 0 } : p), 'number')}
            <button onClick={saveSystem} disabled={saving} className="bg-az-orange text-white text-xs px-3 py-1 rounded disabled:opacity-50">
              {t('settings.save')}
            </button>
          </div>
        )}
      </div>

      {/* Directories */}
      <div className="w-[300px] shrink-0">
        <h2 className="text-sm font-semibold text-white mb-2">{t('settings.directories')}</h2>
        {dirs && (
          <div className="bg-az-panel border border-az-border rounded p-3 space-y-2">
            {field('Videos Dir', dirs.videosDir, v => setDirs(p => p ? { ...p, videosDir: v } : p))}
            {field('Images Dir', dirs.imagesDir, v => setDirs(p => p ? { ...p, imagesDir: v } : p))}
            {field('Labels Dir', dirs.labelsDir, v => setDirs(p => p ? { ...p, labelsDir: v } : p))}
            {field('Results Dir', dirs.resultsDir, v => setDirs(p => p ? { ...p, resultsDir: v } : p))}
            {field('Thumbnails Dir', dirs.thumbnailsDir, v => setDirs(p => p ? { ...p, thumbnailsDir: v } : p))}
            {field('GPS Sat Dir', dirs.gpsSatDir, v => setDirs(p => p ? { ...p, gpsSatDir: v } : p))}
            {field('GPS Route Dir', dirs.gpsRouteDir, v => setDirs(p => p ? { ...p, gpsRouteDir: v } : p))}
            <button onClick={saveDirs} disabled={saving} className="bg-az-orange text-white text-xs px-3 py-1 rounded disabled:opacity-50">
              {t('settings.save')}
            </button>
          </div>
        )}
      </div>

      {/* Aircrafts */}
      <div className="flex-1 max-w-sm">
        <h2 className="text-sm font-semibold text-white mb-2">{t('settings.aircrafts')}</h2>
        <div className="bg-az-panel border border-az-border rounded p-2 space-y-1">
          {aircrafts.map(a => (
            <div key={a.id} className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-az-bg text-xs text-az-text">
              <span className="flex-1">{a.model}</span>
              <span className={`px-1 rounded text-[10px] ${a.type === 'Plane' ? 'bg-az-blue/20 text-az-blue' : 'bg-az-green/20 text-az-green'}`}>
                {a.type}
              </span>
              <button onClick={() => handleToggleDefault(a)} className={`text-sm ${a.isDefault ? 'text-az-orange' : 'text-az-muted hover:text-az-orange'}`}>
                ★
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
