import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { Flight } from '../../types'

interface Props {
  flights: Flight[]
  selectedFlight: Flight | null
  onSelect: (flight: Flight) => void
  onCreate: (name: string) => void
  onDelete: (id: string) => void
}

export default function FlightListSidebar({ flights, selectedFlight, onSelect, onCreate, onDelete }: Props) {
  const { t } = useTranslation()
  const [newName, setNewName] = useState('')
  const [creating, setCreating] = useState(false)
  const [search, setSearch] = useState('')

  const handleCreate = () => {
    const name = newName.trim()
    if (!name) { setCreating(false); return }
    onCreate(name)
    setNewName('')
    setCreating(false)
  }

  const handleCancel = () => {
    setNewName('')
    setCreating(false)
  }

  const needle = search.trim().toLowerCase()
  const filteredFlights = needle
    ? flights.filter(f => f.name.toLowerCase().includes(needle))
    : flights

  return (
    <div className="w-[210px] shrink-0 flex flex-col border-r border-border-hair bg-surface-1">

      {/* Header */}
      <div className="px-3 py-2.5 flex items-center justify-between border-b border-border-hair">
        <span className="sect-head">{t('flights.v2.roster')}</span>
        <span className="micro mono" style={{ color: 'var(--text-muted)' }}>
          {String(flights.length).padStart(2, '0')}
        </span>
      </div>

      {/* Search */}
      <div className="px-3 py-2 border-b border-border-hair">
        <div className="relative">
          <input
            className="inp mono text-[11px]"
            style={{ height: 28, letterSpacing: '0.08em', paddingLeft: 28 }}
            placeholder={t('flights.v2.search')}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          <svg
            className="absolute left-2 top-1/2 -translate-y-1/2"
            width="11"
            height="11"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            style={{ color: 'var(--text-muted)' }}
          >
            <circle cx="11" cy="11" r="7" />
            <line x1="21" y1="21" x2="16.65" y2="16.65" />
          </svg>
        </div>
      </div>

      {/* Flight list */}
      <div className="flex-1 overflow-y-auto">
        {filteredFlights.map(f => {
          const isActive = selectedFlight?.id === f.id
          return (
            <div
              key={f.id}
              onClick={() => onSelect(f)}
              className={`group relative flex items-center gap-2 cursor-pointer border-b border-border-hair mono text-[12px]${isActive ? ' bg-surface-2' : ''}`}
              style={{ height: 28, padding: '0 12px' }}
            >
              {isActive && (
                <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: 'var(--accent-amber)' }} />
              )}
              <span style={{ color: 'var(--accent-amber)' }} className="truncate">
                {f.name}
              </span>
              <span
                className="ml-auto text-[10px]"
                style={{ color: 'var(--text-muted)', letterSpacing: '0.08em' }}
              >
                {new Date(f.createdDate).toLocaleDateString()}
              </span>
              <button
                onClick={e => { e.stopPropagation(); onDelete(f.id) }}
                className="opacity-0 group-hover:opacity-100 hover:text-accent-red text-text-muted text-[13px] leading-none shrink-0"
                aria-label="Delete flight"
              >
                &#215;
              </button>
            </div>
          )
        })}
      </div>

      {/* Create section */}
      <div className="p-3 border-t border-border-hair">
        {creating ? (
          <div className="flex gap-1">
            <input
              autoFocus
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter') handleCreate()
                if (e.key === 'Escape') handleCancel()
              }}
              placeholder={t('flights.v2.createNew')}
              className="inp mono flex-1 min-w-0 text-[11px]"
              style={{ height: 28 }}
            />
            <button onClick={handleCreate} className="btn btn-primary shrink-0">
              OK
            </button>
          </div>
        ) : (
          <button
            onClick={() => setCreating(true)}
            className="btn btn-primary w-full flex items-center justify-center gap-2"
          >
            <svg width="10" height="10" viewBox="0 0 10 10">
              <path d="M5 1 V9 M1 5 H9" stroke="currentColor" strokeWidth="1.5" />
            </svg>
            {t('flights.v2.createNew')}
          </button>
        )}
      </div>

      {/* Telemetry card */}
      <div className="m-3 mt-0 bracket panel p-3">
        <span className="br" />
        <div className="flex items-center justify-between mb-2">
          <span className="micro" style={{ color: 'var(--accent-amber)' }}>// {t('flights.telemetry')}</span>
        </div>
        <label className="micro block mb-1">{t('flights.v2.date')}</label>
        <input type="date" className="inp inp-mono text-[12px]" style={{ colorScheme: 'dark' }} />
      </div>

    </div>
  )
}
