import React from 'react'
import { Filter, X, ChevronLeft, ChevronRight } from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuCheckboxItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { Button } from '../ui/buttonTsx'

/* =======================
   Types
======================= */

export interface FilterOption {
  value: string
  label: string
  color?: string
}

export interface FilterDefinition {
  key: string
  label: string
  options: FilterOption[]
}

export type ActiveFilters = Record<string, string[] | undefined>

interface AdvancedFiltersProps {
  filters?: FilterDefinition[]
  activeFilters?: ActiveFilters
  onFilterChange: (key: string, values?: string[]) => void
  onReset: () => void
  className?: string
}

/* =======================
   Component
======================= */

const AdvancedFilters: React.FC<AdvancedFiltersProps> = ({
  filters = [],
  activeFilters = {},
  onFilterChange,
  onReset,
  className,
}) => {
  const scrollContainerRef = React.useRef<HTMLDivElement>(null)
  const [showScrollButtons, setShowScrollButtons] = React.useState(false)
  const [canScrollLeft, setCanScrollLeft] = React.useState(false)
  const [canScrollRight, setCanScrollRight] = React.useState(false)

  const activeCount = Object.keys(activeFilters).filter(
    key => activeFilters[key]?.length
  ).length

  const handleFilterToggle = (key: string, value: string) => {
    const current = activeFilters[key] ?? []
    const next = current.includes(value)
      ? current.filter(v => v !== value)
      : [...current, value]
    onFilterChange(key, next.length > 0 ? next : undefined)
  }

  // Vérifier si le scroll est nécessaire
  const checkScroll = React.useCallback(() => {
    const container = scrollContainerRef.current
    if (!container) return

    const hasOverflow = container.scrollWidth > container.clientWidth
    setShowScrollButtons(hasOverflow)
    setCanScrollLeft(container.scrollLeft > 0)
    setCanScrollRight(
      container.scrollLeft < container.scrollWidth - container.clientWidth - 1
    )
  }, [])

  React.useEffect(() => {
    checkScroll()
    window.addEventListener('resize', checkScroll)
    return () => window.removeEventListener('resize', checkScroll)
  }, [checkScroll, activeFilters])

  const scroll = (direction: 'left' | 'right') => {
    const container = scrollContainerRef.current
    if (!container) return
    const scrollAmount = 150
    container.scrollBy({
      left: direction === 'left' ? -scrollAmount : scrollAmount,
      behavior: 'smooth',
    })
  }

  // Active filter badges
  const activeBadges = Object.entries(activeFilters)
    .filter(([, values]) => values && values.length > 0)
    .map(([key, values]) => {
      const filterDef = filters.find(f => f.key === key)
      if (!filterDef || !values) return null
      return { key, values, filterDef }
    })
    .filter(Boolean)

  return (
    <div className={cn('flex items-center gap-2 min-w-0', className)}>
      {/* Bouton Filtres */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="outline"
            className={cn(
              'gap-2 h-10 border-dashed shrink-0',
              activeCount > 0 &&
                'border-solid border-[#338660] bg-[#338660]/5 text-[#338660]'
            )}
          >
            <Filter className="w-4 h-4" />
            <span className="hidden sm:inline">Filtres</span>
            {activeCount > 0 && (
              <span className="rounded-full bg-[#338660] text-white w-5 h-5 text-[10px] flex items-center justify-center">
                {activeCount}
              </span>
            )}
          </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent
          align="start"
          className="w-64 bg-white dark:bg-gray-950 border-gray-200 dark:border-gray-800 max-h-[70vh] overflow-y-auto"
        >
          <DropdownMenuLabel>Filtres avancés</DropdownMenuLabel>
          <DropdownMenuSeparator />

          {filters.map(filter => {
            const maxVisible = 6
            const hasScroll = filter.options.length > maxVisible

            return (
              <div key={filter.key} className="px-1 py-1">
                <div className="px-2 py-1.5 text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center justify-between">
                  <span>{filter.label}</span>
                  {hasScroll && (
                    <span className="text-[10px] font-normal text-gray-400">
                      {filter.options.length} options
                    </span>
                  )}
                </div>

                <div
                  className={cn(
                    hasScroll && 'max-h-[192px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-transparent'
                  )}
                >
                  {filter.options.map(option => (
                    <DropdownMenuCheckboxItem
                      key={option.value}
                      checked={(activeFilters[filter.key] ?? []).includes(option.value)}
                      onCheckedChange={() => handleFilterToggle(filter.key, option.value)}
                      className="cursor-pointer"
                    >
                      <span
                        className={cn(
                          'w-2 h-2 rounded-full mr-2 shrink-0',
                          option.color ?? 'bg-gray-300'
                        )}
                      />
                      <span className="truncate">{option.label}</span>
                    </DropdownMenuCheckboxItem>
                  ))}
                </div>

                <DropdownMenuSeparator className="mt-1" />
              </div>
            )
          })}

          {activeCount > 0 && (
            <div className="p-2 sticky bottom-0 bg-white dark:bg-gray-950 border-t border-gray-100 dark:border-gray-800">
              <Button
                variant="ghost"
                size="sm"
                onClick={onReset}
                className="w-full h-8 text-xs text-[#007E45] hover:text-red-600 hover:bg-red-50"
              >
                Réinitialiser les filtres
              </Button>
            </div>
          )}
        </DropdownMenuContent>
      </DropdownMenu>

      {/* Container scrollable pour les badges */}
      {activeBadges.length > 0 && (
        <div className="relative flex items-center min-w-0 flex-1">
          {/* Bouton scroll gauche */}
          {showScrollButtons && canScrollLeft && (
            <button
              onClick={() => scroll('left')}
              className="absolute left-0 z-10 w-6 h-6 flex items-center justify-center bg-white dark:bg-gray-950 shadow-md rounded-full border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
            >
              <ChevronLeft className="w-3 h-3 text-gray-600 dark:text-gray-400" />
            </button>
          )}

          {/* Badges scrollables */}
          <div
            ref={scrollContainerRef}
            onScroll={checkScroll}
            className={cn(
              'flex items-center gap-2 overflow-x-auto scrollbar-hide scroll-smooth',
              showScrollButtons && canScrollLeft && 'pl-7',
              showScrollButtons && canScrollRight && 'pr-7'
            )}
            style={{
              scrollbarWidth: 'none',
              msOverflowStyle: 'none',
            }}
          >
            {activeBadges.map(badge => {
              if (!badge) return null
              const { key, values, filterDef } = badge

              return (
                <div
                  key={key}
                  className="flex items-center gap-1 bg-[#338660]/10 text-[#338660] px-2 py-1 rounded-md text-xs font-medium border border-[#338660]/20 whitespace-nowrap shrink-0"
                >
                  <span className="opacity-70">{filterDef.label}:</span>
                  <span className="max-w-[100px] truncate">
                    {values.length > 2
                      ? `${values.length} sélectionnés`
                      : values
                          .map(v => filterDef.options.find(o => o.value === v)?.label)
                          .join(', ')}
                  </span>
                  <button
                    onClick={() => onFilterChange(key, undefined)}
                    className="ml-1 hover:bg-[#338660]/20 rounded-full p-0.5 shrink-0"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </div>
              )
            })}
          </div>

          {/* Bouton scroll droite */}
          {showScrollButtons && canScrollRight && (
            <button
              onClick={() => scroll('right')}
              className="absolute right-0 z-10 w-6 h-6 flex items-center justify-center bg-white dark:bg-gray-950 shadow-md rounded-full border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
            >
              <ChevronRight className="w-3 h-3 text-gray-600 dark:text-gray-400" />
            </button>
          )}

          {/* Gradient fade effect */}
          {showScrollButtons && canScrollLeft && (
            <div className="absolute left-6 top-0 bottom-0 w-4 bg-gradient-to-r from-white dark:from-gray-950 to-transparent pointer-events-none" />
          )}
          {showScrollButtons && canScrollRight && (
            <div className="absolute right-6 top-0 bottom-0 w-4 bg-gradient-to-l from-white dark:from-gray-950 to-transparent pointer-events-none" />
          )}
        </div>
      )}

      {/* Bouton reset rapide (visible uniquement sur grand écran) */}
      {/* {activeCount > 0 && (
        <button
          onClick={onReset}
          className="hidden lg:flex items-center gap-1 text-xs text-gray-500 hover:text-red-600 transition-colors shrink-0"
        >
          <X className="w-3 h-3" />
          <span>Tout effacer</span>
        </button>
      )} */}
    </div>
  )
}

export default AdvancedFilters