'use client'

/**
 * EventsFilterBar — 治理事件篩選列
 * ==================================
 * event_type 多選 / 時間範圍 / status / severity / 清除全部
 * GlassCard variant="subtle" padding="sm"
 *
 * @created 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5
 */

import { useState, useRef, useEffect } from 'react'
import { Filter, Calendar, ChevronDown, Search, X } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { GlassCard } from '@/components/ui/glass-card'

// =============================================================================
// Types
// =============================================================================

export interface EventsFilter {
  eventId: string
  eventTypes: string[]
  status: 'all' | 'resolved' | 'unresolved'
  severity: 'all' | 'critical' | 'warning' | 'info'
  dateFrom: string
  dateTo: string
}

interface EventsFilterBarProps {
  filter: EventsFilter
  onChange: (filter: EventsFilter) => void
  availableEventTypes?: string[]
}

// =============================================================================
// Helpers
// =============================================================================

const SEVERITY_COLOR: Record<string, string> = {
  critical: '#FF3300',
  warning:  '#F59E0B',
  info:     '#4A90D9',
}

// =============================================================================
// Multi-select combobox
// =============================================================================

interface MultiSelectProps {
  options: string[]
  selected: string[]
  onChange: (values: string[]) => void
  placeholder: string
  labelMap?: Record<string, string>
}

