'use client'

import { useState, useEffect } from "react"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { Settings2, Filter, X, Search, ChevronDown, ChevronUp, Loader2, Plus, Pin, GripVertical } from "lucide-react"
import { useFilterStore } from "@/store/filter-store"
import { DEFAULT_FILTER_SETTINGS } from "@/types/filter.types"
import { TRAIT_CATEGORY_LIST as TRAIT_CATEGORIES, TRAIT_DESCRIPTIONS, TRAIT_DISPLAY_NAMES } from "@/constants/traits"
import { geneApi } from "@/lib/api/gene.api"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from '@dnd-kit/core'
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'

// 드래그 가능한 유전자 아이템 컴포넌트
function SortableGeneItem({
  id,
  isPinned,
  onTogglePin,
  onRemove,
}: {
  id: string
  isPinned: boolean
  onTogglePin: () => void
  onRemove: () => void
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`flex items-center gap-2 p-2 rounded-lg border ${isPinned ? 'bg-amber-50 border-amber-200' : 'bg-white border-slate-200'}`}
    >
      <button
        {...attributes}
        {...listeners}
        className="cursor-grab active:cursor-grabbing p-1 hover:bg-slate-100 rounded"
      >
        <GripVertical className="w-4 h-4 text-slate-400" />
      </button>
      {isPinned && <Pin className="w-3 h-3 text-amber-500" fill="currentColor" />}
      <span className="font-medium text-sm flex-1">{id}</span>
      <button
        onClick={onTogglePin}
        className={`p-1 rounded hover:bg-slate-100 ${isPinned ? 'text-amber-500' : 'text-slate-400'}`}
        title={isPinned ? '고정 해제' : '고정'}
      >
        <Pin className="w-4 h-4" fill={isPinned ? 'currentColor' : 'none'} />
      </button>
      <button
        onClick={onRemove}
        className="p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-red-500"
      >
        <X className="w-4 h-4" />
      </button>
    </div>
  )
}

// 드래그 가능한 형질 아이템 컴포넌트
function SortableTraitItem({
  id,
  isPinned,
  weight,
  onTogglePin,
  onRemove,
  onWeightChange,
}: {
  id: string
  isPinned: boolean
  weight: number
  onTogglePin: () => void
  onRemove: () => void
  onWeightChange: (delta: number) => void
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`flex items-center gap-2 p-2 rounded-lg border ${isPinned ? 'bg-amber-50 border-amber-200' : 'bg-white border-slate-200'}`}
    >
      <button
        {...attributes}
        {...listeners}
        className="cursor-grab active:cursor-grabbing p-1 hover:bg-slate-100 rounded"
      >
        <GripVertical className="w-4 h-4 text-slate-400" />
      </button>
      {isPinned && <Pin className="w-3 h-3 text-amber-500" fill="currentColor" />}
      <span className="font-medium text-sm min-w-0 truncate">{TRAIT_DISPLAY_NAMES[id] || id}</span>
      <div className="flex items-center gap-1.5 ml-auto">
        <Button
          variant="outline"
          size="sm"
          className="h-6 w-6 p-0"
          onClick={() => onWeightChange(-1)}
          disabled={weight <= 1}
        >
          -
        </Button>
        <span className="text-xs font-bold w-8 text-center">{weight}점</span>
        <Button
          variant="outline"
          size="sm"
          className="h-6 w-6 p-0"
          onClick={() => onWeightChange(1)}
          disabled={weight >= 10}
        >
          +
        </Button>
      </div>
      <button
        onClick={onTogglePin}
        className={`p-1 rounded hover:bg-slate-100 ${isPinned ? 'text-amber-500' : 'text-slate-400'}`}
        title={isPinned ? '고정 해제' : '고정'}
      >
        <Pin className="w-4 h-4" fill={isPinned ? 'currentColor' : 'none'} />
      </button>
      <button
        onClick={onRemove}
        className="p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-red-500"
      >
        <X className="w-4 h-4" />
      </button>
    </div>
  )
}

