'use client'

import { useMemo } from 'react'
import { Card, CardContent } from "@/components/ui/card"

// 기본 7개 형질
const DEFAULT_TRAITS = ['도체중', '등심단면적', '등지방두께', '근내지방도', '체장', '체고', '등심weight']

// 낮을수록 좋은 형질 (부호 반전 색상 적용)
const NEGATIVE_TRAITS = ['등지방두께']

// 형질명 표시 (전체 이름)
const TRAIT_SHORT_NAMES: Record<string, string> = {
  '도체중': '도체중',
  '등심단면적': '등심단면적',
  '등지방두께': '등지방두께',
  '근내지방도': '근내지방도',
  '체장': '체장',
  '체고': '체고',
  '등심weight': '등심중량'
}

// 카테고리별 배지 스타일 (진한 톤)
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 TraitData {
  id: number
  name: string
  category: string
  breedVal: number
  percentile: number
  actualValue: number
  unit: string
}

interface TraitDistributionChartsProps {
  allTraits: TraitData[]
  regionAvgZ: number
  farmAvgZ: number
  cowName?: string
  totalCowCount?: number
  selectedTraits?: TraitData[]
  traitWeights?: Record<string, number>
}

// 리스트 뷰 컴포넌트
function TraitListView({ traits, cowName }: { traits: Array<{ name: string; shortName: string; breedVal: number; percentile: number; category?: string; actualValue?: number }>; cowName: string }) {
  return (
    <Card className="bg-white border border-border rounded-xl overflow-hidden shadow-md">
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b-2 border-border bg-muted/70">
                <th className="px-3 sm:px-5 py-4 text-center text-sm sm:text-base font-bold text-foreground">형질명</th>
                <th className="px-3 sm:px-5 py-4 text-left text-sm sm:text-base font-bold text-foreground">카테고리</th>
                <th className="px-3 sm:px-5 py-4 text-left text-sm sm:text-base font-bold text-foreground">육종가</th>
                <th className="px-3 sm:px-5 py-4 text-left text-sm sm:text-base font-bold text-foreground">전국 백분위</th>
              </tr>
            </thead>
            <tbody>
              {traits.map((trait, idx) => (
                <tr key={trait.name} 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="text-sm sm:text-lg font-semibold text-foreground">{trait.shortName}</span>
                  </td>
                  <td className="px-3 sm:px-5 py-4 text-left">
                    {trait.category && (
                      <span
                        className={`inline-flex items-center text-xs sm:text-sm font-bold px-3 sm:px-4 py-1.5 rounded-full whitespace-nowrap border-2 ${CATEGORY_STYLES[trait.category]?.bg || 'bg-slate-50'} ${CATEGORY_STYLES[trait.category]?.text || 'text-slate-700'} ${CATEGORY_STYLES[trait.category]?.border || 'border-slate-200'}`}
                      >
                        {trait.category}
                      </span>
                    )}
                  </td>
                  <td className="px-3 sm:px-5 py-4 text-left">
                    <div className="flex items-center gap-2">
                      <span className={`text-base sm:text-xl font-bold ${(() => {
                        const value = trait.actualValue ?? 0
                        const isNegativeTrait = NEGATIVE_TRAITS.includes(trait.name)
                        // 등지방두께: 음수가 좋음(녹색), 양수가 나쁨(빨간색)
                        // 나머지: 양수가 좋음(녹색), 음수가 나쁨(빨간색)
                        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.actualValue !== undefined ? (
                          <>{trait.actualValue > 0 ? '+' : ''}{trait.actualValue.toFixed(1)}</>
                        ) : '-'}
                      </span>
                    </div>
                  </td>
                  <td className="px-3 sm:px-5 py-4 text-left">
                    <span className="text-base sm:text-xl font-bold text-foreground">
                      상위 {trait.percentile.toFixed(0)}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </CardContent>
    </Card>
  )
}

// 메인 컴포넌트
export function TraitDistributionCharts({
  allTraits,
  regionAvgZ,
  farmAvgZ,
  cowName = '개체',
  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.name] || 1
        return {
          name: trait.name,
          shortName: TRAIT_SHORT_NAMES[trait.name] || trait.name,
          breedVal: trait.breedVal * weight,
          percentile: trait.percentile,
          category: trait.category,
          actualValue: trait.actualValue,
          hasData: true
        }
      })
    }
    // 기본 7개 형질
    return DEFAULT_TRAITS.map(traitName => {
      const trait = allTraits.find(t => t.name === traitName)
      const weight = traitWeights[traitName] || 1
      return {
        name: traitName,
        shortName: TRAIT_SHORT_NAMES[traitName] || traitName,
        breedVal: (trait?.breedVal ?? 0) * weight,
        percentile: trait?.percentile ?? 50,
        category: trait?.category,
        actualValue: trait?.actualValue,
        hasData: !!trait
      }
    })
  }, [allTraits, selectedTraits, traitWeights])

  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>

      {/* 리스트 뷰 */}
      <TraitListView traits={displayTraits} cowName={displayCowNumber} />
    </>
  )
}
