'use client'

import { useMemo, useEffect, useState } from 'react'
import { Card, CardContent } from "@/components/ui/card"
import { DEFAULT_TRAITS, NEGATIVE_TRAITS, getTraitDisplayName } from "@/constants/traits"
import { GenomeCowTraitDto } from "@/types/genome.types"
import { genomeApi, TraitRankDto } from "@/lib/api/genome.api"

// 카테고리별 배지 스타일 (진한 톤)
const CATEGORY_STYLES: Record<string, { bg: string; text: string; border: string }> = {
  '성장': { bg: 'bg-amber-100', text: 'text-amber-800', border: 'border-amber-300' },
  '경제': { bg: 'bg-emerald-100', text: 'text-emerald-800', border: 'border-emerald-300' },
  '체형': { bg: 'bg-blue-100', text: 'text-blue-800', border: 'border-blue-300' },
  '부위별무게': { bg: 'bg-purple-100', text: 'text-purple-800', border: 'border-purple-300' },
  '부위별비율': { bg: 'bg-rose-100', text: 'text-rose-800', border: 'border-rose-300' },
  // 기존 호환
  '생산': { bg: 'bg-emerald-100', text: 'text-emerald-800', border: 'border-emerald-300' },
  '무게': { bg: 'bg-purple-100', text: 'text-purple-800', border: 'border-purple-300' },
  '비율': { bg: 'bg-rose-100', text: 'text-rose-800', border: 'border-rose-300' },
}

interface TraitDistributionChartsProps {
  allTraits: GenomeCowTraitDto[]
  regionAvgZ: number
  farmAvgZ: number
  cowName?: string
  cowNo?: string  // API 호출용 개체번호
  totalCowCount?: number
  selectedTraits?: GenomeCowTraitDto[]
  traitWeights?: Record<string, number>
}