type TraitName = keyof typeof DEFAULT_FILTER_SETTINGS.traitWeights

interface GlobalFilterDialogProps {
  externalOpen?: boolean
  onExternalOpenChange?: (open: boolean) => void
  geneCount?: number
  traitCount?: number
}

export function GlobalFilterDialog({ externalOpen, onExternalOpenChange, geneCount = 0, traitCount = 0 }: GlobalFilterDialogProps = {}) {
  const { filters, updateFilters, resetFilters } = useFilterStore()
  const [internalOpen, setInternalOpen] = useState(false)

  const open = externalOpen !== undefined ? externalOpen : internalOpen
  const setOpen = onExternalOpenChange || setInternalOpen

  // 모달 상태
  const [showGeneModal, setShowGeneModal] = useState(false)
  const [showTraitModal, setShowTraitModal] = useState(false)
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')

  // 카테고리 열림/닫힘 상태
  const [openCategories, setOpenCategories] = useState<Record<string, boolean>>({})

  // DB에서 가져온 유전자 목록
  const [quantityGenes, setQuantityGenes] = useState<any[]>([])
  const [qualityGenes, setQualityGenes] = useState<any[]>([])
  const [loadingGenes, setLoadingGenes] = useState(false)

  // 로컬 상태
  const [localFilters, setLocalFilters] = useState({
    ...DEFAULT_FILTER_SETTINGS,
    ...filters,
  })

  useEffect(() => {
    if (open) {
      setLocalFilters({
        ...DEFAULT_FILTER_SETTINGS,
        ...filters,
      })
      loadAllGenes()
      setGeneSearch('')
      setTraitSearch('')
      setOpenCategories({})
    }
  }, [open, filters])

  // 전체 유전자 로드
  // TODO: 백엔드 /gene/markers API 구현 후 활성화
  const loadAllGenes = async () => {
    // try {
    //   setLoadingGenes(true)
    //   const [qtyGenes, qltGenes] = await Promise.all([
    //     geneApi.getGenesByType('QTY'),
    //     geneApi.getGenesByType('QLT'),
    //   ])
    //   setQuantityGenes(qtyGenes)
    //   setQualityGenes(qltGenes)
    // } catch {
    //   setQuantityGenes([])
    //   setQualityGenes([])
    // } finally {
    //   setLoadingGenes(false)
    // }
  }

  // 필터 활성화 여부
  const isFilterActive = (filterSettings: typeof localFilters) => {
    const hasSelectedGenes = filterSettings.selectedGenes.length > 0
    const hasCustomWeights = Object.values(filterSettings.traitWeights).some(weight => weight > 0)
    return hasSelectedGenes || hasCustomWeights
  }

  // 필터 적용
  const handleApply = () => {
    const updatedFilters = {
      ...localFilters,
      isActive: isFilterActive(localFilters)
    }
    updateFilters(updatedFilters)
    setOpen(false)
  }

  // 필터 리셋
  const handleReset = () => {
    resetFilters()
    setLocalFilters(DEFAULT_FILTER_SETTINGS)
  }

  // 유전자 토글
  const toggleGene = (markerNm: string) => {
    setLocalFilters(prev => ({
      ...prev,
      selectedGenes: prev.selectedGenes.includes(markerNm)
        ? prev.selectedGenes.filter(g => g !== markerNm)
        : [...prev.selectedGenes, markerNm],
      pinnedGenes: prev.selectedGenes.includes(markerNm)
        ? prev.pinnedGenes?.filter(g => g !== markerNm) || []
        : prev.pinnedGenes
    }))
  }

  // 유전자 고정 토글 (고정 시 고정된 항목들 맨 아래로 이동)
  const toggleGenePin = (markerNm: string) => {
    setLocalFilters(prev => {
      const pinnedGenes = prev.pinnedGenes || []
      if (pinnedGenes.includes(markerNm)) {
        // 고정 해제
        return { ...prev, pinnedGenes: pinnedGenes.filter(g => g !== markerNm) }
      } else {
        // 고정 + 고정된 항목들 중 맨 아래로 이동
        const newPinnedGenes = [...pinnedGenes, markerNm]
        const unpinnedGenes = prev.selectedGenes.filter(g => !newPinnedGenes.includes(g))
        const pinnedInOrder = prev.selectedGenes.filter(g => pinnedGenes.includes(g))
        const newSelectedGenes = [...pinnedInOrder, markerNm, ...unpinnedGenes]
        return {
          ...prev,
          pinnedGenes: newPinnedGenes,
          selectedGenes: newSelectedGenes
        }
      }
    })
  }

  // 형질 토글
  const toggleTrait = (traitName: string) => {
    setLocalFilters(prev => {
      const selectedTraits = prev.selectedTraits || []
      const traitWeights = { ...prev.traitWeights }

      if (selectedTraits.includes(traitName)) {
        // 제거
        traitWeights[traitName as TraitName] = 0
        return {
          ...prev,
          selectedTraits: selectedTraits.filter(t => t !== traitName),
          pinnedTraits: prev.pinnedTraits?.filter(t => t !== traitName) || [],
          traitWeights
        }
      } else {
        // 추가
        traitWeights[traitName as TraitName] = 5
        return {
          ...prev,
          selectedTraits: [...selectedTraits, traitName],
          traitWeights
        }
      }
    })
  }

  // 형질 고정 토글 (고정 시 고정된 항목들 맨 아래로 이동)
  const toggleTraitPin = (traitName: string) => {
    setLocalFilters(prev => {
      const pinnedTraits = prev.pinnedTraits || []
      const selectedTraits = prev.selectedTraits || []
      if (pinnedTraits.includes(traitName)) {
        // 고정 해제
        return { ...prev, pinnedTraits: pinnedTraits.filter(t => t !== traitName) }
      } else {
        // 고정 + 고정된 항목들 중 맨 아래로 이동
        const newPinnedTraits = [...pinnedTraits, traitName]
        const unpinnedTraits = selectedTraits.filter(t => !newPinnedTraits.includes(t))
        const pinnedInOrder = selectedTraits.filter(t => pinnedTraits.includes(t))
        const newSelectedTraits = [...pinnedInOrder, traitName, ...unpinnedTraits]
        return {
          ...prev,
          pinnedTraits: newPinnedTraits,
          selectedTraits: newSelectedTraits
        }
      }
    })
  }

  // 가중치 변경 (1~10 범위)
  const updateTraitWeight = (traitName: string, delta: number) => {
    setLocalFilters(prev => {
      const current = prev.traitWeights[traitName as TraitName] || 1
      const newValue = Math.min(10, Math.max(1, current + delta))
      return {
        ...prev,
        traitWeights: { ...prev.traitWeights, [traitName]: newValue }
      }
    })
  }

  // 카테고리 전체 선택/해제
  const toggleCategoryGenes = (genes: any[], select: boolean) => {
    setLocalFilters(prev => {
      if (select) {
        const newGenes = [...prev.selectedGenes]
        genes.forEach(g => {
          if (!newGenes.includes(g.markerNm)) newGenes.push(g.markerNm)
        })
        return { ...prev, selectedGenes: newGenes }
      } else {
        return {
          ...prev,
          selectedGenes: prev.selectedGenes.filter(id => !genes.some(g => g.markerNm === id)),
          pinnedGenes: prev.pinnedGenes?.filter(id => !genes.some(g => g.markerNm === id)) || []
        }
      }
    })
  }

  const toggleCategoryTraits = (traits: string[], select: boolean) => {
    setLocalFilters(prev => {
      const newWeights = { ...prev.traitWeights }
      let newSelectedTraits = [...(prev.selectedTraits || [])]

      if (select) {
        traits.forEach(t => {
          if (!newSelectedTraits.includes(t)) {
            newSelectedTraits.push(t)
            newWeights[t as TraitName] = 5
          }
        })
      } else {
        traits.forEach(t => {
          newWeights[t as TraitName] = 0
        })
        newSelectedTraits = newSelectedTraits.filter(t => !traits.includes(t))
      }

      return {
        ...prev,
        selectedTraits: newSelectedTraits,
        traitWeights: newWeights,
        pinnedTraits: select ? prev.pinnedTraits : prev.pinnedTraits?.filter(t => !traits.includes(t)) || []
      }
    })
  }

  // 드래그 앤 드롭 센서
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  )

  // 유전자 순서 변경
  const handleGeneDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    if (over && active.id !== over.id) {
      setLocalFilters(prev => {
        const oldIndex = prev.selectedGenes.indexOf(active.id as string)
        const newIndex = prev.selectedGenes.indexOf(over.id as string)
        return {
          ...prev,
          selectedGenes: arrayMove(prev.selectedGenes, oldIndex, newIndex)
        }
      })
    }
  }

  // 형질 순서 변경
  const handleTraitDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    if (over && active.id !== over.id) {
      setLocalFilters(prev => {
        const selectedTraits = prev.selectedTraits || []
        const oldIndex = selectedTraits.indexOf(active.id as string)
        const newIndex = selectedTraits.indexOf(over.id as string)
        return {
          ...prev,
          selectedTraits: arrayMove(selectedTraits, oldIndex, newIndex)
        }
      })
    }
  }

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>
        <Button
          variant={(geneCount > 0 || traitCount > 0) ? "default" : "outline"}
          size="sm"
          data-filter-button
          className="h-8 md:h-9 text-xs md:text-base font-semibold px-2 md:px-3 relative"
        >
          <Settings2 className="h-3 w-3 md:h-4 md:w-4 mr-1 md:mr-1.5" />
          <span>필터 ({traitCount})</span>
        </Button>
      </SheetTrigger>

      <SheetContent side="right" className="w-full sm:w-[400px] p-0 gap-0 flex flex-col overflow-hidden">
        {/* 헤더 */}
        <div className="px-4 pt-4 pb-3 border-b flex-shrink-0">
          <SheetHeader>
            <SheetTitle className="flex items-center gap-2 text-lg">
              <Filter className="h-5 w-5 text-primary" />
              전역 필터 설정
            </SheetTitle>
            <SheetDescription className="text-sm">
              유전자와 형질을 선택하세요
            </SheetDescription>
          </SheetHeader>
        </div>

        {/* 메인 콘텐츠 */}
        <ScrollArea className="flex-1 overflow-y-auto">
          <div className="p-4 space-y-4">
            {/* 유전자 선택 버튼 */}
            <div className="space-y-2">
              <div className="text-sm font-medium">유전자</div>
              <button
                onClick={() => setShowGeneModal(true)}
                className="w-full p-3 border-2 border-dashed border-slate-300 rounded-lg text-slate-500 hover:border-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors flex items-center justify-center gap-2"
              >
                <Plus className="w-4 h-4" />
                {localFilters.selectedGenes.length > 0
                  ? `유전자 수정 (${localFilters.selectedGenes.length}개 선택됨)`
                  : '유전자를 선택해주세요'}
              </button>
            </div>

            {/* 형질 선택 버튼 */}
            <div className="space-y-2">
              <div className="text-sm font-medium">유전체 형질</div>
              <button
                onClick={() => setShowTraitModal(true)}
                className="w-full p-3 border-2 border-dashed border-slate-300 rounded-lg text-slate-500 hover:border-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors flex items-center justify-center gap-2"
              >
                <Plus className="w-4 h-4" />
                {(localFilters.selectedTraits?.length || 0) > 0
                  ? `형질 수정 (${localFilters.selectedTraits?.length}개 선택됨)`
                  : '형질을 선택해주세요'}
              </button>
            </div>

            {/* 선택한 조건 표시 */}
            {(localFilters.selectedGenes.length > 0 || (localFilters.selectedTraits?.length || 0) > 0) && (
              <div className="p-4 bg-slate-50 rounded-xl border space-y-4">
                <h4 className="font-semibold text-foreground">
                  선택한 조건 ({localFilters.selectedGenes.length + (localFilters.selectedTraits?.length || 0)}개)
                </h4>

                {/* 유전자 */}
                {localFilters.selectedGenes.length > 0 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">유전자</div>
                    <DndContext
                      sensors={sensors}
                      collisionDetection={closestCenter}
                      onDragEnd={handleGeneDragEnd}
                    >
                      <SortableContext
                        items={localFilters.selectedGenes}
                        strategy={verticalListSortingStrategy}
                      >
                        <div className="space-y-1">
                          {localFilters.selectedGenes.map(geneId => (
                            <SortableGeneItem
                              key={geneId}
                              id={geneId}
                              isPinned={localFilters.pinnedGenes?.includes(geneId) || false}
                              onTogglePin={() => toggleGenePin(geneId)}
                              onRemove={() => toggleGene(geneId)}
                            />
                          ))}
                        </div>
                      </SortableContext>
                    </DndContext>
                  </div>
                )}

                {/* 형질 */}
                {(localFilters.selectedTraits?.length || 0) > 0 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">유전체 형질</div>
                    <DndContext
                      sensors={sensors}
                      collisionDetection={closestCenter}
                      onDragEnd={handleTraitDragEnd}
                    >
                      <SortableContext
                        items={localFilters.selectedTraits || []}
                        strategy={verticalListSortingStrategy}
                      >
                        <div className="space-y-1">
                          {(localFilters.selectedTraits || []).map(traitId => (
                            <SortableTraitItem
                              key={traitId}
                              id={traitId}
                              isPinned={localFilters.pinnedTraits?.includes(traitId) || false}
                              weight={localFilters.traitWeights[traitId as TraitName] || 0}
                              onTogglePin={() => toggleTraitPin(traitId)}
                              onRemove={() => toggleTrait(traitId)}
                              onWeightChange={(delta) => updateTraitWeight(traitId, delta)}
                            />
                          ))}
                        </div>
                      </SortableContext>
                    </DndContext>
                  </div>
                )}
              </div>
            )}
          </div>
        </ScrollArea>

        {/* 하단 버튼 */}
        <div className="p-4 border-t flex gap-2">
          <Button variant="outline" className="flex-1" onClick={handleReset}>
            초기화
          </Button>
          <Button className="flex-1" onClick={handleApply}>
            적용
          </Button>
        </div>

        {/* 유전자 선택 모달 */}
        {showGeneModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-lg max-h-[80vh] flex flex-col">
              <div className="flex items-center justify-between p-4 border-b">
                <h3 className="font-semibold text-lg">유전자 선택</h3>
                <button
                  onClick={() => setShowGeneModal(false)}
                  className="p-2 hover:bg-slate-100 rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-4 space-y-3 flex-1 overflow-y-auto">
                {/* 검색창 + 전체 선택/해제 버튼 */}
                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <Input
                      placeholder="유전자 검색..."
                      className="pl-9"
                      value={geneSearch}
                      onChange={(e) => setGeneSearch(e.target.value)}
                    />
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    className="whitespace-nowrap text-xs"
                    onClick={() => {
                      const allGenes = [...quantityGenes, ...qualityGenes]
                      toggleCategoryGenes(allGenes, true)
                    }}
                  >
                    전체 선택
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="whitespace-nowrap text-xs"
                    onClick={() => {
                      const allGenes = [...quantityGenes, ...qualityGenes]
                      toggleCategoryGenes(allGenes, false)
                    }}
                  >
                    전체 해제
                  </Button>
                </div>

                {loadingGenes ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
                  </div>
                ) : (
                  <div className="space-y-2">
                    {/* 육량형 */}
                    {(() => {
                      const genes = quantityGenes
                      const isCategoryMatch = geneSearch && '육량형'.includes(geneSearch.toLowerCase())
                      const filteredGenes = geneSearch
                        ? isCategoryMatch
                          ? genes
                          : genes.filter(g =>
                              g.markerNm.toLowerCase().includes(geneSearch.toLowerCase()) ||
                              (g.relatedTrait && g.relatedTrait.toLowerCase().includes(geneSearch.toLowerCase()))
                            )
                        : genes

                      if (geneSearch && filteredGenes.length === 0) return null

                      const selectedCount = filteredGenes.filter(g => localFilters.selectedGenes.includes(g.markerNm)).length
                      const isAllSelected = selectedCount === filteredGenes.length && filteredGenes.length > 0
                      const hasSelected = selectedCount > 0
                      const isExpanded = geneSearch ? true : (openCategories['quantity'] ?? false)

                      return (
                        <Collapsible
                          open={isExpanded}
                          onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, quantity: open }))}
                        >
                          <div className={`rounded-lg border ${hasSelected ? 'border-slate-300 bg-slate-100' : 'border-slate-200 bg-slate-50'}`}>
                            <div className="flex items-center justify-between p-3">
                              <div className="flex items-center gap-2">
                                <Checkbox
                                  checked={isAllSelected}
                                  onCheckedChange={(checked) => toggleCategoryGenes(filteredGenes, !!checked)}
                                  className="h-4 w-4"
                                />
                                <span className={`font-semibold text-sm ${hasSelected ? 'text-slate-800' : 'text-slate-700'}`}>
                                  육량형
                                </span>
                                <Badge variant="secondary" className="text-xs">
                                  {selectedCount}/{filteredGenes.length}
                                </Badge>
                              </div>
                              <CollapsibleTrigger asChild>
                                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                  {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                                </Button>
                              </CollapsibleTrigger>
                            </div>
                            <CollapsibleContent>
                              <div className="px-3 pb-3 space-y-1">
                                {filteredGenes.map(gene => {
                                  const isSelected = localFilters.selectedGenes.includes(gene.markerNm)
                                  return (
                                    <div
                                      key={gene.markerNm}
                                      className={`p-2 rounded-lg transition-colors cursor-pointer ${
                                        isSelected ? 'bg-white border border-slate-200' : 'hover:bg-white/50'
                                      }`}
                                      onClick={() => toggleGene(gene.markerNm)}
                                    >
                                      <div className="flex items-center gap-3">
                                        <Checkbox checked={isSelected} />
                                        <div className="flex-1">
                                          <span className="font-medium text-sm">{gene.markerNm}</span>
                                          {gene.relatedTrait && (
                                            <span className="text-xs text-muted-foreground ml-2">{gene.relatedTrait}</span>
                                          )}
                                        </div>
                                      </div>
                                    </div>
                                  )
                                })}
                              </div>
                            </CollapsibleContent>
                          </div>
                        </Collapsible>
                      )
                    })()}

                    {/* 육질형 */}
                    {(() => {
                      const genes = qualityGenes
                      const isCategoryMatch = geneSearch && '육질형'.includes(geneSearch.toLowerCase())
                      const filteredGenes = geneSearch
                        ? isCategoryMatch
                          ? genes
                          : genes.filter(g =>
                              g.markerNm.toLowerCase().includes(geneSearch.toLowerCase()) ||
                              (g.relatedTrait && g.relatedTrait.toLowerCase().includes(geneSearch.toLowerCase()))
                            )
                        : genes

                      if (geneSearch && filteredGenes.length === 0) return null

                      const selectedCount = filteredGenes.filter(g => localFilters.selectedGenes.includes(g.markerNm)).length
                      const isAllSelected = selectedCount === filteredGenes.length && filteredGenes.length > 0
                      const hasSelected = selectedCount > 0
                      const isExpanded = geneSearch ? true : (openCategories['quality'] ?? false)

                      return (
                        <Collapsible
                          open={isExpanded}
                          onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, quality: open }))}
                        >
                          <div className={`rounded-lg border ${hasSelected ? 'border-slate-300 bg-slate-100' : 'border-slate-200 bg-slate-50'}`}>
                            <div className="flex items-center justify-between p-3">
                              <div className="flex items-center gap-2">
                                <Checkbox
                                  checked={isAllSelected}
                                  onCheckedChange={(checked) => toggleCategoryGenes(filteredGenes, !!checked)}
                                  className="h-4 w-4"
                                />
                                <span className={`font-semibold text-sm ${hasSelected ? 'text-slate-800' : 'text-slate-700'}`}>
                                  육질형
                                </span>
                                <Badge variant="secondary" className="text-xs">
                                  {selectedCount}/{filteredGenes.length}
                                </Badge>
                              </div>
                              <CollapsibleTrigger asChild>
                                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                  {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                                </Button>
                              </CollapsibleTrigger>
                            </div>
                            <CollapsibleContent>
                              <div className="px-3 pb-3 space-y-1">
                                {filteredGenes.map(gene => {
                                  const isSelected = localFilters.selectedGenes.includes(gene.markerNm)
                                  return (
                                    <div
                                      key={gene.markerNm}
                                      className={`p-2 rounded-lg transition-colors cursor-pointer ${
                                        isSelected ? 'bg-white border border-slate-200' : 'hover:bg-white/50'
                                      }`}
                                      onClick={() => toggleGene(gene.markerNm)}
                                    >
                                      <div className="flex items-center gap-3">
                                        <Checkbox checked={isSelected} />
                                        <div className="flex-1">
                                          <span className="font-medium text-sm">{gene.markerNm}</span>
                                          {gene.relatedTrait && (
                                            <span className="text-xs text-muted-foreground ml-2">{gene.relatedTrait}</span>
                                          )}
                                        </div>
                                      </div>
                                    </div>
                                  )
                                })}
                              </div>
                            </CollapsibleContent>
                          </div>
                        </Collapsible>
                      )
                    })()}
                  </div>
                )}
              </div>

              <div className="p-4 border-t flex gap-2">
                <Button variant="outline" className="flex-1" onClick={() => setShowGeneModal(false)}>
                  취소
                </Button>
                <Button className="flex-1" onClick={() => setShowGeneModal(false)}>
                  완료 ({localFilters.selectedGenes.length}개 선택)
                </Button>
              </div>
            </div>
          </div>
        )}

        {/* 형질 선택 모달 */}
        {showTraitModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-lg max-h-[80vh] flex flex-col">
              <div className="flex items-center justify-between p-4 border-b">
                <h3 className="font-semibold text-lg">유전체 형질 선택</h3>
                <button
                  onClick={() => setShowTraitModal(false)}
                  className="p-2 hover:bg-slate-100 rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-4 space-y-3 flex-1 overflow-y-auto">
                {/* 검색창 + 전체 선택/해제 버튼 */}
                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <Input
                      placeholder="형질 검색..."
                      className="pl-9"
                      value={traitSearch}
                      onChange={(e) => setTraitSearch(e.target.value)}
                    />
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    className="whitespace-nowrap text-xs"
                    onClick={() => {
                      const allTraits = TRAIT_CATEGORIES.flatMap(cat => cat.traits)
                      toggleCategoryTraits(allTraits, true)
                    }}
                  >
                    전체 선택
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="whitespace-nowrap text-xs"
                    onClick={() => {
                      const allTraits = TRAIT_CATEGORIES.flatMap(cat => cat.traits)
                      toggleCategoryTraits(allTraits, false)
                    }}
                  >
                    전체 해제
                  </Button>
                </div>

                {/* 형질 목록 - 카테고리별 아코디언 */}
                <div className="space-y-2">
                  {TRAIT_CATEGORIES.map(cat => {
                    const isCategoryMatch = traitSearch && cat.name.toLowerCase().includes(traitSearch.toLowerCase())
                    const filteredTraits: string[] = traitSearch
                      ? isCategoryMatch
                        ? [...cat.traits]
                        : [...cat.traits].filter(t =>
                            t.toLowerCase().includes(traitSearch.toLowerCase()) ||
                            (TRAIT_DESCRIPTIONS[t] && TRAIT_DESCRIPTIONS[t].toLowerCase().includes(traitSearch.toLowerCase()))
                          )
                      : [...cat.traits]

                    if (traitSearch && filteredTraits.length === 0) return null

                    const selectedCount = filteredTraits.filter(t => localFilters.selectedTraits?.includes(t)).length
                    const isAllSelected = selectedCount === filteredTraits.length && filteredTraits.length > 0
                    const hasSelected = selectedCount > 0
                    const isExpanded = traitSearch ? true : (openCategories[cat.id] ?? false)

                    return (
                      <Collapsible
                        key={cat.id}
                        open={isExpanded}
                        onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, [cat.id]: open }))}
                      >
                        <div className={`rounded-lg border ${hasSelected ? 'border-slate-300 bg-slate-100' : 'border-slate-200 bg-slate-50'}`}>
                          <div className="flex items-center justify-between p-3">
                            <div className="flex items-center gap-2">
                              <Checkbox
                                checked={isAllSelected}
                                onCheckedChange={(checked) => toggleCategoryTraits(filteredTraits, !!checked)}
                                className="h-4 w-4"
                              />
                              <span className={`font-semibold text-sm ${hasSelected ? 'text-slate-800' : 'text-slate-700'}`}>
                                {cat.name}
                              </span>
                              <Badge variant="secondary" className="text-xs">
                                {selectedCount}/{filteredTraits.length}
                              </Badge>
                            </div>
                            <CollapsibleTrigger asChild>
                              <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                              </Button>
                            </CollapsibleTrigger>
                          </div>
                          <CollapsibleContent>
                            <div className="px-3 pb-3 space-y-1">
                              {filteredTraits.map(trait => {
                                const isSelected = localFilters.selectedTraits?.includes(trait)
                                return (
                                  <div
                                    key={trait}
                                    className={`p-2 rounded-lg transition-colors ${
                                      isSelected ? 'bg-white border border-slate-200' : 'hover:bg-white/50'
                                    }`}
                                  >
                                    <div
                                      className="flex items-center gap-3 cursor-pointer"
                                      onClick={() => toggleTrait(trait)}
                                    >
                                      <Checkbox checked={isSelected} />
                                      <div className="flex-1">
                                        <span className="font-medium text-sm">{TRAIT_DISPLAY_NAMES[trait] || trait}</span>
                                        {TRAIT_DESCRIPTIONS[trait] && (
                                          <span className="text-xs text-muted-foreground ml-2">{TRAIT_DESCRIPTIONS[trait]}</span>
                                        )}
                                      </div>
                                    </div>
                                    {isSelected && (
                                      <div className="flex items-center gap-2 mt-2 pl-7">
                                        <span className="text-xs text-muted-foreground">가중치</span>
                                        <div className="flex items-center gap-1">
                                          <Button
                                            variant="outline"
                                            size="sm"
                                            className="h-7 w-7 p-0"
                                            onClick={(e) => {
                                              e.stopPropagation()
                                              updateTraitWeight(trait, -1)
                                            }}
                                            disabled={(localFilters.traitWeights[trait as TraitName] || 1) <= 1}
                                          >
                                            -
                                          </Button>
                                          <span className="text-sm font-bold w-8 text-center">
                                            {localFilters.traitWeights[trait as TraitName] || 0}점
                                          </span>
                                          <Button
                                            variant="outline"
                                            size="sm"
                                            className="h-7 w-7 p-0"
                                            onClick={(e) => {
                                              e.stopPropagation()
                                              updateTraitWeight(trait, 1)
                                            }}
                                            disabled={(localFilters.traitWeights[trait as TraitName] || 0) >= 10}
                                          >
                                            +
                                          </Button>
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                )
                              })}
                            </div>
                          </CollapsibleContent>
                        </div>
                      </Collapsible>
                    )
                  })}
                </div>
              </div>

              <div className="p-4 border-t flex gap-2">
                <Button variant="outline" className="flex-1" onClick={() => setShowTraitModal(false)}>
                  취소
                </Button>
                <Button className="flex-1" onClick={() => setShowTraitModal(false)}>
                  완료 ({localFilters.selectedTraits?.length || 0}개 선택)
                </Button>
              </div>
            </div>
          </div>
        )}
      </SheetContent>
    </Sheet>
  )
}
