import { AutocompleteInput } from '@/component/TemplateManager/AutocompleteInput'
import { useCategoryContext } from '@/entity/template/model/CategoryContext'
import { Template } from '@/type/template'
import { Filter, X } from 'lucide-react'
import React, { useMemo } from 'react'
import { Button } from 'shared/ui/button'
import { Label } from 'shared/ui/label'
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarSeparator,
} from 'shared/ui/sidebar'

export interface TemplateFilters {
  name: string
  description: string
  attributes: { [attributeId: string]: string } // attributeId -> value для фильтрации
}

interface TemplateFilterSidebarProps {
  templates: Template[]
  filters: TemplateFilters
  onFiltersChange: (filters: TemplateFilters) => void
}

export const TemplateFilterSidebar: React.FC<TemplateFilterSidebarProps> = ({
  templates,
  filters,
  onFiltersChange,
}) => {
  const { attributes = [], isLoading: attributesLoading } = useCategoryContext()

  // Получаем уникальные значения для автокомплита
  const nameSuggestions = useMemo(() => {
    const names = templates.map(t => t.name).filter(Boolean)
    return [...new Set(names)].sort()
  }, [templates])

  const descriptionSuggestions = useMemo(() => {
    const descriptions = templates
      .map(t => t.description)
      .filter(Boolean) as string[]
    return [...new Set(descriptions)].sort()
  }, [templates])

  // Обработчики изменения фильтров
  const updateFilters = (updates: Partial<TemplateFilters>) => {
    onFiltersChange({ ...filters, ...updates })
  }

  const updateAttributeFilter = (attributeId: string, value: string) => {
    const newAttributes = { ...filters.attributes }
    if (value) {
      newAttributes[attributeId] = value
    } else {
      delete newAttributes[attributeId]
    }
    updateFilters({ attributes: newAttributes })
  }

  const clearAllFilters = () => {
    onFiltersChange({
      name: '',
      description: '',
      attributes: {},
    })
  }

  const hasActiveFilters =
    filters.name ||
    filters.description ||
    Object.keys(filters.attributes).length > 0

  const getAttributeName = (attributeId: string) => {
    const attribute = attributes.find(a => a.id === attributeId)
    return attribute?.name || 'Неизвестный атрибут'
  }

  return (
    <Sidebar>
      <SidebarHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Filter className="h-4 w-4" />
            <span className="font-semibold">Фильтры</span>
          </div>
          {hasActiveFilters && (
            <Button
              variant="ghost"
              size="sm"
              onClick={clearAllFilters}
              className="h-auto p-1 text-xs"
            >
              <X className="mr-1 h-3 w-3" />
              Очистить
            </Button>
          )}
        </div>
      </SidebarHeader>

      <SidebarContent>
        {/* Фильтр по названию */}
        <SidebarGroup>
          <Label className="text-sm font-medium">Поиск по названию</Label>
          <SidebarGroupContent>
            <AutocompleteInput
              label=""
              value={filters.name}
              onValueChange={value => updateFilters({ name: value })}
              suggestions={nameSuggestions}
            />
          </SidebarGroupContent>
        </SidebarGroup>

        <SidebarSeparator />

        {/* Активные фильтры по атрибутам */}
        {Object.keys(filters.attributes).length > 0 && (
          <>
            <SidebarGroup>
              <SidebarGroupLabel>Активные фильтры</SidebarGroupLabel>
              <SidebarGroupContent>
                <div className="space-y-2">
                  {Object.entries(filters.attributes).map(
                    ([attributeId, value]) => (
                      <div
                        key={attributeId}
                        className="flex items-center justify-between text-xs"
                      >
                        <span className="text-muted-foreground">
                          {getAttributeName(attributeId)}:
                        </span>
                        <div className="flex items-center gap-1">
                          <span className="font-medium">{value}</span>
                          <button
                            onClick={() =>
                              updateAttributeFilter(attributeId, '')
                            }
                            className="text-muted-foreground hover:text-foreground"
                          >
                            <X className="h-3 w-3" />
                          </button>
                        </div>
                      </div>
                    )
                  )}
                </div>
              </SidebarGroupContent>
            </SidebarGroup>
            <SidebarSeparator />
          </>
        )}

        {/* Фильтры по атрибутам */}
        {!attributesLoading && attributes.length > 0 && (
          <SidebarGroup>
            {/* <SidebarGroupLabel>Фильтры по атрибутам</SidebarGroupLabel> */}
            <SidebarGroupContent>
              <div className="space-y-3">
                {attributes.map(attribute => (
                  <div key={attribute.id}>
                    <AutocompleteInput
                      label={attribute.name}
                      value={filters.attributes[attribute.id] || ''}
                      onValueChange={value =>
                        updateAttributeFilter(attribute.id, value)
                      }
                      suggestions={[]} // Пока без автодополнения
                    />
                  </div>
                ))}
              </div>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {attributesLoading && (
          <SidebarGroup>
            <SidebarGroupLabel>Атрибуты</SidebarGroupLabel>
            <SidebarGroupContent>
              <div className="text-xs text-muted-foreground">
                Загрузка атрибутов...
              </div>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {!attributesLoading && attributes.length === 0 && (
          <SidebarGroup>
            <SidebarGroupLabel>Атрибуты</SidebarGroupLabel>
            <SidebarGroupContent>
              <div className="text-xs text-muted-foreground">
                Атрибуты не настроены
              </div>
            </SidebarGroupContent>
          </SidebarGroup>
        )}
      </SidebarContent>
    </Sidebar>
  )
}

export default TemplateFilterSidebar
