'use client'

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useEffect, useState } from "react"
import { useAnalysisYear } from "@/contexts/AnalysisYearContext"
import { useGlobalFilter } from "@/contexts/GlobalFilterContext"
import { Trophy, AlertTriangle, Sparkles, Star, AlertCircle, Lightbulb } from "lucide-react"
import { dashboardApi } from "@/lib/api/dashboard.api"
import { toast } from "sonner"

interface CattleItem {
  rank: number
  cattleId: string
  name: string
  score: number
  reason: string
  scoreUnit?: string // 점수 단위 (점, 마리 등)
}

interface Top3ListsProps {
  farmNo: number | null
  mode?: 'full' | 'compact' | 'cull-only' | 'recommend-only'
}

export function Top3Lists({ farmNo, mode = 'full' }: Top3ListsProps) {
  const { selectedYear } = useAnalysisYear()
  const { filters } = useGlobalFilter()
  const [excellentList, setExcellentList] = useState<CattleItem[]>([])
  const [cullingList, setCullingList] = useState<CattleItem[]>([])
  const [recommendList, setRecommendList] = useState<CattleItem[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      if (!farmNo) {
        setLoading(false)
        return
      }

      setLoading(true)

      try {
        // 필터 조건 생성
        const filterDto = {
          targetGenes: filters.selectedGenes,
          limit: 3, // Top 3만 가져오기
        }

        // 병렬로 API 호출
        const [excellentData, cullData, kpnData] = await Promise.all([
          dashboardApi.getExcellentCows(farmNo, filterDto),
          dashboardApi.getCullCows(farmNo, filterDto),
          dashboardApi.getKpnRecommendationAggregation(farmNo, filterDto),
        ])

        // 우수개체 데이터 변환
        const excellentList: CattleItem[] = (excellentData || []).map((item: any, index: number) => ({
          rank: index + 1,
          cattleId: item.cowNo || '없음',
          name: item.cowName || item.cowNo || '정보 없음', // 이름이 없으면 개체번호 사용
          score: Math.round(item.overallScore || 0),
          scoreUnit: '점',
          reason: item.reason || '정보 없음',
        }))

        // 도태개체 데이터 변환
        const cullList: CattleItem[] = (cullData || []).map((item: any, index: number) => ({
          rank: index + 1,
          cattleId: item.cowNo || '없음',
          name: item.cowName || item.cowNo || '정보 없음', // 이름이 없으면 개체번호 사용
          score: Math.round(item.overallScore || 0),
          scoreUnit: '점',
          reason: item.reason || '정보 없음',
        }))

        // KPN 추천 데이터 변환 (상위 3개)
        const recommendList: CattleItem[] = ((kpnData?.kpnAggregations || []) as any[])
          .slice(0, 3)
          .map((item: any, index: number) => ({
            rank: index + 1,
            cattleId: item.kpnNumber || '없음',
            name: item.kpnName || '이름 없음',
            score: item.recommendedCowCount || 0,
            scoreUnit: '마리',
            reason: `평균 매칭점수 ${Math.round(item.avgMatchingScore || 0)}점`,
          }))

        setExcellentList(excellentList)
        setCullingList(cullList)
        setRecommendList(recommendList)
      } catch (error: any) {
        toast.error(`데이터를 불러오는데 실패했습니다: ${error?.message || '알 수 없는 오류'}`)

        // 에러 시 빈 배열 설정
        setExcellentList([])
        setCullingList([])
        setRecommendList([])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [selectedYear, filters, farmNo])

  if (loading) {
    return (
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-3 md:gap-4">
        {[1, 2, 3].map((i) => (
          <Card key={i} className="border-gray-200">
            <CardHeader className="pb-2 md:pb-3">
              <CardTitle className="text-xs md:text-sm font-semibold">로딩 중...</CardTitle>
            </CardHeader>
            <CardContent className="pt-0 pb-2 md:pb-3">
              <div className="h-[150px] flex items-center justify-center">
                <div className="animate-pulse space-y-2 w-full">
                  <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                  <div className="h-4 bg-gray-200 rounded w-5/6"></div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  if (!farmNo) {
    return (
      <div className="px-4 lg:px-6">
        <h2 className="text-xl font-bold mb-4">주요 개체 및 추천</h2>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardHeader>
                <CardTitle>
                  {i === 1 ? '우수개체 Top3' : i === 2 ? '도태대상 Top3' : 'KPN추천 Top3'}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[200px] flex items-center justify-center">
                  <div className="text-center">
                    <p className="text-muted-foreground mb-2">농장 정보가 없습니다</p>
                    <p className="text-sm text-muted-foreground">로그인 후 다시 시도해주세요</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  const renderListCard = (
    title: string,
    description: string,
    icon: React.ReactNode,
    items: CattleItem[],
    variant: 'excellent' | 'culling' | 'recommend'
  ) => {
    const colorSchemes = {
      excellent: {
        badge: 'bg-green-600 text-white'
      },
      culling: {
        badge: 'bg-red-600 text-white'
      },
      recommend: {
        badge: 'bg-blue-600 text-white'
      }
    }

    const scheme = colorSchemes[variant]

    return (
      <Card>
        <CardContent className="pt-4">
          <div className="space-y-2.5">
            {items.map((item, index) => (
              <div
                key={item.cattleId}
                className="relative p-3 rounded-lg border border-gray-200 bg-white hover:shadow-sm transition-shadow"
              >
                {/* 순위 배지 */}
                <div className="absolute -top-1.5 -right-1.5">
                  <div className={`w-6 h-6 rounded-full ${scheme.badge} flex items-center justify-center text-[10px] font-bold shadow-sm`}>
                    {item.rank}
                  </div>
                </div>

                <div className="flex items-start justify-between mb-2">
                  <div className="flex-1">
                    <p className="font-semibold text-sm text-foreground mb-0.5">{item.name}</p>
                    <p className="text-[10px] text-muted-foreground font-mono">{item.cattleId}</p>
                  </div>
                  <div className="text-right ml-2">
                    <p className="text-xl font-bold text-foreground">{item.score}</p>
                    <p className="text-[10px] text-muted-foreground">{item.scoreUnit || '점'}</p>
                  </div>
                </div>

                <div className="pt-2 border-t border-gray-100">
                  <p className="text-xs text-muted-foreground">{item.reason}</p>
                </div>
              </div>
            ))}
          </div>

          {/* 요약 */}
          <div className="mt-4 pt-3 border-t border-border">
            <div className="text-center space-y-0.5">
              <p className="text-xs font-medium text-foreground">
                {variant === 'excellent'
                  ? '농장 내 최상위 개체'
                  : variant === 'culling'
                  ? '개선 또는 도태 권장'
                  : '최적 교배 추천'}
              </p>
              <p className="text-[10px] text-muted-foreground">
                {filters.analysisIndex === 'GENE' ? '유전자 기반 분석' : '유전능력 기반 분석'}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  // compact 모드: 우수개체만 표시
  if (mode === 'compact') {
    return renderListCard(
      '우수개체 Top3',
      '농장 내 상위 개체',
      <Trophy className="h-5 w-5 text-green-600" />,
      excellentList,
      'excellent'
    )
  }

  // cull-only 모드: 도태대상만 표시
  if (mode === 'cull-only') {
    return renderListCard(
      '도태대상 Top3',
      '개선 필요 개체',
      <AlertTriangle className="h-5 w-5 text-red-600" />,
      cullingList,
      'culling'
    )
  }

  // recommend-only 모드: KPN추천만 표시
  if (mode === 'recommend-only') {
    return renderListCard(
      'KPN추천 Top3',
      '최적 씨수소 추천',
      <Sparkles className="h-5 w-5 text-blue-600" />,
      recommendList,
      'recommend'
    )
  }

  // Vercel 스타일 리스트 아이템 렌더링
  const renderListItem = (item: CattleItem, variant: 'excellent' | 'culling' | 'recommend') => {
    const colorSchemes = {
      excellent: {
        icon: <Trophy className="h-4 w-4 text-green-600" />,
        scoreColor: 'text-green-600',
        dotColor: 'bg-green-500'
      },
      culling: {
        icon: <AlertTriangle className="h-4 w-4 text-red-600" />,
        scoreColor: 'text-red-600',
        dotColor: 'bg-red-500'
      },
      recommend: {
        icon: <Sparkles className="h-4 w-4 text-blue-600" />,
        scoreColor: 'text-blue-600',
        dotColor: 'bg-blue-500'
      }
    }

    const scheme = colorSchemes[variant]

    return (
      <div className="flex items-center justify-between py-2 md:py-2.5 border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors px-1 md:px-1.5 -mx-1 md:-mx-1.5 rounded">
        <div className="flex items-center gap-2 md:gap-2.5 flex-1 min-w-0">
          <div className={`w-1 h-1 md:w-1.5 md:h-1.5 rounded-full ${scheme.dotColor} flex-shrink-0`}></div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1 md:gap-1.5">
              <p className="text-xs md:text-sm font-medium text-foreground truncate">{item.name}</p>
              <span className="text-[9px] md:text-[10px] text-gray-400 font-mono flex-shrink-0">{item.cattleId}</span>
            </div>
            <p className="text-[9px] md:text-[10px] text-gray-500 mt-0.5 line-clamp-1">{item.reason}</p>
          </div>
        </div>
        <div className="flex items-center gap-1 md:gap-1.5 flex-shrink-0 ml-2">
          <p className={`text-sm md:text-base font-semibold ${scheme.scoreColor}`}>{item.score}</p>
          <span className="text-[9px] md:text-[10px] text-gray-400">{item.scoreUnit || '점'}</span>
        </div>
      </div>
    )
  }

  // full 모드: Vercel 스타일 리스트로 표시
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-3 md:gap-4">
      {/* 우수개체 섹션 */}
      <Card className="border-gray-200 shadow-none hover:border-black hover:shadow-lg transition-all duration-200">
        <CardHeader className="pb-2 md:pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1.5 md:gap-2">
              <Trophy className="h-3 w-3 md:h-3.5 md:w-3.5 text-green-600" />
              <CardTitle className="text-xs md:text-sm font-semibold">우수개체 Top3</CardTitle>
            </div>
            <svg className="w-3 h-3 md:w-3.5 md:h-3.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </CardHeader>
        <CardContent className="pt-0 pb-2 md:pb-3">
          {excellentList.length > 0 ? (
            <div className="space-y-0">
              {excellentList.map((item) => (
                <div key={item.cattleId}>
                  {renderListItem(item, 'excellent')}
                </div>
              ))}
            </div>
          ) : (
            <div className="h-[150px] flex items-center justify-center">
              <div className="text-center">
                <Trophy className="h-8 w-8 text-gray-300 mx-auto mb-2" />
                <p className="text-xs text-muted-foreground">데이터가 없습니다</p>
                <p className="text-[10px] text-gray-400 mt-1">유전체 분석 데이터를 등록해주세요</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 도태대상 섹션 */}
      <Card className="border-gray-200 shadow-none hover:border-black hover:shadow-lg transition-all duration-200">
        <CardHeader className="pb-2 md:pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1.5 md:gap-2">
              <AlertTriangle className="h-3 w-3 md:h-3.5 md:w-3.5 text-red-600" />
              <CardTitle className="text-xs md:text-sm font-semibold">도태대상 Top3</CardTitle>
            </div>
            <svg className="w-3 h-3 md:w-3.5 md:h-3.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </CardHeader>
        <CardContent className="pt-0 pb-2 md:pb-3">
          {cullingList.length > 0 ? (
            <div className="space-y-0">
              {cullingList.map((item) => (
                <div key={item.cattleId}>
                  {renderListItem(item, 'culling')}
                </div>
              ))}
            </div>
          ) : (
            <div className="h-[150px] flex items-center justify-center">
              <div className="text-center">
                <AlertTriangle className="h-8 w-8 text-gray-300 mx-auto mb-2" />
                <p className="text-xs text-muted-foreground">데이터가 없습니다</p>
                <p className="text-[10px] text-gray-400 mt-1">유전체 분석 데이터를 등록해주세요</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* KPN 추천 섹션 */}
      <Card className="border-gray-200 shadow-none hover:border-black hover:shadow-lg transition-all duration-200">
        <CardHeader className="pb-2 md:pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1.5 md:gap-2">
              <Sparkles className="h-3 w-3 md:h-3.5 md:w-3.5 text-blue-600" />
              <CardTitle className="text-xs md:text-sm font-semibold">KPN 추천 Top3</CardTitle>
            </div>
            <svg className="w-3 h-3 md:w-3.5 md:h-3.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </CardHeader>
        <CardContent className="pt-0 pb-2 md:pb-3">
          {recommendList.length > 0 ? (
            <div className="space-y-0">
              {recommendList.map((item) => (
                <div key={item.cattleId}>
                  {renderListItem(item, 'recommend')}
                </div>
              ))}
            </div>
          ) : (
            <div className="h-[150px] flex items-center justify-center">
              <div className="text-center">
                <Sparkles className="h-8 w-8 text-gray-300 mx-auto mb-2" />
                <p className="text-xs text-muted-foreground">데이터가 없습니다</p>
                <p className="text-[10px] text-gray-400 mt-1">KPN 및 개체 데이터를 등록해주세요</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
