import { useCallback, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { api } from '../api/client'
import {
  BRAND_CHANGED_EVENT,
  getActiveBrandId,
  rememberBrandId,
} from '../lib/brandContext'
import type { BrandData, ListBrandsData } from '../types/brand'

export function useActiveBrand() {
  const [searchParams, setSearchParams] = useSearchParams()
  const [brandId, setBrandIdState] = useState('')
  const [brands, setBrands] = useState<BrandData[]>([])
  const [brand, setBrand] = useState<BrandData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const resolveBrandId = useCallback(
    (list: BrandData[]) => {
      const fromQuery = searchParams.get('brand')?.trim() ?? ''
      if (fromQuery) return fromQuery
      const stored = getActiveBrandId()
      if (stored && list.some((item) => item.id === stored)) return stored
      return list[0]?.id ?? ''
    },
    [searchParams],
  )

  const load = useCallback(async () => {
    setLoading(true)
    setError('')
    try {
      const data = await api.get<ListBrandsData>('/api/v1/brands/', { auth: true })
      const list = data.list ?? []
      setBrands(list)
      const resolved = resolveBrandId(list)
      setBrandIdState(resolved)
      if (resolved) {
        rememberBrandId(resolved)
        const found = list.find((item) => item.id === resolved)
        if (found) {
          setBrand(found)
        } else {
          const detail = await api.get<BrandData>(`/api/v1/brands/${encodeURIComponent(resolved)}`, {
            auth: true,
          })
          setBrand(detail)
        }
      } else {
        setBrand(null)
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : '載入品牌失敗')
      setBrands([])
      setBrand(null)
      setBrandIdState('')
    } finally {
      setLoading(false)
    }
  }, [resolveBrandId])

  useEffect(() => {
    void load()
  }, [load])

  useEffect(() => {
    const onBrandChanged = (event: Event) => {
      const id = (event as CustomEvent<{ id: string }>).detail?.id?.trim() ?? ''
      if (id) setBrandIdState(id)
    }
    window.addEventListener(BRAND_CHANGED_EVENT, onBrandChanged)
    return () => window.removeEventListener(BRAND_CHANGED_EVENT, onBrandChanged)
  }, [])

  useEffect(() => {
    if (!brandId) {
      setBrand(null)
      return
    }
    const found = brands.find((item) => item.id === brandId)
    if (found) {
      setBrand(found)
      return
    }
    void api
      .get<BrandData>(`/api/v1/brands/${encodeURIComponent(brandId)}`, { auth: true })
      .then(setBrand)
      .catch(() => setBrand(null))
  }, [brandId, brands])

  const setBrandId = useCallback(
    (id: string) => {
      const next = id.trim()
      if (!next) return
      rememberBrandId(next)
      setBrandIdState(next)
      const found = brands.find((item) => item.id === next)
      if (found) setBrand(found)
      const params = new URLSearchParams(searchParams)
      params.set('brand', next)
      setSearchParams(params, { replace: true })
    },
    [brands, searchParams, setSearchParams],
  )

  return { brandId, brand, brands, setBrandId, loading, error, reload: load }
}