'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import { ExternalDataState, ExternalDataAction } from './externalDataReducer';
import { dataSourceTypes, dataSourceStatuses } from '../types';
import { Search, Filter, X } from 'lucide-react';

interface FilterPanelProps {
  state: ExternalDataState;
  dispatch: React.Dispatch<ExternalDataAction>;
}

export function FilterPanel({ state, dispatch }: FilterPanelProps) {
  const [isExpanded, setIsExpanded] = useState(false);

  const uniqueProviders = Array.from(new Set(state.dataSources.map(ds => ds.provider)));

  const handleFilterChange = (key: keyof ExternalDataState['filters'], value: any) => {
    dispatch({ type: 'UPDATE_FILTER', payload: { key, value } });
  };

  const handleToggleFilter = (filterType: 'type' | 'status' | 'provider', value: string) => {
    dispatch({ type: 'TOGGLE_ARRAY_FILTER', payload: { key: filterType, value } });
  };

  const clearAllFilters = () => {
    dispatch({ type: 'CLEAR_FILTERS' });
  };

  const hasActiveFilters = Object.values(state.filters).some(
    value => Array.isArray(value) ? value.length > 0 : value !== ''
  );

  const activeFilterCount = Object.values(state.filters).reduce(
    (count, value) => count + (Array.isArray(value) ? value.length : (value ? 1 : 0)),
    0
  );

  return (
    <Card className="bg-card border-border">
      <div className="p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-muted-foreground" />
            <h3 className="font-medium">筛选条件</h3>
            {hasActiveFilters && (
              <Badge variant="secondary" className="ml-2">
                {activeFilterCount}
              </Badge>
            )}
          </div>
          <div className="flex items-center gap-2">
            {hasActiveFilters && (
              <Button
                variant="ghost"
                size="sm"
                onClick={clearAllFilters}
                className="text-muted-foreground hover:text-foreground"
              >
                <X className="w-4 h-4 mr-1" />
                清除
              </Button>
            )}
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(!isExpanded)}
            >
              {isExpanded ? '收起' : '展开'}
            </Button>
          </div>
        </div>

        {/* 搜索框 */}
        <div className="relative mb-4">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="搜索数据源名称、提供商..."
            value={state.filters.searchTerm}
            onChange={(e) => handleFilterChange('searchTerm', e.target.value)}
            className="pl-10"
          />
        </div>

        {isExpanded && (
          <div className="space-y-4">
            {/* 数据类型筛选 */}
            <div>
              <Label className="text-sm font-medium mb-2 block">数据类型</Label>
              <div className="flex flex-wrap gap-2">
                {dataSourceTypes.map((type) => (
                  <Badge
                    key={type.key}
                    variant={state.filters.type.includes(type.key) ? 'default' : 'outline'}
                    className="cursor-pointer font-light"
                    style={{
                      backgroundColor: state.filters.type.includes(type.key) ? type.color : 'transparent',
                      borderColor: type.color,
                      color: state.filters.type.includes(type.key) ? 'white' : type.color,
                    }}
                    onClick={() => handleToggleFilter('type', type.key)}
                  >
                    {type.name}
                  </Badge>
                ))}
              </div>
            </div>

            {/* 状态筛选 */}
            <div>
              <Label className="text-sm font-medium mb-2 block">状态</Label>
              <div className="flex flex-wrap gap-2">
                {dataSourceStatuses.map((status) => (
                  <Badge
                    key={status.key}
                    variant={state.filters.status.includes(status.key) ? 'default' : 'outline'}
                    className="cursor-pointer font-light"
                    style={{
                      backgroundColor: state.filters.status.includes(status.key) ? status.color : 'transparent',
                      borderColor: status.color,
                      color: state.filters.status.includes(status.key) ? 'white' : status.color,
                    }}
                    onClick={() => handleToggleFilter('status', status.key)}
                  >
                    {status.name}
                  </Badge>
                ))}
              </div>
            </div>

            {/* 提供商筛选 */}
            {uniqueProviders.length > 0 && (
              <div>
                <Label className="text-sm font-medium mb-2 block">数据提供商</Label>
                <div className="flex flex-wrap gap-2">
                  {uniqueProviders.map((provider) => (
                    <Badge
                      key={provider}
                      variant={state.filters.provider.includes(provider) ? 'default' : 'outline'}
                      className="cursor-pointer font-light"
                      style={{
                        backgroundColor: state.filters.provider.includes(provider) ? '#3b82f6' : 'transparent',
                        borderColor: '#3b82f6',
                        color: state.filters.provider.includes(provider) ? 'white' : '#3b82f6',
                      }}
                      onClick={() => handleToggleFilter('provider', provider)}
                    >
                      {provider}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </Card>
  );
}