'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import * as motion from 'framer-motion/m'
import { AnimatePresence } from 'framer-motion'
import { Filter, ChevronDown, ChevronUp, RotateCcw, SlidersHorizontal, X } from 'lucide-react'

export interface FilterSection {
  id: string
  title: string
  content: React.ReactNode
  defaultExpanded?: boolean
}

interface FilterSidebarProps {
  sections: FilterSection[]
  activeFiltersCount: number
  onClearAll?: () => void
  title?: string
}

export default function FilterSidebar({ sections, activeFiltersCount, onClearAll, title: titleProp }: FilterSidebarProps) {
  const t = useTranslations('Filters')
  const title = titleProp ?? t('title')
  const [isMobileOpen, setIsMobileOpen] = useState(false)
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>(
    Object.fromEntries(sections.map(s => [s.id, s.defaultExpanded !== false]))
  )

  const toggleSection = (sectionId: string) => {
    setExpandedSections(prev => ({ ...prev, [sectionId]: !prev[sectionId] }))
  }

  return (
    <>
      {/* Mobile Filter Button */}
      <div className="md:hidden mb-4">
        <button
          onClick={() => setIsMobileOpen(true)}
          className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-primary text-white rounded-xl font-medium text-sm hover:shadow-md transition-all"
        >
          <SlidersHorizontal size={16} />
          {title}
          {activeFiltersCount > 0 && (
            <span className="ml-2 px-2 py-0.5 bg-white/20 text-white text-xs rounded-full">
              {activeFiltersCount}
            </span>
          )}
        </button>
      </div>

      {/* Desktop Sidebar */}
      <div className="hidden md:block w-72 shrink-0">
        <div className="sticky top-24 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          {/* Header */}
          <div className="p-4 border-b border-gray-100 bg-gray-50">
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-2">
                <Filter size={18} className="text-primary" />
                <span className="font-semibold text-dark">{title}</span>
                {activeFiltersCount > 0 && (
                  <span className="px-2 py-0.5 bg-primary/10 text-primary text-xs rounded-full font-medium">
                    {activeFiltersCount}
                  </span>
                )}
              </div>
              {activeFiltersCount > 0 && onClearAll && (
                <button
                  onClick={onClearAll}
                  className="flex items-center gap-1 text-xs text-gray-custom hover:text-primary transition-colors"
                >
                  <RotateCcw size={12} />
                  {t('clearAll')}
                </button>
              )}
            </div>
          </div>

          {/* Filter Sections */}
          {sections.map((section) => (
            <div key={section.id} className="border-b border-gray-100">
              <button
                onClick={() => toggleSection(section.id)}
                className="w-full flex justify-between items-center p-4 hover:bg-gray-50 transition-colors"
              >
                <span className="font-semibold text-dark">{section.title}</span>
                {expandedSections[section.id] ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
              </button>
              <AnimatePresence>
                {expandedSections[section.id] && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 'auto', opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    className="px-4 pb-4"
                  >
                    {section.content}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          ))}
        </div>
      </div>

      {/* Mobile Filter Modal */}
      <AnimatePresence>
        {isMobileOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black/50 z-50"
              onClick={() => setIsMobileOpen(false)}
            />
            <motion.div
              initial={{ y: '100%' }}
              animate={{ y: 0 }}
              exit={{ y: '100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 300 }}
              className="fixed bottom-0 left-0 right-0 bg-white rounded-t-2xl z-50 max-h-[85vh] overflow-y-auto"
            >
              <div className="sticky top-0 bg-white border-b border-gray-100 p-4 flex justify-between items-center">
                <div>
                  <h3 className="font-bold text-dark text-lg">{title}</h3>
                  {activeFiltersCount > 0 && (
                    <p className="text-xs text-gray-custom mt-0.5">{t('filtersApplied', { count: activeFiltersCount })}</p>
                  )}
                </div>
                <button onClick={() => setIsMobileOpen(false)} aria-label={t('close')} className="p-2 hover:bg-gray-100 rounded-full transition">
                  <X size={20} />
                </button>
              </div>

              <div className="p-4 space-y-6">
                {sections.map((section) => (
                  <div key={section.id}>
                    <h4 className="font-semibold text-dark mb-3">{section.title}</h4>
                    {section.content}
                  </div>
                ))}
              </div>

              <div className="sticky bottom-0 bg-white border-t border-gray-100 p-4 flex gap-3">
                {onClearAll && (
                  <button
                    onClick={onClearAll}
                    className="flex-1 border border-gray-200 text-dark py-3 rounded-lg font-medium hover:bg-gray-50 transition"
                  >
                    {t('clearAll')}
                  </button>
                )}
                <button
                  onClick={() => setIsMobileOpen(false)}
                  className="flex-1 bg-gradient-primary text-white py-3 rounded-lg font-medium hover:shadow-md transition"
                >
                  {t('applyFilters')}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  )
}