import { useState, useCallback, useMemo } from 'react'
import { Filter, Search, SlidersHorizontal, Calendar, HardDrive } from 'lucide-react'
import { formatPlatformName } from '../lib/utils'

export interface FilterState {
  platformFilter: string
  sourceFilter: string
  typeFilter: 'all' | 'image' | 'video'
  searchQuery: string
  dateFrom: string
  dateTo: string
  sizeMin: string
  sizeMax: string
  sortBy: string
  sortOrder: 'asc' | 'desc'
}

export interface FilterBarProps {
  filters: FilterState
  platforms?: string[]
  sources?: string[]
  onFilterChange: <K extends keyof FilterState>(key: K, value: FilterState[K]) => void
  onReset: () => void
  sortOptions?: Array<{ value: string; label: string }>
  showFaceRecognitionFilter?: boolean
  faceRecognitionFilter?: string
  onFaceRecognitionChange?: (value: string) => void
  showDeletedFromFilter?: boolean
  deletedFromFilter?: string | null
  onDeletedFromChange?: (value: string | null) => void
  deletedFromStats?: Record<string, { count: number }>
  searchPlaceholder?: string
  dateLabelPrefix?: string
}

const DEFAULT_SORT_OPTIONS = [
  { value: 'post_date', label: 'Post Date' },
  { value: 'download_date', label: 'Download Date' },
  { value: 'file_size', label: 'File Size' },
  { value: 'filename', label: 'Filename' },
  { value: 'source', label: 'Source' },
  { value: 'platform', label: 'Platform' },
]

