import { useEffect, useState } from 'react'
import type { SelectChangeEvent } from '@mui/material/Select'

export type UseProductFiltersResult = ReturnType<typeof useProductFilters>

export function useProductFilters() {
  const [categorySlug, setCategorySlug] = useState<string>('')
  const [qInput, setQInput] = useState('')
  const [q, setQ] = useState('')
  const [moreOpen, setMoreOpen] = useState(false)
  const [sort, setSort] = useState<'price_asc' | 'price_desc' | ''>('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(12)
  const [priceMinRub, setPriceMinRub] = useState('')
  const [priceMaxRub, setPriceMaxRub] = useState('')
  const [cardScale, setCardScale] = useState<70 | 90 | 110 | 130>(90)

  useEffect(() => {
    const t = window.setTimeout(() => {
      setQ(qInput.trim())
      setPage(1)
    }, 250)
    return () => window.clearTimeout(t)
  }, [qInput])

  const handleCategoryChange = (slug: string) => {
    setCategorySlug(slug)
    setPage(1)
  }

  const handleSortChange = (e: SelectChangeEvent<string>) => {
    const v = e.target.value
    if (v === '' || v === 'price_asc' || v === 'price_desc') {
      setSort(v)
      setPage(1)
    }
  }

  const handlePageSizeChange = (e: SelectChangeEvent<string>) => {
    const n = Number(e.target.value)
    if (Number.isFinite(n) && n > 0) {
      setPageSize(n)
      setPage(1)
    }
  }

  const handlePriceMinChange = (v: string) => {
    setPriceMinRub(v)
    setPage(1)
  }

  const handlePriceMaxChange = (v: string) => {
    setPriceMaxRub(v)
    setPage(1)
  }

  const handleCardScaleChange = (v: number) => {
    if (v === 70 || v === 90 || v === 110 || v === 130) setCardScale(v as 70 | 90 | 110 | 130)
  }

  const resetFilters = () => {
    setCategorySlug('')
    setQInput('')
    setSort('')
    setPriceMinRub('')
    setPriceMaxRub('')
    setPageSize(12)
    setCardScale(90)
    setMoreOpen(false)
  }

  const toCents = (v: string) => {
    const trimmed = String(v).trim()
    if (!trimmed) return undefined
    const n = Number(trimmed.replace(',', '.'))
    return Number.isFinite(n) && n >= 0 ? Math.round(n * 100) : undefined
  }

  return {
    categorySlug,
    qInput,
    q,
    moreOpen,
    sort,
    page,
    pageSize,
    priceMinRub,
    priceMaxRub,
    cardScale,
    setPage,
    setQInput,
    setMoreOpen,
    handleCategoryChange,
    handleSortChange,
    handlePageSizeChange,
    handlePriceMinChange,
    handlePriceMaxChange,
    handleCardScaleChange,
    resetFilters,
    toCents,
  }
}
