import { useState, useRef, useEffect, useCallback } from 'react'
import { INPUT_CLASS } from '../../../ui/tokens'

export function FilterBar({ children, right }) {
  return (
    <div className="flex items-center justify-between gap-3 border-b border-slate-200 px-6 py-3 flex-shrink-0">
      <div className="flex flex-wrap items-center gap-2">{children}</div>
      {right && <div className="flex items-center gap-2 flex-shrink-0">{right}</div>}
    </div>
  )
}

// ── Searchable custom dropdown ─────────────────────────────────────────────────

export function FilterSelect({ value, onChange, options, label, icon: Icon }) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const containerRef = useRef(null)
  const inputRef = useRef(null)
  const listRef = useRef(null)

  const selected = options.find(o => o.value === value)

  const filtered = query.trim()
    ? options.filter(o => o.label.toLowerCase().includes(query.toLowerCase()))
    : options

  // Close on outside click
  useEffect(() => {
    function handler(e) {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setOpen(false)
        setQuery('')
      }
    }
    if (open) document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  // Focus search input when opening
  useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus()
  }, [open])

  function handleSelect(val) {
    onChange(val)
    setOpen(false)
    setQuery('')
  }

  function handleKeyDown(e) {
    if (e.key === 'Escape') { setOpen(false); setQuery('') }
  }

  // Dropdown position: flip up if near bottom of viewport
  const [dropUp, setDropUp] = useState(false)
  const openDropdown = useCallback(() => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect()
      setDropUp(rect.bottom + 280 > window.innerHeight)
    }
    setOpen(true)
  }, [])

  return (
    <div ref={containerRef} className="relative" onKeyDown={handleKeyDown}>
      {/* Trigger button */}
      <button
        type="button"
        onClick={() => open ? (setOpen(false), setQuery('')) : openDropdown()}
        className={`flex items-center gap-2 ${INPUT_CLASS} cursor-pointer whitespace-nowrap`}
      >
        {Icon && <Icon className="h-3.5 w-3.5 text-slate-400 flex-shrink-0" />}
        {label && (
          <span className="text-[11px] font-medium uppercase tracking-wider text-slate-400 flex-shrink-0">
            {label}
          </span>
        )}
        <span className="text-[13px] text-slate-700 font-normal">
          {selected?.label ?? '—'}
        </span>
        <svg className="ml-1 h-3.5 w-3.5 text-slate-400 flex-shrink-0 transition-transform" style={{ transform: open ? 'rotate(180deg)' : '' }} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {/* Dropdown panel */}
      {open && (
        <div
          className={`absolute z-50 w-64 rounded-lg border border-slate-200 bg-white shadow-lg ring-1 ring-slate-100 ${dropUp ? 'bottom-full mb-1' : 'top-full mt-1'}`}
          style={{ minWidth: 'max-content' }}
        >
          {/* Search box — only shown when there are enough options */}
          {options.length > 6 && (
            <div className="border-b border-slate-100 px-3 py-2">
              <div className="flex items-center gap-2 rounded-md border border-slate-200 bg-slate-50 px-2.5 py-1.5">
                <svg className="h-3.5 w-3.5 text-slate-400 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                  <circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
                <input
                  ref={inputRef}
                  type="text"
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder="Αναζήτηση…"
                  className="flex-1 bg-transparent text-[12px] text-slate-700 placeholder-slate-400 outline-none"
                />
                {query && (
                  <button onClick={() => setQuery('')} className="text-slate-400 hover:text-slate-600">
                    <svg className="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5}>
                      <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
                    </svg>
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Options list */}
          <ul ref={listRef} className="max-h-64 overflow-y-auto py-1">
            {filtered.length === 0 ? (
              <li className="px-4 py-3 text-[12px] text-slate-400 text-center">Δεν βρέθηκαν αποτελέσματα</li>
            ) : (
              filtered.map(o => {
                const isActive = o.value === value
                return (
                  <li key={o.value}>
                    <button
                      type="button"
                      onClick={() => handleSelect(o.value)}
                      className={`w-full px-4 py-2 text-left text-[13px] transition-colors flex items-center gap-2 ${
                        isActive
                          ? 'bg-sky-50 text-sky-700 font-medium'
                          : 'text-slate-700 hover:bg-slate-50'
                      }`}
                    >
                      {isActive && (
                        <svg className="h-3.5 w-3.5 text-sky-500 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5}>
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      )}
                      {!isActive && <span className="w-3.5 flex-shrink-0" />}
                      <span className="truncate">{o.label}</span>
                    </button>
                  </li>
                )
              })
            )}
          </ul>
        </div>
      )}
    </div>
  )
}

// ── Date input ─────────────────────────────────────────────────────────────────

const GR_MONTHS = ['Ιανουάριος','Φεβρουάριος','Μάρτιος','Απρίλιος','Μάιος','Ιούνιος','Ιούλιος','Αύγουστος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος']
const GR_DAYS   = ['Κυ','Δε','Τρ','Τε','Πε','Πα','Σα']

function fmtGR(value) {
  if (!value) return ''
  const [y, m, d] = value.split('-')
  if (!y || !m || !d) return value
  return `${d}/${m}/${y}`
}

function CalendarDropdown({ value, onCommit, onClose }) {
  const today = new Date()
  const initYear  = value ? parseInt(value.slice(0, 4)) : today.getFullYear()
  const initMonth = value ? parseInt(value.slice(5, 7)) - 1 : today.getMonth()

  const [viewYear,  setViewYear]  = useState(initYear)
  const [viewMonth, setViewMonth] = useState(initMonth)

  const selectedY = value ? parseInt(value.slice(0, 4)) : null
  const selectedM = value ? parseInt(value.slice(5, 7)) - 1 : null
  const selectedD = value ? parseInt(value.slice(8, 10)) : null

  function prevMonth(e) {
    e.stopPropagation()
    if (viewMonth === 0) { setViewMonth(11); setViewYear(y => y - 1) }
    else setViewMonth(m => m - 1)
  }
  function nextMonth(e) {
    e.stopPropagation()
    if (viewMonth === 11) { setViewMonth(0); setViewYear(y => y + 1) }
    else setViewMonth(m => m + 1)
  }

  // Build grid: first cell = weekday of 1st of month (0=Sun)
  const firstDow = new Date(viewYear, viewMonth, 1).getDay()
  const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate()
  const cells = []
  for (let i = 0; i < firstDow; i++) cells.push(null)
  for (let d = 1; d <= daysInMonth; d++) cells.push(d)

  function selectDay(e, day) {
    e.stopPropagation()
    const mm = String(viewMonth + 1).padStart(2, '0')
    const dd = String(day).padStart(2, '0')
    onCommit(`${viewYear}-${mm}-${dd}`)
    onClose()
  }

  const todayY = today.getFullYear()
  const todayM = today.getMonth()
  const todayD = today.getDate()

  return (
    <div
      className="absolute left-0 top-full mt-1 z-50 w-64 rounded-lg border border-slate-200 bg-white shadow-xl ring-1 ring-slate-100 select-none"
      onMouseDown={e => e.preventDefault()}
      onClick={e => e.stopPropagation()}
    >
      {/* Month navigation */}
      <div className="flex items-center justify-between px-3 py-2 border-b border-slate-100">
        <button
          type="button"
          onClick={prevMonth}
          className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"
        >
          <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}><polyline points="15 18 9 12 15 6" /></svg>
        </button>
        <span className="text-[13px] font-semibold text-slate-800">
          {GR_MONTHS[viewMonth]} {viewYear}
        </span>
        <button
          type="button"
          onClick={nextMonth}
          className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"
        >
          <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}><polyline points="9 18 15 12 9 6" /></svg>
        </button>
      </div>

      {/* Day-of-week headers */}
      <div className="grid grid-cols-7 px-2 pt-2 pb-1">
        {GR_DAYS.map(d => (
          <div key={d} className="text-center text-[10px] font-semibold text-slate-400 py-0.5">{d}</div>
        ))}
      </div>

      {/* Day cells */}
      <div className="grid grid-cols-7 px-2 pb-2 gap-y-0.5">
        {cells.map((day, i) => {
          if (!day) return <div key={`e${i}`} />
          const isSelected = day === selectedD && viewMonth === selectedM && viewYear === selectedY
          const isToday    = day === todayD    && viewMonth === todayM    && viewYear === todayY
          return (
            <button
              key={day}
              type="button"
              onClick={e => selectDay(e, day)}
              className={`
                h-8 w-8 mx-auto rounded-full text-[12px] font-medium transition-colors
                ${isSelected
                  ? 'bg-sky-500 text-white'
                  : isToday
                    ? 'bg-sky-50 text-sky-700 ring-1 ring-sky-200 hover:bg-sky-100'
                    : 'text-slate-700 hover:bg-slate-100'
                }
              `}
            >
              {day}
            </button>
          )
        })}
      </div>
    </div>
  )
}

