'use client'

import { useState, useMemo, useEffect } from "react"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Search, Loader2 } from "lucide-react"
import { geneApi } from "@/lib/api/gene.api"

/**
 * 마커 데이터 타입 (API에서 받아오는 형식)
 */
interface MarkerData {
  pkMarkerNo: number
  markerNm: string
  markerDesc: string
  markerTypeCd: string
  relatedTrait: string
  favorableAllele: string
  useYn: string
  markerTypeInfo?: {
    pkTypeCd: string
    typeNm: string
    typeDesc: string
  }
}

/**
 * 유전자 필터에서 사용할 간소화된 타입
 */
interface GeneOption {
  name: string
  description: string
  type: 'QTY' | 'QLT'
  relatedTrait: string
}

interface GeneFilterModalProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  selectedGenes: string[]
  onConfirm: (genes: string[]) => void
}

export function GeneFilterModal({ open, onOpenChange, selectedGenes, onConfirm }: GeneFilterModalProps) {
  const [tempSelectedGenes, setTempSelectedGenes] = useState<string[]>(selectedGenes)
  const [searchQuery, setSearchQuery] = useState('')
  const [sortBy, setSortBy] = useState<'name' | 'type'>('name')
  const [allMarkers, setAllMarkers] = useState<GeneOption[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // API에서 마커 목록 가져오기
  useEffect(() => {
    if (open) {
      fetchMarkers()
    }
  }, [open])

  const fetchMarkers = async () => {
    try {
      setLoading(true)
      setError(null)
      const markers = await geneApi.getAllMarkers() as unknown as MarkerData[]

      // API 데이터를 GeneOption 형식으로 변환
      const geneOptions: GeneOption[] = markers.map(marker => ({
        name: marker.markerNm,
        description: marker.relatedTrait || marker.markerDesc || '',
        type: marker.markerTypeCd as 'QTY' | 'QLT',
        relatedTrait: marker.relatedTrait || ''
      }))

      setAllMarkers(geneOptions)
    } catch (err) {
      console.error('Failed to fetch markers:', err)
      setError('유전자 목록을 불러오는데 실패했습니다.')
    } finally {
      setLoading(false)
    }
  }

  // 육량형/육질형 필터링
  const quantityGenes = useMemo(() => {
    return allMarkers.filter(g => g.type === 'QTY').sort((a, b) => a.name.localeCompare(b.name))
  }, [allMarkers])

  const qualityGenes = useMemo(() => {
    return allMarkers.filter(g => g.type === 'QLT').sort((a, b) => a.name.localeCompare(b.name))
  }, [allMarkers])

  // 전체 유전자 목록 (정렬)
  const allGenes = useMemo(() => {
    return [...allMarkers].sort((a, b) => {
      if (sortBy === 'type') {
        if (a.type !== b.type) {
          return a.type.localeCompare(b.type)
        }
      }
      return a.name.localeCompare(b.name)
    })
  }, [allMarkers, sortBy])

  const filteredGenes = useMemo(() => {
    if (!searchQuery) return allGenes
    return allGenes.filter(gene =>
      gene.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      gene.description.toLowerCase().includes(searchQuery.toLowerCase())
    )
  }, [allGenes, searchQuery])

  const toggleGene = (geneName: string) => {
    setTempSelectedGenes(prev =>
      prev.includes(geneName)
        ? prev.filter(g => g !== geneName)
        : [...prev, geneName]
    )
  }

  const handleConfirm = () => {
    onConfirm(tempSelectedGenes)
    onOpenChange(false)
  }

  const handleCancel = () => {
    setTempSelectedGenes(selectedGenes)
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>유전자 선택</DialogTitle>
          <DialogDescription>
            개체를 필터링할 유전자를 선택하세요. 시스템이 자동으로 중요도 순으로 정렬합니다.
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <span className="ml-2">유전자 목록 불러오는 중...</span>
          </div>
        ) : error ? (
          <div className="text-center py-8 text-destructive">
            <p>{error}</p>
            <Button variant="outline" className="mt-4" onClick={fetchMarkers}>
              다시 시도
            </Button>
          </div>
        ) : (
          <Tabs defaultValue="quick" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="quick">타입별 선택 ({allMarkers.length}개)</TabsTrigger>
              <TabsTrigger value="all">전체 유전자 검색</TabsTrigger>
            </TabsList>

            <TabsContent value="quick" className="space-y-4">
              <Tabs defaultValue="quantity" className="w-full">
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="quantity">육량형 ({quantityGenes.length}개)</TabsTrigger>
                  <TabsTrigger value="quality">육질형 ({qualityGenes.length}개)</TabsTrigger>
                </TabsList>

                <TabsContent value="quantity">
                  <ScrollArea className="h-[300px] w-full rounded-md border p-4">
                    <div className="space-y-3">
                      {quantityGenes.length === 0 ? (
                        <p className="text-center text-muted-foreground py-8">
                          육량형 유전자가 없습니다.
                        </p>
                      ) : (
                        quantityGenes.map((gene) => (
                          <div key={gene.name} className="flex items-start space-x-3">
                            <Checkbox
                              id={`quick-${gene.name}`}
                              checked={tempSelectedGenes.includes(gene.name)}
                              onCheckedChange={() => toggleGene(gene.name)}
                            />
                            <div className="flex-1">
                              <Label
                                htmlFor={`quick-${gene.name}`}
                                className="text-sm font-medium cursor-pointer"
                              >
                                {gene.name}
                              </Label>
                              <p className="text-xs text-muted-foreground">{gene.description}</p>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </ScrollArea>
                </TabsContent>

                <TabsContent value="quality">
                  <ScrollArea className="h-[300px] w-full rounded-md border p-4">
                    <div className="space-y-3">
                      {qualityGenes.length === 0 ? (
                        <p className="text-center text-muted-foreground py-8">
                          육질형 유전자가 없습니다.
                        </p>
                      ) : (
                        qualityGenes.map((gene) => (
                          <div key={gene.name} className="flex items-start space-x-3">
                            <Checkbox
                              id={`quick-${gene.name}`}
                              checked={tempSelectedGenes.includes(gene.name)}
                              onCheckedChange={() => toggleGene(gene.name)}
                            />
                            <div className="flex-1">
                              <Label
                                htmlFor={`quick-${gene.name}`}
                                className="text-sm font-medium cursor-pointer"
                              >
                                {gene.name}
                              </Label>
                              <p className="text-xs text-muted-foreground">{gene.description}</p>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </ScrollArea>
                </TabsContent>
              </Tabs>
            </TabsContent>

            <TabsContent value="all" className="space-y-4">
              <div className="flex gap-2">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <Input
                    placeholder="유전자명 또는 설명 검색..."
                    className="pl-9"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                </div>
                <Button
                  variant="outline"
                  onClick={() => setSortBy(sortBy === 'name' ? 'type' : 'name')}
                >
                  {sortBy === 'type' ? '타입순' : '이름순'}
                </Button>
              </div>

              <ScrollArea className="h-[300px] w-full rounded-md border p-4">
                <div className="space-y-3">
                  {filteredGenes.length === 0 ? (
                    <p className="text-center text-muted-foreground py-8">
                      검색 결과가 없습니다.
                    </p>
                  ) : (
                    filteredGenes.map((gene) => (
                      <div key={gene.name} className="flex items-start space-x-3">
                        <Checkbox
                          id={`all-${gene.name}`}
                          checked={tempSelectedGenes.includes(gene.name)}
                          onCheckedChange={() => toggleGene(gene.name)}
                        />
                        <div className="flex-1">
                          <Label
                            htmlFor={`all-${gene.name}`}
                            className="text-sm font-medium cursor-pointer"
                          >
                            {gene.name} <span className="text-xs text-muted-foreground">({gene.type === 'QTY' ? '육량형' : '육질형'})</span>
                          </Label>
                          <p className="text-xs text-muted-foreground">{gene.description}</p>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </ScrollArea>
            </TabsContent>
          </Tabs>
        )}

        <div className="text-sm text-muted-foreground">
          선택된 유전자: {tempSelectedGenes.length}개
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button onClick={handleConfirm}>
            선택 완료
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