export default function FilterBar({
  filters,
  platforms = [],
  sources = [],
  onFilterChange,
  onReset,
  sortOptions = DEFAULT_SORT_OPTIONS,
  showFaceRecognitionFilter = false,
  faceRecognitionFilter = '',
  onFaceRecognitionChange,
  showDeletedFromFilter = false,
  deletedFromFilter = null,
  onDeletedFromChange,
  deletedFromStats,
  searchPlaceholder = 'Search filenames...',
  dateLabelPrefix = 'Date',
}: FilterBarProps) {
  const [showAdvanced, setShowAdvanced] = useState(false)

  const {
    platformFilter,
    sourceFilter,
    typeFilter,
    searchQuery,
    dateFrom,
    dateTo,
    sizeMin,
    sizeMax,
    sortBy,
    sortOrder,
  } = filters

  // Check if any filters are active
  const hasActiveFilters = useMemo(() => {
    return !!(
      searchQuery ||
      typeFilter !== 'all' ||
      platformFilter ||
      sourceFilter ||
      dateFrom ||
      dateTo ||
      sizeMin ||
      sizeMax ||
      faceRecognitionFilter ||
      deletedFromFilter
    )
  }, [searchQuery, typeFilter, platformFilter, sourceFilter, dateFrom, dateTo, sizeMin, sizeMax, faceRecognitionFilter, deletedFromFilter])

  const handleClearAll = useCallback(() => {
    onReset()
    if (onFaceRecognitionChange) onFaceRecognitionChange('')
    if (onDeletedFromChange) onDeletedFromChange(null)
  }, [onReset, onFaceRecognitionChange, onDeletedFromChange])

  return (
    <div className="card-glass-hover rounded-xl p-4 space-y-4">
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2 text-slate-700 dark:text-slate-300">
          <Filter className="w-4 h-4" />
          <span className="text-sm font-medium">Filters</span>
        </div>
        {hasActiveFilters && (
          <button
            onClick={handleClearAll}
            className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
          >
            Clear all
          </button>
        )}
      </div>

      {/* Main Filters Row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Platform Filter */}
        <select
          value={platformFilter}
          onChange={(e) => onFilterChange('platformFilter', e.target.value)}
          className={`px-4 py-2 rounded-lg border ${
            platformFilter
              ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
              : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
          } text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
        >
          <option value="">All Platforms</option>
          {platforms.map((platform) => (
            <option key={platform} value={platform}>
              {formatPlatformName(platform)}
            </option>
          ))}
        </select>

        {/* Source Filter */}
        <select
          value={sourceFilter}
          onChange={(e) => onFilterChange('sourceFilter', e.target.value)}
          className={`px-4 py-2 rounded-lg border ${
            sourceFilter
              ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
              : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
          } text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
        >
          <option value="">All Sources</option>
          {sources.map((source) => (
            <option key={source} value={source}>
              {source}
            </option>
          ))}
        </select>

        {/* Type Filter */}
        <select
          value={typeFilter}
          onChange={(e) => onFilterChange('typeFilter', e.target.value as 'all' | 'image' | 'video')}
          className={`px-4 py-2 rounded-lg border ${
            typeFilter !== 'all'
              ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
              : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
          } text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
        >
          <option value="all">All Media</option>
          <option value="image">Images Only</option>
          <option value="video">Videos Only</option>
        </select>

        {/* Face Recognition Filter (optional) */}
        {showFaceRecognitionFilter && onFaceRecognitionChange && (
          <select
            value={faceRecognitionFilter}
            onChange={(e) => onFaceRecognitionChange(e.target.value)}
            className={`px-4 py-2 rounded-lg border ${
              faceRecognitionFilter
                ? 'border-green-500 bg-green-50 dark:bg-green-900/20'
                : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
            } text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-green-500`}
          >
            <option value="">All Files</option>
            <option value="matched">Matched Only</option>
            <option value="no_match">No Match Only</option>
            <option value="not_scanned">Not Scanned</option>
          </select>
        )}

        {/* Deleted From Filter (for RecycleBin) */}
        {showDeletedFromFilter && onDeletedFromChange && (
          <select
            value={deletedFromFilter || ''}
            onChange={(e) => onDeletedFromChange(e.target.value || null)}
            className={`px-4 py-2 rounded-lg border ${
              deletedFromFilter
                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
            } text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
          >
            <option value="">All Deleted From</option>
            <option value="downloads">Downloads ({deletedFromStats?.downloads?.count || 0})</option>
            <option value="media">Media ({deletedFromStats?.media?.count || 0})</option>
            <option value="review">Review ({deletedFromStats?.review?.count || 0})</option>
            <option value="instagram_perceptual_duplicate_detection">
              Perceptual Duplicates ({deletedFromStats?.instagram_perceptual_duplicate_detection?.count || 0})
            </option>
          </select>
        )}
      </div>

      {/* Sort and Advanced Filters Row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Sort By */}
        <select
          value={sortBy}
          onChange={(e) => onFilterChange('sortBy', e.target.value)}
          className="px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          {sortOptions.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>

        {/* Sort Order */}
        <select
          value={sortOrder}
          onChange={(e) => onFilterChange('sortOrder', e.target.value as 'asc' | 'desc')}
          className="px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="desc">Newest First</option>
          <option value="asc">Oldest First</option>
        </select>

        {/* Advanced Filters Toggle */}
        <button
          onClick={() => setShowAdvanced(!showAdvanced)}
          className={`flex items-center justify-center gap-2 px-4 py-2 rounded-lg border font-medium text-sm transition-all lg:col-span-2 ${
            showAdvanced
              ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
              : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:border-blue-400'
          }`}
        >
          <SlidersHorizontal className="w-4 h-4" />
          {showAdvanced ? 'Hide Advanced' : 'Advanced Filters'}
        </button>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
        <input
          type="text"
          placeholder={searchPlaceholder}
          value={searchQuery}
          onChange={(e) => onFilterChange('searchQuery', e.target.value)}
          className="w-full pl-10 pr-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      {/* Advanced Filters Panel */}
      {showAdvanced && (
        <div className="pt-4 border-t border-slate-200 dark:border-slate-700 space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Date Range */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                <Calendar className="w-4 h-4" />
                <span>{dateLabelPrefix} From</span>
              </label>
              <input
                type="date"
                value={dateFrom}
                onChange={(e) => onFilterChange('dateFrom', e.target.value)}
                className="w-full px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                <Calendar className="w-4 h-4" />
                <span>{dateLabelPrefix} To</span>
              </label>
              <input
                type="date"
                value={dateTo}
                onChange={(e) => onFilterChange('dateTo', e.target.value)}
                className="w-full px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {/* File Size Range */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                <HardDrive className="w-4 h-4" />
                <span>Min Size</span>
              </label>
              <input
                type="number"
                value={sizeMin}
                onChange={(e) => onFilterChange('sizeMin', e.target.value)}
                placeholder="1MB = 1048576"
                className="w-full px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                <HardDrive className="w-4 h-4" />
                <span>Max Size</span>
              </label>
              <input
                type="number"
                value={sizeMax}
                onChange={(e) => onFilterChange('sizeMax', e.target.value)}
                placeholder="10MB = 10485760"
                className="w-full px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        </div>
      )}

      {/* Active Filters Display */}
      {hasActiveFilters && (
        <div className="flex items-center gap-2 flex-wrap pt-2 border-t border-slate-200 dark:border-slate-700">
          <span className="text-xs text-slate-500 dark:text-slate-400">Active filters:</span>
          {platformFilter && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Platform: {formatPlatformName(platformFilter)}
              <button onClick={() => onFilterChange('platformFilter', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {sourceFilter && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Source: {sourceFilter}
              <button onClick={() => onFilterChange('sourceFilter', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {typeFilter !== 'all' && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Type: {typeFilter === 'image' ? 'Images' : 'Videos'}
              <button onClick={() => onFilterChange('typeFilter', 'all')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {faceRecognitionFilter && (
            <span className="text-xs px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-md flex items-center gap-1">
              Face: {faceRecognitionFilter === 'matched' ? 'Matched' : faceRecognitionFilter === 'no_match' ? 'No Match' : 'Not Scanned'}
              <button onClick={() => onFaceRecognitionChange?.('')} className="hover:text-green-900 dark:hover:text-green-100">×</button>
            </span>
          )}
          {deletedFromFilter && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Deleted From: {deletedFromFilter}
              <button onClick={() => onDeletedFromChange?.(null)} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {searchQuery && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Search: "{searchQuery}"
              <button onClick={() => onFilterChange('searchQuery', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {dateFrom && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              From: {dateFrom}
              <button onClick={() => onFilterChange('dateFrom', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {dateTo && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              To: {dateTo}
              <button onClick={() => onFilterChange('dateTo', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {sizeMin && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Min: {sizeMin} bytes
              <button onClick={() => onFilterChange('sizeMin', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
          {sizeMax && (
            <span className="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-md flex items-center gap-1">
              Max: {sizeMax} bytes
              <button onClick={() => onFilterChange('sizeMax', '')} className="hover:text-blue-900 dark:hover:text-blue-100">×</button>
            </span>
          )}
        </div>
      )}
    </div>
  )
}