// 테이블 뷰 컴포넌트 (데스크탑)
function TraitTableView({ traits, traitRanks }: {
  traits: Array<{
    traitName?: string;
    shortName: string;
    breedVal: number;
    percentile?: number;
    traitCategory?: string;
    traitVal?: number;
    hasData?: boolean;
  }>;
  traitRanks: Record<string, TraitRankDto>
}) {
  return (
    <Card className="hidden lg:block bg-white border border-border rounded-xl overflow-hidden shadow-md">
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <table className="w-full text-[1.5rem]">
            <thead>
              <tr className="border-b-2 border-border bg-muted/70">
                <th className="px-3 sm:px-5 py-4 text-center font-semibold text-foreground">유전형질</th>
                <th className="px-3 sm:px-5 py-4 text-center font-semibold text-foreground">유전체 육종가</th>
                <th className="px-3 sm:px-5 py-4 text-center font-semibold text-foreground">전국 백분위</th>
                <th className="px-3 sm:px-5 py-4 text-center font-semibold text-foreground">농가 내 순위</th>
                <th className="px-3 sm:px-5 py-4 text-center font-semibold text-foreground">보은군 내 순위</th>
              </tr>
            </thead>
            <tbody>
              {traits.map((trait, idx) => {
                const rankData = trait.traitName ? traitRanks[trait.traitName] : null
                return (
                  <tr key={trait.traitName || idx} className="border-b border-border last:border-b-0 hover:bg-muted/30 transition-colors">
                    <td className="px-3 sm:px-5 py-4 text-center">
                      <span className="font-medium text-foreground">{trait.shortName}</span>
                    </td>
                    <td className="px-3 sm:px-5 py-4 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <span className={`font-bold ${(() => {
                          const value = trait.traitVal ?? 0
                          const isNegativeTrait = NEGATIVE_TRAITS.includes(trait.traitName || '')
                          if (value === 0) return 'text-muted-foreground'
                          if (isNegativeTrait) {
                            return value < 0 ? 'text-green-600' : 'text-red-600'
                          }
                          return value > 0 ? 'text-green-600' : 'text-red-600'
                        })()}`}>
                          {trait.traitVal !== undefined ? (
                            <>{trait.traitVal > 0 ? '+' : ''}{trait.traitVal.toFixed(1)}</>
                          ) : '-'}
                        </span>
                      </div>
                    </td>
                    <td className="px-3 sm:px-5 py-4 text-center">
                      <span className="font-bold text-foreground">
                        상위 {(trait.percentile || 0).toFixed(0)}%
                      </span>
                    </td>
                    <td className="px-3 sm:px-5 py-4 text-center">
                      <span className="font-bold text-foreground">
                        {rankData?.farmRank && rankData.farmTotal ? (
                          `${rankData.farmRank}위/${rankData.farmTotal}두`
                        ) : '-'}
                      </span>
                    </td>
                    <td className="px-3 sm:px-5 py-4 text-center">
                      <span className="font-bold text-foreground">
                        {rankData?.regionRank && rankData.regionTotal ? (
                          `${rankData.regionRank}위/${rankData.regionTotal}두`
                        ) : '-'}
                      </span>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </CardContent>
    </Card>
  )
}

// 카드 뷰 컴포넌트 (모바일)
function TraitCardView({ traits, traitRanks }: {
  traits: Array<{
    traitName?: string;
    shortName: string;
    breedVal: number;
    percentile?: number;
    traitCategory?: string;
    traitVal?: number;
    hasData?: boolean;
  }>;
  traitRanks: Record<string, TraitRankDto>
}) {
  return (
    <div className="lg:hidden space-y-3">
      {traits.map((trait, idx) => {
        const rankData = trait.traitName ? traitRanks[trait.traitName] : null
        const value = trait.traitVal ?? 0
        const isNegativeTrait = NEGATIVE_TRAITS.includes(trait.traitName || '')
        const valueColor = (() => {
          if (value === 0) return 'text-muted-foreground'
          if (isNegativeTrait) {
            return value < 0 ? 'text-green-600' : 'text-red-600'
          }
          return value > 0 ? 'text-green-600' : 'text-red-600'
        })()

        return (
          <Card key={trait.traitName || idx} className="bg-white border border-border rounded-xl overflow-hidden shadow-sm">
            <CardContent className="p-4">
              <div className="space-y-3">
                {/* 형질명 */}
                <div className="flex items-center justify-between pb-3 border-b border-border">
                  <span className="text-sm font-medium text-muted-foreground">유전형질</span>
                  <span className="text-base font-bold text-foreground">{trait.shortName}</span>
                </div>

                {/* 유전체 육종가 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">유전체 육종가</span>
                  <span className={`text-base font-bold ${valueColor}`}>
                    {trait.traitVal !== undefined ? (
                      <>{trait.traitVal > 0 ? '+' : ''}{trait.traitVal.toFixed(1)}</>
                    ) : '-'}
                  </span>
                </div>

                {/* 전국 백분위 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">전국 백분위</span>
                  <span className="text-base font-bold text-foreground">
                    상위 {(trait.percentile || 0).toFixed(0)}%
                  </span>
                </div>

                {/* 농가 내 순위 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">농가 내 순위</span>
                  <span className="text-base font-bold text-foreground">
                    {rankData?.farmRank && rankData.farmTotal ? (
                      `${rankData.farmRank}위/${rankData.farmTotal}두`
                    ) : '-'}
                  </span>
                </div>

                {/* 보은군 내 순위 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">보은군 내 순위</span>
                  <span className="text-base font-bold text-foreground">
                    {rankData?.regionRank && rankData.regionTotal ? (
                      `${rankData.regionRank}위/${rankData.regionTotal}두`
                    ) : '-'}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        )
      })}
    </div>
  )
}

// 메인 컴포넌트
export function TraitDistributionCharts({
  allTraits,
  regionAvgZ,
  farmAvgZ,
  cowName = '개체',
  cowNo,
  totalCowCount = 100,
  selectedTraits = [],
  traitWeights = {}
}: TraitDistributionChartsProps) {
  // 개체번호에서 KOR 제외한 002로 시작하는 번호 추출
  const displayCowNumber = useMemo(() => {
    if (!cowName) return '개체'
    const match = cowName.match(/002\d+/)
    return match ? match[0] : cowName
  }, [cowName])

  // 표시할 형질 결정: 선택된 형질이 있으면 사용, 없으면 기본 7개
  // 육종가는 가중치 적용된 값 (원본 육종가 × 가중치)
  const displayTraits = useMemo(() => {
    if (selectedTraits.length > 0) {
      return selectedTraits.map(trait => {
        const weight = traitWeights[trait.traitName || ''] || 1
        return {
          traitName: trait.traitName,
          shortName: getTraitDisplayName(trait.traitName || ''),
          breedVal: (trait.breedVal || 0) * weight,
          percentile: trait.percentile,
          traitCategory: trait.traitCategory,
          traitVal: trait.traitVal,
          hasData: true
        }
      })
    }
    // 기본 7개 형질
    return DEFAULT_TRAITS.map(traitName => {
      const trait = allTraits.find(t => t.traitName === traitName)
      const weight = traitWeights[traitName] || 1
      return {
        traitName: traitName,
        shortName: getTraitDisplayName(traitName),
        breedVal: (trait?.breedVal ?? 0) * weight,
        percentile: trait?.percentile ?? 50,
        traitCategory: trait?.traitCategory,
        traitVal: trait?.traitVal,
        hasData: !!trait
      }
    })
  }, [allTraits, selectedTraits, traitWeights])

  // 표시할 형질명 목록 (순위 조회용)
  const traitNames = useMemo(() => {
    return displayTraits
      .filter(trait => trait.traitName && trait.hasData)
      .map(trait => trait.traitName!)
      .sort()  // 정렬하여 안정적인 키 생성
  }, [displayTraits])

  // 형질명 목록의 안정적인 키 (dependency용)
  const traitNamesKey = useMemo(() => {
    return traitNames.join(',')
  }, [traitNames])

  // 각 형질의 순위 정보 가져오기
  const [traitRanks, setTraitRanks] = useState<Record<string, TraitRankDto>>({})
  const [loadingRanks, setLoadingRanks] = useState(false)

  useEffect(() => {
    if (!cowNo || traitNames.length === 0) return

    const fetchRanks = async () => {
      setLoadingRanks(true)
      try {
        const rankPromises = traitNames.map(traitName => 
          genomeApi.getTraitRank(cowNo, traitName)
            .then(rank => ({ traitName, rank }))
            .catch(() => null)
        )
        
        const results = await Promise.all(rankPromises)
        const ranksMap: Record<string, TraitRankDto> = {}
        results.forEach(result => {
          if (result) {
            ranksMap[result.traitName] = result.rank
          }
        })
        setTraitRanks(ranksMap)
      } catch (error) {
        console.error('순위 정보 로드 실패:', error)
      } finally {
        setLoadingRanks(false)
      }
    }

    fetchRanks()
  }, [cowNo, traitNamesKey])

  return (
    <>
      {/* 헤더 */}
      <div className="flex items-center justify-between mb-3">
        <div className="text-sm text-muted-foreground">
          {selectedTraits.length > 0 ? (
            <span>선택된 형질 <span className="font-semibold text-primary">{selectedTraits.length}개</span></span>
          ) : (
            <span>기본 형질 <span className="font-semibold">7개</span></span>
          )}
        </div>
      </div>

      {/* 테이블 뷰 (데스크탑) */}
      <TraitTableView traits={displayTraits} traitRanks={traitRanks} />
      
      {/* 카드 뷰 (모바일) */}
      <TraitCardView traits={displayTraits} traitRanks={traitRanks} />
    </>
  )
}