export function FilterDateInput({ value, onChange, label }) {
  const [open, setOpen] = useState(false)
  const containerRef = useRef(null)

  useEffect(() => {
    if (!open) return
    function handler(e) {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  return (
    <div ref={containerRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className={`flex items-center gap-2 ${INPUT_CLASS} cursor-pointer`}
      >
        <svg className="h-3.5 w-3.5 text-slate-400 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
          <rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" />
        </svg>
        {label && (
          <span className="text-[11px] font-medium uppercase tracking-wider text-slate-400 flex-shrink-0">
            {label}
          </span>
        )}
        <span className="text-[13px] font-normal whitespace-nowrap">
          {value
            ? <span className="text-slate-700">{fmtGR(value)}</span>
            : <span className="text-slate-400">ΗΗ/ΜΜ/ΕΕΕΕ</span>
          }
        </span>
      </button>

      {open && (
        <CalendarDropdown
          value={value}
          onCommit={onChange}
          onClose={() => setOpen(false)}
        />
      )}
    </div>
  )
}

// ── Work Day / Date Range toggle ───────────────────────────────────────────────

export function WorkDayDateToggle({ mode, onChange }) {
  return (
    <div className="inline-flex items-center rounded-md border border-slate-200 bg-slate-50 p-0.5 shadow-[inset_0_1px_0_rgba(15,23,42,0.04)]">
      {[
        { id: 'workday', label: 'Εργάσιμη Μέρα' },
        { id: 'range',   label: 'Εύρος Ημερομηνιών' },
      ].map((opt) => (
        <button
          key={opt.id}
          type="button"
          onClick={() => onChange(opt.id)}
          className={`flex items-center gap-1.5 rounded px-2.5 py-1 text-[12px] font-medium transition whitespace-nowrap ${
            mode === opt.id
              ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200'
              : 'text-slate-500 hover:text-slate-700'
          }`}
        >
          {opt.label}
        </button>
      ))}
    </div>
  )
}