function MultiSelect({ options, selected, onChange, placeholder, labelMap }: MultiSelectProps) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

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

  const toggle = (v: string) => {
    onChange(selected.includes(v) ? selected.filter(x => x !== v) : [...selected, v])
  }

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          display: 'flex', alignItems: 'center', gap: 4,
          padding: '4px 8px',
          border: '0.5px solid #e0ddd4',
          borderRadius: 6,
          background: selected.length > 0 ? 'rgba(217,119,87,0.06)' : '#fff',
          cursor: 'pointer',
          fontFamily: "'DM Mono', monospace",
          fontSize: 11,
          color: selected.length > 0 ? '#d97757' : '#87867f',
          transition: 'all 0.12s',
          whiteSpace: 'nowrap',
        }}
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <Filter size={11} />
        {selected.length > 0 ? `${selected.length} 已選` : placeholder}
        <ChevronDown size={10} style={{ marginLeft: 2, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }} />
      </button>

      {open && (
        <div
          role="listbox"
          style={{
            position: 'absolute', top: '100%', left: 0, zIndex: 50,
            marginTop: 4,
            background: '#fff',
            border: '0.5px solid #e0ddd4',
            borderRadius: 8,
            boxShadow: '0 8px 24px rgba(0,0,0,0.10)',
            minWidth: 160,
            padding: 4,
          }}
        >
          {options.map(opt => (
            <button
              key={opt}
              role="option"
              aria-selected={selected.includes(opt)}
              onClick={() => toggle(opt)}
              style={{
                display: 'flex', alignItems: 'center', gap: 8,
                width: '100%', padding: '5px 10px',
                background: selected.includes(opt) ? 'rgba(217,119,87,0.06)' : 'transparent',
                border: 'none', cursor: 'pointer', borderRadius: 4,
                fontFamily: "'DM Mono', monospace", fontSize: 11,
                color: selected.includes(opt) ? '#d97757' : '#141413',
                textAlign: 'left',
              }}
            >
              <span style={{
                width: 12, height: 12, borderRadius: 3,
                border: `1.5px solid ${selected.includes(opt) ? '#d97757' : '#d0cec7'}`,
                background: selected.includes(opt) ? '#d97757' : 'transparent',
                flexShrink: 0,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {selected.includes(opt) && (
                  <svg width="8" height="6" viewBox="0 0 8 6" fill="none">
                    <path d="M1 3l2 2 4-4" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </span>
              {labelMap?.[opt] ?? opt}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

// =============================================================================
// Component
// =============================================================================

export function EventsFilterBar({ filter, onChange, availableEventTypes = [] }: EventsFilterBarProps) {
  const t = useTranslations('governance.events.filter')
  const tType = useTranslations('governance.events.eventType')

  const eventTypeLabels: Record<string, string> = {
    slo_violation: tType('slo_violation'),
    governance_slo_data_gap: tType('governance_slo_data_gap'),
    knowledge_degradation: tType('knowledge_degradation'),
    kb_stale: tType('kb_stale'),
    execution_blast_radius: tType('execution_blast_radius'),
    conservative_mode: tType('conservative_mode'),
    replay_degraded: tType('replay_degraded'),
    self_demotion: tType('self_demotion'),
    slo_breach: tType('slo_breach'),
    accuracy_drop: tType('accuracy_drop'),
    km_stall: tType('km_stall'),
    mcp_failure: tType('mcp_failure'),
    trust_degradation: tType('trust_degradation'),
  }

  const hasActiveFilter =
    filter.eventId.trim() !== '' ||
    filter.eventTypes.length > 0 ||
    filter.status !== 'all' ||
    filter.severity !== 'all' ||
    filter.dateFrom !== '' ||
    filter.dateTo !== ''

  const clearAll = () => onChange({
    eventId: '',
    eventTypes: [],
    status: 'all',
    severity: 'all',
    dateFrom: '',
    dateTo: '',
  })

  const selectStyle = {
    padding: '4px 8px',
    border: '0.5px solid #e0ddd4',
    borderRadius: 6,
    background: '#fff',
    cursor: 'pointer',
    fontFamily: "'DM Mono', monospace",
    fontSize: 11,
    color: '#141413',
    appearance: 'none' as const,
    WebkitAppearance: 'none' as const,
    paddingRight: 24,
  }

  const dateInputStyle = {
    padding: '4px 8px',
    border: '0.5px solid #e0ddd4',
    borderRadius: 6,
    background: '#fff',
    fontFamily: "'DM Mono', monospace",
    fontSize: 11,
    color: '#141413',
    cursor: 'pointer',
  }

  return (
    <GlassCard variant="subtle" padding="sm">
      <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}>

        {/* Event type multi-select */}
        <MultiSelect
          options={availableEventTypes.length > 0 ? availableEventTypes : Object.keys(eventTypeLabels)}
          selected={filter.eventTypes}
          onChange={v => onChange({ ...filter, eventTypes: v })}
          placeholder={t('placeholder')}
          labelMap={eventTypeLabels}
        />

        {/* Event ID exact search */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Search size={11} style={{ color: '#87867f', flexShrink: 0 }} />
          <input
            type="search"
            value={filter.eventId}
            onChange={e => onChange({ ...filter, eventId: e.target.value })}
            placeholder={t('eventIdPlaceholder')}
            aria-label={t('eventId')}
            style={{
              padding: '4px 8px',
              border: '0.5px solid #e0ddd4',
              borderRadius: 6,
              background: '#fff',
              fontFamily: "'DM Mono', monospace",
              fontSize: 11,
              color: '#141413',
              minWidth: 190,
            }}
          />
        </div>

        {/* Date from */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Calendar size={11} style={{ color: '#87867f', flexShrink: 0 }} />
          <input
            type="date"
            value={filter.dateFrom}
            onChange={e => onChange({ ...filter, dateFrom: e.target.value })}
            style={dateInputStyle}
            aria-label={t('from')}
          />
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f' }}>–</span>
          <input
            type="date"
            value={filter.dateTo}
            onChange={e => onChange({ ...filter, dateTo: e.target.value })}
            style={dateInputStyle}
            aria-label={t('to')}
          />
        </div>

        {/* Status select */}
        <div style={{ position: 'relative' }}>
          <select
            value={filter.status}
            onChange={e => onChange({ ...filter, status: e.target.value as EventsFilter['status'] })}
            style={selectStyle}
            aria-label={t('status')}
          >
            <option value="all">{t('allStatuses')}</option>
            <option value="resolved">{t('resolved')}</option>
            <option value="unresolved">{t('unresolved')}</option>
          </select>
          <ChevronDown size={10} style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', color: '#87867f', pointerEvents: 'none' }} />
        </div>

        {/* Severity select */}
        <div style={{ position: 'relative' }}>
          <select
            value={filter.severity}
            onChange={e => onChange({ ...filter, severity: e.target.value as EventsFilter['severity'] })}
            style={{
              ...selectStyle,
              color: filter.severity !== 'all' ? SEVERITY_COLOR[filter.severity] : '#141413',
            }}
            aria-label={t('severity')}
          >
            <option value="all">{t('allSeverities')}</option>
            <option value="critical">{t('critical')}</option>
            <option value="warning">{t('warning')}</option>
            <option value="info">{t('info')}</option>
          </select>
          <ChevronDown size={10} style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', color: '#87867f', pointerEvents: 'none' }} />
        </div>

        {/* Clear all */}
        {hasActiveFilter && (
          <button
            onClick={clearAll}
            style={{
              display: 'flex', alignItems: 'center', gap: 4,
              background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: "'DM Mono', monospace", fontSize: 11,
              color: '#d97757', marginLeft: 4,
              padding: '4px 0',
            }}
          >
            <X size={11} />
            {t('clearAll')}
          </button>
        )}
      </div>
    </GlassCard>
  )
}
