import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { newGuid } from './flightPlanUtils'
import type { OrthoPhoto } from './types'

interface LiveGps {
  lat: number
  lon: number
  satellites: number
  status: string
}

interface Props {
  liveGps: LiveGps | null
  orthophotos: OrthoPhoto[]
  onAddOrthophotos: (photos: OrthoPhoto[]) => void
  /** Apply a manual GPS correction to a waypoint (1-based number as shown in the list). */
  onApplyCorrection: (waypointNumber: number, lat: number, lon: number) => void
  onBack: () => void
}

/**
 * GPS-Denied operating mode. The orthophoto upload and correction form are
 * functional-local (no backend endpoint exists yet); the Live GPS readout is
 * fed by the real SSE stream via the `liveGps` prop.
 */
function Row({ label, className, children }: { label: string; className?: string; children: React.ReactNode }) {
  return (
    <div className={`flex items-center justify-between py-1 ${className ?? ''}`}>
      <span className="micro">{label}</span>
      {children}
    </div>
  )
}

export default function GpsDeniedPanel({ liveGps, orthophotos, onAddOrthophotos, onApplyCorrection, onBack }: Props) {
  const { t } = useTranslation()
  const [wp, setWp] = useState('')
  const [coords, setCoords] = useState('')

  const handleUpload = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.multiple = true
    input.onchange = (e) => {
      const files = Array.from((e.target as HTMLInputElement).files ?? [])
      if (!files.length) return
      const base = orthophotos.length
      const photos: OrthoPhoto[] = files.map((f, i) => ({
        id: newGuid(),
        name: f.name,
        lat: 48.8566 + (base + i) * 0.0046,
        lon: 2.3522 + (base + i) * 0.0079,
      }))
      onAddOrthophotos(photos)
    }
    input.click()
  }

  const handleApply = () => {
    const num = parseInt(wp, 10)
    const parts = coords.split(',').map(s => Number(s.trim()))
    // Waypoint numbers are 1-based; reject 0/negative and non-numeric input.
    if (!Number.isFinite(num) || num < 1 || parts.length !== 2 || !parts.every(Number.isFinite)) return
    onApplyCorrection(num, parts[0], parts[1])
  }

  const connected = liveGps?.status?.toUpperCase().includes('CONNECT') ?? false

  return (
    <section className="p-4 space-y-5 flex-1 overflow-y-auto">
      <header className="flex items-center justify-between gap-2">
        <h2 className="sect-head" style={{ color: 'var(--accent-red)', whiteSpace: 'nowrap' }}>{t('flights.v2.gpsDeniedActive')}</h2>
        <span className="pill pill-red" style={{ whiteSpace: 'nowrap', flexShrink: 0 }}>
          <span className="dot live" />{t('flights.v2.active')}
        </span>
      </header>

      {/* Orthophoto upload — red frame (mockup: .bracket-red + .gps-active-frame).
          Remap --accent-amber→red locally so the .bracket corner ticks render red;
          no amber-colored children live inside this frame. */}
      <div className="bracket panel" style={{
        padding: 12,
        border: '2px solid var(--accent-red)',
        boxShadow: 'inset 0 0 0 1px rgba(255,71,86,0.12)',
        ['--accent-amber' as string]: 'var(--accent-red)',
      } as React.CSSProperties}>
        <header className="flex items-center justify-between" style={{ marginBottom: 12 }}>
          <span className="sect-head" style={{ color: 'var(--accent-red)' }}>// {t('flights.v2.orthophotoUpload')}</span>
          <span className="micro mono" style={{ color: 'var(--text-muted)' }}>
            {String(orthophotos.length).padStart(2, '0')} / 12
          </span>
        </header>

        <div className="space-y-1.5">
          {orthophotos.map((p, i) => (
            <div key={p.id} className="flex items-center gap-2.5 border border-border-hair"
              style={{ padding: '8px 10px', background: 'var(--surface-0)' }}>
              <span className="flex items-center justify-center shrink-0 mono"
                style={{ width: 24, height: 24, background: 'var(--accent-cyan)', color: '#0A0D10', fontSize: 10, fontWeight: 700 }}>
                P{i + 1}
              </span>
              <span className="mono text-[11px] flex-1 truncate" style={{ color: 'var(--text-primary)' }}>{p.name}</span>
              <span className="mono text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                {p.lat.toFixed(4)}, {p.lon.toFixed(4)}
              </span>
            </div>
          ))}
        </div>

        <button onClick={handleUpload}
          className="w-full mono flex items-center justify-center gap-2"
          style={{ marginTop: 10, padding: '8px 0', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
            border: '1px dashed var(--border-raised)', color: 'var(--text-secondary)', background: 'transparent', borderRadius: 2 }}>
          <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 1 V9 M1 5 H9" stroke="currentColor" strokeWidth="1.4" /></svg>
          {t('flights.v2.uploadPhotos')}
        </button>
        <span className="br" />
      </div>

      {/* Live GPS readout */}
      <div className="bracket panel" style={{ padding: 12 }}>
        <header className="flex items-center justify-between gap-2" style={{ marginBottom: 10 }}>
          <span className="sect-head" style={{ whiteSpace: 'nowrap' }}>// {t('flights.v2.liveGps')}</span>
          <span className={`pill ${connected ? 'pill-green' : 'pill-muted'}`} style={{ whiteSpace: 'nowrap', flexShrink: 0 }}>
            <span className="dot live" />{connected ? t('flights.v2.connected') : t('flights.v2.offline')}
          </span>
        </header>
        <div className="space-y-1.5 text-[12px]">
          <Row label={t('flights.v2.status')} className="border-b border-border-hair">
            <span className="mono" style={{ whiteSpace: 'nowrap', color: connected ? 'var(--accent-green)' : 'var(--text-secondary)' }}>
              {connected ? t('flights.v2.connectedStreaming') : t('flights.v2.offline')}
            </span>
          </Row>
          <Row label={t('flights.v2.latitude')} className="border-b border-border-hair">
            <span className="mono num">{(liveGps?.lat ?? 0).toFixed(5)}° N</span>
          </Row>
          <Row label={t('flights.v2.longitude')} className="border-b border-border-hair">
            <span className="mono num">{(liveGps?.lon ?? 0).toFixed(5)}° E</span>
          </Row>
          <Row label={t('flights.v2.satellites')} className="border-b border-border-hair">
            <span className="mono num" style={{ color: 'var(--accent-cyan)' }}>{liveGps?.satellites ?? 0} / 14</span>
          </Row>
          <Row label={t('flights.v2.drift')}>
            <span className="mono num" style={{ color: 'var(--accent-amber)' }}>±2.4 M</span>
          </Row>
        </div>
        <span className="br" />
      </div>

      {/* GPS Correction */}
      <div className="bracket panel" style={{ padding: 12 }}>
        <header className="flex items-center justify-between" style={{ marginBottom: 10 }}>
          <span className="sect-head">// {t('flights.v2.gpsCorrection')}</span>
        </header>
        <div className="space-y-2.5">
          <div>
            <label className="micro block mb-1.5">{t('flights.v2.waypointNum')}</label>
            <input value={wp} onChange={e => setWp(e.target.value)} type="number" className="inp inp-mono" />
          </div>
          <div>
            <label className="micro block mb-1.5">{t('flights.v2.correctedGps')}</label>
            <input value={coords} onChange={e => setCoords(e.target.value)} type="text" placeholder="48.86120, 2.36011" className="inp inp-mono" />
          </div>
          <button onClick={handleApply} className="btn btn-primary w-full justify-center">{t('flights.v2.applyCorrection')}</button>
        </div>
        <span className="br" />
      </div>

      <button onClick={onBack} className="btn btn-ghost w-full justify-center">‹ {t('flights.v2.backToParams')}</button>
    </section>
  )
}
