import { useState, type ChangeEvent } from 'react'
import { Search } from 'lucide-react'
import styles from './FilterBar.module.css'
import { Input } from '../../primitives/Input/Input'
import { FilterPill } from '../../primitives/FilterPill/FilterPill'
import { Tag } from '../../primitives/Tag/Tag'

export interface FilterOption {
  label: string
  value: string
  count?: number
  color?: 'success' | 'error' | 'running'
}

export interface ActiveFilter {
  label: string
  value: string
}

interface FilterBarProps {
  filters: FilterOption[]
  activeFilters: ActiveFilter[]
  onFilterChange: (filters: ActiveFilter[]) => void
  searchPlaceholder?: string
  searchValue?: string
  onSearchChange?: (value: string) => void
  className?: string
}

export function FilterBar({
  filters,
  activeFilters,
  onFilterChange,
  searchPlaceholder = 'Search...',
  searchValue,
  onSearchChange,
  className,
}: FilterBarProps) {
  const [internalSearch, setInternalSearch] = useState('')
  const search = searchValue !== undefined ? searchValue : internalSearch

  function handleSearchChange(e: ChangeEvent<HTMLInputElement>) {
    if (onSearchChange) {
      onSearchChange(e.target.value)
    } else {
      setInternalSearch(e.target.value)
    }
  }

  function toggleFilter(filter: FilterOption) {
    const isActive = activeFilters.some((f) => f.value === filter.value)
    if (isActive) {
      onFilterChange(activeFilters.filter((f) => f.value !== filter.value))
    } else {
      onFilterChange([...activeFilters, { label: filter.label, value: filter.value }])
    }
  }

  function removeFilter(value: string) {
    onFilterChange(activeFilters.filter((f) => f.value !== value))
  }

  function clearAll() {
    onFilterChange([])
  }

  const hasActiveFilters = activeFilters.length > 0

  return (
    <div className={`${styles.section} ${className ?? ''}`}>
      <div className={styles.row}>
        <div className={styles.searchWrap}>
          <Input
            placeholder={searchPlaceholder}
            value={search}
            onChange={handleSearchChange}
            onClear={search ? () => {
              if (onSearchChange) onSearchChange('')
              else setInternalSearch('')
            } : undefined}
            icon={<Search size={13} />}
          />
        </div>

        {filters.length > 0 && <div className={styles.sep} />}

        {filters.length > 0 && (
          <div className={styles.filterGroup}>
            {filters.map((filter) => (
              <FilterPill
                key={filter.value}
                label={filter.label}
                count={filter.count}
                active={activeFilters.some((f) => f.value === filter.value)}
                onClick={() => toggleFilter(filter)}
              />
            ))}
          </div>
        )}
      </div>

      {hasActiveFilters && (
        <div className={styles.activeTags}>
          {activeFilters.map((filter) => (
            <Tag
              key={filter.value}
              label={filter.label}
              onRemove={() => removeFilter(filter.value)}
              color="auto"
            />
          ))}
          <button className={styles.clearAll} onClick={clearAll} type="button">
            Clear all
          </button>
        </div>
      )}
    </div>
  )
}
