'use client'

import { useState, useEffect, useMemo } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
  faFilter,
  faXmark,
  faMagnifyingGlass,
  faArrowDownWideShort,
  faTag,
  faBoxOpen,
  faCheck,
  faStar
} from '@fortawesome/free-solid-svg-icons'

const SORT_OPTIONS = [
  'پربازدیدترین',
  'جدیدترین',
  'گران‌ترین',
  'ارزان‌ترین',
  'تخفیف‌دار'
]

// تبدیل اعداد فارسی به انگلیسی
function toEn(num) {
  if (!num && num !== 0) return num;
  return num.toString().replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
}

export default function MobileFilterModal({
  category,
  availableBrands = [],
  availableMinPrice = 0,
  availableMaxPrice = 100000000,
  basePath = 'category'
}) {
  const router = useRouter()
  const searchParams = useSearchParams()

  const [isOpen, setIsOpen] = useState(false)
  const [inStock, setInStock] = useState(false)
  const [hasDiscount, setHasDiscount] = useState(false)
  const [isFeatured, setIsFeatured] = useState(false)
  const [minPrice, setMinPrice] = useState(availableMinPrice)
  const [maxPrice, setMaxPrice] = useState(availableMaxPrice)
  const [selectedBrands, setSelectedBrands] = useState([])
  const [selectedSort, setSelectedSort] = useState(1)
  const [brandSearch, setBrandSearch] = useState('')

  // همگام‌سازی با URL
  useEffect(() => {
    setInStock(searchParams.get('inStock') === 'true')
    setHasDiscount(searchParams.get('discount') === 'true')
    setIsFeatured(searchParams.get('isFeatured') === 'true')

    const urlMinPrice = searchParams.get('minPrice')
    const urlMaxPrice = searchParams.get('maxPrice')

    setMinPrice(urlMinPrice ? Number(urlMinPrice) : availableMinPrice)
    setMaxPrice(urlMaxPrice ? Number(urlMaxPrice) : availableMaxPrice)

    const brandsParam = searchParams.get('brands')
    if (brandsParam) {
      setSelectedBrands(brandsParam.split(','))
    } else {
      setSelectedBrands([])
    }

    const sortParam = searchParams.get('selectedSort')
    if (sortParam) {
      setSelectedSort(Number(sortParam))
    }
  }, [searchParams, availableMinPrice, availableMaxPrice])

  // قفل کردن اسکرول صفحه
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = 'unset'
    }
    return () => {
      document.body.style.overflow = 'unset'
    }
  }, [isOpen])

  // آماده‌سازی برندها
  const cleanBrands = useMemo(() => {
    const validBrands = availableBrands.filter(b => b)
    const unique = Array.from(new Set(validBrands))
    return unique.sort((a, b) => a.localeCompare(b, 'fa'))
  }, [availableBrands])

  const filteredBrands = useMemo(() => {
    if (!brandSearch) return cleanBrands
    const searchLower = brandSearch.toLowerCase()
    return cleanBrands.filter(b => b.toLowerCase().includes(searchLower))
  }, [cleanBrands, brandSearch])

  // محاسبه تعداد فیلترهای فعال
  const activeCount = useMemo(() => {
    let count = 0
    if (inStock) count++
    if (hasDiscount) count++
    if (isFeatured) count++
    if (minPrice > availableMinPrice || maxPrice < availableMaxPrice) count++
    if (selectedBrands.length > 0) count++
    return count
  }, [inStock, hasDiscount, isFeatured, minPrice, maxPrice, selectedBrands, availableMinPrice, availableMaxPrice])

  const handleBrandToggle = (brand) => {
    setSelectedBrands(prev =>
      prev.includes(brand)
        ? prev.filter(b => b !== brand)
        : [...prev, brand]
    )
  }

  // ساخت مسیر داینامیک بر اساس basePath
  const buildSortPath = (sortNum) => {
    if (!category) return ''
    const t = category.title.replace(/\s+/g, '-')
    return `/${basePath}/${t}/${category._id}/${sortNum}`
  }

  const applyFilters = () => {
    const params = new URLSearchParams(searchParams.toString())

    if (inStock) params.set('inStock', 'true')
    else params.delete('inStock')

    if (hasDiscount) params.set('discount', 'true')
    else params.delete('discount')

    if (isFeatured) params.set('isFeatured', 'true')
    else params.delete('isFeatured')

    if (minPrice > availableMinPrice) params.set('minPrice', minPrice.toString())
    else params.delete('minPrice')

    if (maxPrice < availableMaxPrice) params.set('maxPrice', maxPrice.toString())
    else params.delete('maxPrice')

    if (selectedBrands.length > 0) params.set('brands', selectedBrands.join(','))
    else params.delete('brands')

    params.set('selectedSort', selectedSort.toString())

    router.push(`${buildSortPath(selectedSort)}?${params.toString()}`, { scroll: false })
    setIsOpen(false)
  }

  const clearFilters = () => {
    setInStock(false)
    setHasDiscount(false)
    setIsFeatured(false)
    setMinPrice(availableMinPrice)
    setMaxPrice(availableMaxPrice)
    setSelectedBrands([])

    router.push(buildSortPath(selectedSort), { scroll: false })
    setIsOpen(false)
  }

  // توابع مدیریت ورودی‌های متنی قیمت
  const handleMinPriceInputChange = (e) => {
    const rawValue = toEn(e.target.value).replace(/,/g, '').replace(/\D/g, '');
    const val = rawValue ? parseInt(rawValue, 10) : availableMinPrice;
    setMinPrice(Math.min(val, availableMaxPrice));
  };

  const handleMaxPriceInputChange = (e) => {
    const rawValue = toEn(e.target.value).replace(/,/g, '').replace(/\D/g, '');
    const val = rawValue ? parseInt(rawValue, 10) : availableMinPrice;
    setMaxPrice(Math.min(val, availableMaxPrice));
  };

  const handlePriceInputBlur = () => {
    let newMin = minPrice;
    let newMax = maxPrice;

    if (newMin > newMax) {
      newMin = maxPrice;
      newMax = minPrice;
    }

    newMin = Math.max(availableMinPrice, Math.min(newMin, availableMaxPrice));
    newMax = Math.max(availableMinPrice, Math.min(newMax, availableMaxPrice));

    setMinPrice(newMin);
    setMaxPrice(newMax);
  };

  // محاسبه درصد برای نوار رنگی اسلایدر با در نظر گرفتن رنج داینامیک
  const safeMinPrice = Math.max(availableMinPrice, Math.min(minPrice, maxPrice));
  const safeMaxPrice = Math.min(availableMaxPrice, Math.max(minPrice, maxPrice));
  const priceRange = availableMaxPrice - availableMinPrice || 1;

  const minPercent = ((safeMinPrice - availableMinPrice) / priceRange) * 100;
  const maxPercent = ((safeMaxPrice - availableMinPrice) / priceRange) * 100;

  const stepValue = priceRange > 1000000 ? 100000 : (priceRange > 100000 ? 10000 : 1000);

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        aria-label={activeCount > 0 ? `فیلترها، ${activeCount} فیلتر فعال` : 'باز کردن فیلترها'}
        className={`group relative flex items-center gap-2.5 px-5 py-3 rounded-full font-bold text-sm active:scale-95 transition-all duration-200 focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-rose-200 ${
          activeCount > 0
            ? 'bg-gradient-to-l from-rose-500 to-rose-400 text-white shadow-[0_4px_20px_-6px_rgba(244,63,94,0.5)] border border-rose-400'
            : 'bg-white text-slate-700 shadow-[0_4px_20px_-8px_rgba(0,0,0,0.15)] border border-slate-200/70'
        }`}
      >
        <FontAwesomeIcon
          icon={faFilter}
          className={`text-xs ${activeCount > 0 ? 'text-white' : 'text-rose-500'}`}
        />
        فیلترها
        {activeCount > 0 && (
          <>
            <span className="bg-white text-rose-500 min-w-5 h-5 px-1 rounded-full flex items-center justify-center text-[11px] font-black shadow-sm">
              {activeCount}
            </span>
            <span className="absolute -top-1 -right-1 flex h-3 w-3">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75" />
              <span className="relative inline-flex rounded-full h-3 w-3 bg-rose-500" />
            </span>
          </>
        )}
      </button>

      {isOpen && (
        <div className="fixed inset-0 flex flex-col justify-end z-[9999]">
          <div
            className="absolute inset-0 bg-slate-950/50 backdrop-blur-md animate-[fadeIn_0.25s_ease-out]"
            onClick={() => setIsOpen(false)}
          />

          <div
            className="relative bg-white/95 backdrop-blur-2xl w-full h-[88vh] rounded-t-[2rem] shadow-[0_-10px_60px_-15px_rgba(0,0,0,0.3)] flex flex-col overflow-hidden animate-[slideUp_0.35s_cubic-bezier(0.16,1,0.3,1)]"
            dir="rtl"
          >
            {/* Grabber */}
            <div className="flex justify-center pt-3 pb-1 shrink-0">
              <div className="w-10 h-1.5 rounded-full bg-slate-200" />
            </div>

            {/* Header */}
            <div className="flex items-center justify-between px-5 pt-2 pb-4 border-b border-slate-100/80 shrink-0">
              <div className="flex flex-col gap-0.5">
                <h2 className="text-xl font-black text-slate-900 tracking-tight">فیلتر کالاها</h2>
                <span className="text-xs font-medium text-slate-400">
                  {activeCount > 0 ? `${activeCount} فیلتر فعال` : 'نتایج را دقیق‌تر کن'}
                </span>
              </div>
              <button
                onClick={() => setIsOpen(false)}
                className="w-11 h-11 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-slate-500 active:scale-90 transition-all duration-200"
              >
                <FontAwesomeIcon icon={faXmark} className="text-lg" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto px-5 py-6 space-y-9 [scrollbar-width:thin]">

              {/* Sort */}
              <section className="space-y-4">
                <h3 className="text-[13px] font-black text-slate-900 flex items-center gap-2 tracking-tight">
                  <span className="w-7 h-7 rounded-lg bg-rose-50 flex items-center justify-center">
                    <FontAwesomeIcon icon={faArrowDownWideShort} className="text-rose-500 text-xs" />
                  </span>
                  مرتب‌سازی
                </h3>
                <div className="flex flex-wrap gap-2">
                  {SORT_OPTIONS.map((opt, idx) => {
                    const sortNum = idx + 1
                    const isActive = selectedSort === sortNum
                    return (
                      <button
                        key={opt}
                        onClick={() => setSelectedSort(sortNum)}
                        className={`px-4 py-2.5 rounded-full text-[13px] font-bold border active:scale-95 transition-all duration-200 ${
                          isActive
                            ? 'border-rose-500 bg-rose-500 text-white shadow-md shadow-rose-200'
                            : 'border-slate-200 bg-white text-slate-600 hover:border-slate-300'
                        }`}
                      >
                        {opt}
                      </button>
                    )
                  })}
                </div>
              </section>

              {/* Toggles */}
              <section className="space-y-1 bg-slate-50/80 p-3 rounded-3xl border border-slate-100">
                <ToggleRow
                  icon={faBoxOpen}
                  color="text-emerald-500"
                  bg="bg-emerald-50"
                  label="فقط کالاهای موجود"
                  checked={inStock}
                  onChange={setInStock}
                />
                <ToggleRow
                  icon={faTag}
                  color="text-rose-500"
                  bg="bg-rose-50"
                  label="فقط تخفیف‌دار"
                  checked={hasDiscount}
                  onChange={setHasDiscount}
                />
                <ToggleRow
                  icon={faStar}
                  color="text-amber-500"
                  bg="bg-amber-50"
                  label="فقط کالاهای ویژه"
                  checked={isFeatured}
                  onChange={setIsFeatured}
                />
              </section>

              {/* Price Range */}
              <section className="space-y-6">
                <h3 className="text-[13px] font-black text-slate-900 tracking-tight">محدوده قیمت</h3>

                <div className="px-1" dir="rtl">
                  {/* Slider Container */}
                  <div className="relative h-1.5 bg-slate-100 rounded-full mt-8">
                    {/* Active Track */}
                    <div
                      className="absolute h-full bg-gradient-to-l from-rose-500 to-rose-400 rounded-full pointer-events-none"
                      style={{ right: `${minPercent}%`, left: `${100 - maxPercent}%` }}
                    />

                    <input
                      type="range"
                      min={availableMinPrice}
                      max={availableMaxPrice}
                      step={stepValue}
                      value={minPrice}
                      onChange={(e) => {
                        const val = Math.min(Number(e.target.value), maxPrice - stepValue)
                        setMinPrice(Math.max(val, availableMinPrice))
                      }}
                      className="absolute w-full -top-2 appearance-none bg-transparent pointer-events-none [&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:w-6 [&::-webkit-slider-thumb]:h-6 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:border-[3px] [&::-webkit-slider-thumb]:border-rose-500 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:shadow-[0_2px_8px_rgba(244,63,94,0.35)] [&::-webkit-slider-thumb]:cursor-grab [&::-webkit-slider-thumb]:active:cursor-grabbing [&::-webkit-slider-thumb]:transition-transform [&::-webkit-slider-thumb]:active:scale-110"
                    />

                    <input
                      type="range"
                      min={availableMinPrice}
                      max={availableMaxPrice}
                      step={stepValue}
                      value={maxPrice}
                      onChange={(e) => {
                        const val = Math.max(Number(e.target.value), minPrice + stepValue)
                        setMaxPrice(Math.min(val, availableMaxPrice))
                      }}
                      className="absolute w-full -top-2 appearance-none bg-transparent pointer-events-none [&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:w-6 [&::-webkit-slider-thumb]:h-6 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:border-[3px] [&::-webkit-slider-thumb]:border-rose-500 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:shadow-[0_2px_8px_rgba(244,63,94,0.35)] [&::-webkit-slider-thumb]:cursor-grab [&::-webkit-slider-thumb]:active:cursor-grabbing [&::-webkit-slider-thumb]:transition-transform [&::-webkit-slider-thumb]:active:scale-110"
                    />
                  </div>

                  {/* Manual Inputs with Commas */}
                  <div className="flex justify-between items-center mt-9 text-sm gap-3">
                    <div className="flex-1 flex flex-col gap-2 items-start text-slate-500">
                      <span className="text-[11px] font-bold px-1 text-slate-400">از قیمت</span>
                      <div className="w-full flex items-center bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-3 focus-within:border-rose-400 focus-within:bg-white focus-within:ring-4 focus-within:ring-rose-50 transition-all duration-200">
                        <input
                          type="text"
                          dir="ltr"
                          value={minPrice === 0 && availableMinPrice === 0 ? '' : minPrice.toLocaleString('en-US')}
                          onChange={handleMinPriceInputChange}
                          onBlur={handlePriceInputBlur}
                          placeholder={availableMinPrice.toLocaleString('en-US')}
                          className="w-full bg-transparent font-black text-slate-800 text-left outline-none placeholder:text-slate-300 placeholder:font-medium"
                        />
                        <span className="text-[11px] text-slate-400 mr-2 shrink-0 font-medium">تومان</span>
                      </div>
                    </div>

                    <div className="flex-1 flex flex-col gap-2 items-start text-slate-500">
                      <span className="text-[11px] font-bold px-1 text-slate-400">تا قیمت</span>
                      <div className="w-full flex items-center bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-3 focus-within:border-rose-400 focus-within:bg-white focus-within:ring-4 focus-within:ring-rose-50 transition-all duration-200">
                        <input
                          type="text"
                          dir="ltr"
                          value={maxPrice === 0 ? '' : maxPrice.toLocaleString('en-US')}
                          onChange={handleMaxPriceInputChange}
                          onBlur={handlePriceInputBlur}
                          placeholder={availableMaxPrice.toLocaleString('en-US')}
                          className="w-full bg-transparent font-black text-slate-800 text-left outline-none placeholder:text-slate-300 placeholder:font-medium"
                        />
                        <span className="text-[11px] text-slate-400 mr-2 shrink-0 font-medium">تومان</span>
                      </div>
                    </div>
                  </div>
                </div>
              </section>

              {/* Brands */}
              <section className="space-y-4">
                <h3 className="text-[13px] font-black text-slate-900 tracking-tight">برندها</h3>

                <div className="relative">
                  <input
                    type="text"
                    placeholder="جستجوی برند..."
                    value={brandSearch}
                    onChange={(e) => setBrandSearch(e.target.value)}
                    className="w-full bg-slate-50 border border-slate-200 rounded-2xl py-3.5 pr-12 pl-4 text-sm font-medium placeholder:text-slate-400 focus:outline-none focus:border-rose-400 focus:bg-white focus:ring-4 focus:ring-rose-50 transition-all duration-200"
                  />
                  <FontAwesomeIcon
                    icon={faMagnifyingGlass}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 text-sm"
                  />
                </div>

                <div className="max-h-56 overflow-y-auto space-y-1 -mx-1 px-1 [scrollbar-width:thin]">
                  {filteredBrands.map(brand => (
                    <label
                      key={brand}
                      className="flex items-center justify-between p-3.5 rounded-2xl hover:bg-slate-50 active:bg-slate-100 cursor-pointer transition-colors duration-150"
                    >
                      <span className="text-sm font-bold text-slate-700">{brand}</span>
                      <div className={`w-6 h-6 rounded-lg border flex items-center justify-center transition-all duration-200 ${
                        selectedBrands.includes(brand)
                          ? 'bg-rose-500 border-rose-500 scale-105'
                          : 'border-slate-300 bg-white'
                      }`}>
                        {selectedBrands.includes(brand) && (
                          <FontAwesomeIcon icon={faCheck} className="text-white text-[11px]" />
                        )}
                      </div>
                      <input
                        type="checkbox"
                        className="hidden"
                        checked={selectedBrands.includes(brand)}
                        onChange={() => handleBrandToggle(brand)}
                      />
                    </label>
                  ))}
                  {filteredBrands.length === 0 && (
                    <div className="text-center py-8 text-slate-400 text-sm font-medium">
                      برندی یافت نشد
                    </div>
                  )}
                </div>
              </section>

            </div>

            {/* Footer Actions */}
            <div className="px-5 py-4 border-t border-slate-100/80 flex gap-3 shrink-0 bg-white/80 backdrop-blur-xl">
              <button
                onClick={clearFilters}
                className="px-5 py-3.5 rounded-2xl font-bold text-sm text-slate-500 bg-slate-100 hover:bg-slate-200 active:scale-95 transition-all duration-200"
              >
                حذف فیلترها
              </button>
              <button
                onClick={applyFilters}
                className="flex-1 px-4 py-3.5 rounded-2xl font-black text-sm text-white bg-rose-500 hover:bg-rose-600 active:scale-[0.98] shadow-lg shadow-rose-200 flex justify-center items-center gap-2 transition-all duration-200"
              >
                مشاهده نتایج
                {activeCount > 0 && ` (${activeCount} فیلتر)`}
              </button>
            </div>

          </div>
        </div>
      )}

      <style jsx global>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes slideUp {
          from { transform: translateY(100%); }
          to { transform: translateY(0); }
        }
      `}</style>
    </>
  )
}

// کامپوننت ردیف‌های سوییچ با اینپوت مخفی
const ToggleRow = ({ icon, color, bg, label, checked, onChange }) => (
  <label className="flex items-center justify-between cursor-pointer group p-2.5 rounded-2xl hover:bg-white/60 transition-colors duration-150">
    <span className="flex items-center gap-3 text-sm font-bold text-slate-700">
      <div className={`w-9 h-9 rounded-xl ${bg || 'bg-slate-50'} flex items-center justify-center ${color} transition-transform duration-200 group-active:scale-90`}>
        <FontAwesomeIcon icon={icon} className="text-sm" />
      </div>
      {label}
    </span>
    <div className={`relative w-12 h-7 rounded-full transition-colors duration-300 ${checked ? 'bg-emerald-500 shadow-inner shadow-emerald-600/20' : 'bg-slate-200'}`}>
      <span className={`absolute top-1 w-5 h-5 bg-white rounded-full shadow-md transition-all duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] ${checked ? 'left-1' : 'left-6'}`} />
    </div>
    <input
      type="checkbox"
      className="hidden"
      checked={checked}
      onChange={(e) => onChange(e.target.checked)}
    />
  </label>
)
