'use client'

import * as React from 'react'
import { useState } from 'react'
import { useSticky } from '@/hooks/useSticky'
import { cn } from '@/lib/utils'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Chip } from '@/components/ui/chip'
import FilterDrawer, { FilterOptions } from './FilterDrawer'
import { useMainLayout } from '@/context/mainLayout'

interface Role {
  code?: string
  name?: string
  childDictList?: Tag[]
}

interface Tag {
  code?: string
  name?: string
}

interface MeetHeaderProps {
  selectedRole: string
  selectedTags: string[]
  roles: Role[]
  quickTags: Tag[]
  onRoleChange: (roleCode: string) => void
  onTagsChange: (tagCodes: string[]) => void
  onFilterClick: () => void
  filters?: FilterOptions
  onFiltersChange?: (filters: FilterOptions) => void
}

const MeetHeader = ({
  selectedRole,
  selectedTags,
  roles,
  quickTags,
  onRoleChange,
  onTagsChange,
  onFilterClick,
  filters = { gender: [], age: [], type: [] },
  onFiltersChange,
}: MeetHeaderProps) => {
  const [isFilterDrawerOpen, setIsFilterDrawerOpen] = useState(false)
  const { isSidebarExpanded } = useMainLayout()

  // 计算筛选器数量
  const filterCount =
    (filters.gender?.length || 0) + (filters.age?.length || 0) + (filters.type?.length || 0)

  // 使用 sticky hook 检测粘性状态
  const [stickyRef, isSticky] = useSticky<HTMLDivElement>({
    offset: 64, // offset 为 top-16 (64px)
    hysteresis: 15, // 增加滞后容差，避免边界抖动和快速滚动时的状态闪烁
  })

  // 计算左侧偏移量：侧边栏宽度
  const leftOffset = isSidebarExpanded ? 320 : 80 // w-80 = 320px, w-20 = 80px

  const handleRoleSelect = (roleCode: string) => {
    onRoleChange?.(roleCode)
  }

  const handleTagToggle = (tagCode: string) => {
    const newSelectedTags = selectedTags.includes(tagCode)
      ? selectedTags.filter((code) => code !== tagCode)
      : [...selectedTags, tagCode]

    onTagsChange?.(newSelectedTags)
  }

  const handleFilterClick = () => {
    setIsFilterDrawerOpen(true)
    onFilterClick?.()
  }

  const handleFiltersReset = () => {
    const resetFilters = { gender: [], age: [], type: [] }
    onFiltersChange?.(resetFilters)
  }

  const handleFiltersConfirm = () => {
    // 筛选确认逻辑可以在父组件处理
  }

  // 渲染筛选区域内容
  const renderFilterContent = () => (
    <div className="flex w-full flex-col gap-4">
      {/* 角色类型标签页和筛选按钮 */}
      <div className="flex w-full items-start justify-between gap-6">
        {/* 使用 Tabs 组件 */}
        <Tabs value={selectedRole} onValueChange={handleRoleSelect} className="flex-1">
          <TabsList className="h-auto justify-start overflow-x-auto rounded-none bg-transparent p-0">
            {/* ALL 选项 */}
            <TabsTrigger
              key="ALL"
              value="ALL"
              className={cn(
                'relative h-8 border-0 bg-transparent pr-3 shadow-none',
                'txt-title-s text-txt-secondary-normal',
                'data-[state=active]:text-txt-primary-normal',
                'data-[state=active]:bg-transparent',
                'data-[state=active]:shadow-none',
                'hover:text-txt-primary-normal',
                'focus-visible:ring-0 focus-visible:ring-offset-0',
                'flex cursor-pointer items-center justify-center'
              )}
            >
              <span className="whitespace-nowrap">All</span>
              {/* 活跃状态指示器 */}
              <div
                className={cn(
                  'bg-primary-normal absolute bottom-0 left-1/2 -ml-1.5 h-1 w-4 -translate-x-1/2 rounded-xs transition-opacity',
                  selectedRole === 'ALL' ? 'opacity-100' : 'opacity-0'
                )}
              />
            </TabsTrigger>
            {roles.map((role) => (
              <TabsTrigger
                key={role.code}
                value={role.code || ''}
                className={cn(
                  'relative h-8 border-0 bg-transparent pr-3 shadow-none',
                  'txt-title-s text-txt-secondary-normal',
                  'data-[state=active]:text-txt-primary-normal',
                  'data-[state=active]:bg-transparent',
                  'data-[state=active]:shadow-none',
                  'hover:text-txt-primary-normal',
                  'focus-visible:ring-0 focus-visible:ring-offset-0',
                  'flex cursor-pointer items-center justify-center'
                )}
              >
                <span className="whitespace-nowrap">{role.name}</span>
                {/* 活跃状态指示器 */}
                <div
                  className={cn(
                    'bg-primary-normal absolute bottom-0 left-1/2 -ml-1.5 h-1 w-4 -translate-x-1/2 rounded-xs transition-opacity',
                    selectedRole === role.code ? 'opacity-100' : 'opacity-0'
                  )}
                />
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>

        {/* Filter 按钮 */}
        <Chip className="px-4" onClick={handleFilterClick}>
          <div className="flex items-center gap-1">
            <i className="iconfont icon-filter-fill" />
            <div className="txt-label-m">
              {filterCount > 0 ? `Filter(${filterCount})` : 'Filter'}
            </div>
          </div>
        </Chip>
      </div>

      {/* 快速筛选标签 */}
      <div className="flex flex-wrap items-start justify-start gap-2">
        {quickTags.map((tag) => (
          <Chip
            key={tag.code}
            size="small"
            className="px-4"
            state={selectedTags.includes(tag.code || '') ? 'active' : 'inactive'}
            onClick={() => handleTagToggle(tag.code || '')}
          >
            #{tag.name}
          </Chip>
        ))}
      </div>
    </div>
  )

  return (
    <>
      {/* 原始容器 - 用于检测 sticky 触发点 */}
      <div ref={stickyRef} className="mt-12 w-full">
        {/* 占位元素 - 当 fixed 时保持布局不跳动 */}
        {isSticky && <div className="w-full py-6" style={{ height: '104px' }} />}

        {!isSticky && (
          <div className="w-full py-6">
            <div className="w-full">
              {/* Meet 标题 */}
              <h1 className="txt-title-l text-txt-primary-normal mb-6">🔮 More Characters</h1>

              {/* 筛选区域 */}
              {renderFilterContent()}
            </div>
          </div>
        )}
      </div>

      {/* Fixed 定位的筛选栏 - sticky 时显示 */}
      {isSticky && (
        <div
          className="border-outline-normal fixed top-16 right-0 z-50 border-b py-6 backdrop-blur-[10px] transition-opacity duration-200 ease-in-out"
          style={{
            left: `${leftOffset}px`,
            right: 0,
            opacity: isSticky ? 1 : 0,
            willChange: 'opacity',
          }}
        >
          {/* 半透明背景 */}
          <div className="bg-background-default absolute inset-0 opacity-85" />

          {/* 内容区域 - 与 HomePage 保持一致的 padding 和 max-width */}
          <div className="relative px-16">
            <div className="mx-auto max-w-[1136px]">{renderFilterContent()}</div>
          </div>
        </div>
      )}

      {/* 筛选抽屉 */}
      <FilterDrawer
        open={isFilterDrawerOpen}
        onOpenChange={setIsFilterDrawerOpen}
        filters={filters}
        onFiltersChange={onFiltersChange || (() => {})}
        onReset={handleFiltersReset}
        onConfirm={handleFiltersConfirm}
      />
    </>
  )
}

export default MeetHeader
