'use client'

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip as RechartsTooltip,
  ResponsiveContainer,
  ReferenceLine
} from 'recharts'

// 형질 데이터 타입
interface GenomicTrait {
  id: number
  name: string
  category: string
  breedVal: number
  percentile: number
  actualValue: number
  description?: string  // 형질 설명
  unit?: string         // 단위 (kg, cm 등)
}

interface CategoryTraitGridProps {
  categories: string[]
  traits: GenomicTrait[]
}

// 카테고리 색상
const CATEGORY_COLORS: Record<string, string> = {
  '성장': '#3b82f6',
  '생산': '#f59e0b',
  '체형': '#10b981',
  '무게': '#8b5cf6',
  '비율': '#ec4899'
}

// 백분위 기반 등급 계산
function getGradeFromPercentile(percentile: number): { grade: string; color: string; bg: string } {
  if (percentile <= 16) {
    return { grade: '우수', color: 'text-green-600', bg: 'bg-green-100' }
  } else if (percentile <= 84) {
    return { grade: '보통', color: 'text-gray-600', bg: 'bg-gray-100' }
  } else {
    return { grade: '개선필요', color: 'text-orange-600', bg: 'bg-orange-100' }
  }
}

// 정규분포 데이터 생성
function generateNormalDistribution(mean: number, stdDev: number, currentValue: number) {
  const data = []
  for (let x = -3; x <= 3; x += 0.1) {
    const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) *
      Math.exp(-0.5 * Math.pow((x - mean) / stdDev, 2))
    data.push({
      x: parseFloat(x.toFixed(2)),
      density: y * 100,
      value: y
    })
  }
  return data
}

export function CategoryTraitGrid({ categories, traits }: CategoryTraitGridProps) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      {categories.map(cat => {
        const catTraits = traits.filter(t => t.category === cat)
        if (catTraits.length === 0) return null

        return (
          <Card key={cat} className="bg-white border-0 shadow-sm rounded-xl">
            <CardHeader className="pb-2 sm:pb-3">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-sm md:text-base flex items-center gap-2">
                    <div
                      className="w-3 h-3 rounded flex-shrink-0"
                      style={{ backgroundColor: CATEGORY_COLORS[cat] }}
                    />
                    {cat} 형질
                  </CardTitle>
                  <CardDescription className="text-xs">{catTraits.length}개 형질 정규분포 분석</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="pt-0">
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-2 xl:grid-cols-3 gap-2 sm:gap-3">
                {catTraits.map(trait => {
                  const distribution = generateNormalDistribution(0, 1, trait.breedVal)
                  return (
                    <div key={trait.id} className="border border-border rounded-lg p-2 md:p-3 hover:shadow-md transition-shadow bg-card">
                      {/* 형질명 + 등급 배지 */}
                      <div className="mb-1.5 md:mb-2">
                        <div className="flex items-center justify-between gap-1">
                          <div className="text-xs md:text-sm font-bold text-foreground truncate" title={trait.name}>
                            {trait.name}
                          </div>
                          <span className={`text-[9px] md:text-[10px] font-medium px-1.5 py-0.5 rounded ${getGradeFromPercentile(trait.percentile).bg} ${getGradeFromPercentile(trait.percentile).color} whitespace-nowrap`}>
                            {getGradeFromPercentile(trait.percentile).grade}
                          </span>
                        </div>
                        <div className="text-[10px] md:text-xs text-muted-foreground truncate">
                          {trait.description}
                        </div>
                      </div>

                      {/* 정규분포 미니 차트 */}
                      <div className="h-12 md:h-14 mb-1.5 md:mb-2">
                        <ResponsiveContainer width="100%" height="100%">
                          <AreaChart data={distribution} margin={{ top: 3, right: 3, left: 3, bottom: 0 }}>
                            <defs>
                              <linearGradient id={`grad-${trait.id}`} x1="0" y1="0" x2="0" y2="1">
                                <stop offset="5%" stopColor={CATEGORY_COLORS[cat]} stopOpacity={0.5} />
                                <stop offset="95%" stopColor={CATEGORY_COLORS[cat]} stopOpacity={0.1} />
                              </linearGradient>
                            </defs>
                            <XAxis dataKey="x" type="number" domain={[-3, 3]} hide />
                            <YAxis domain={[0, 42]} hide />
                            <RechartsTooltip
                              content={() => (
                                <div className="bg-white/95 backdrop-blur-sm border border-border rounded-lg shadow-lg px-2.5 py-1.5 text-xs">
                                  <div className="font-semibold text-foreground">{trait.name}</div>
                                  <div className="text-muted-foreground">육종가: {trait.breedVal > 0 ? '+' : ''}{trait.breedVal.toFixed(2)}σ</div>
                                  <div className="text-muted-foreground">백분위: 상위 {trait.percentile.toFixed(1)}%</div>
                                </div>
                              )}
                            />
                            <Area
                              type="monotone"
                              dataKey="density"
                              stroke={CATEGORY_COLORS[cat]}
                              strokeWidth={1.5}
                              fill={`url(#grad-${trait.id})`}
                            />
                            <ReferenceLine
                              x={parseFloat(trait.breedVal.toFixed(2))}
                              stroke="#ef4444"
                              strokeWidth={1.5}
                              strokeDasharray="3 3"
                            />
                          </AreaChart>
                        </ResponsiveContainer>
                      </div>

                      {/* 지표 */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-muted-foreground">표준화 육종가</span>
                          <Badge
                            variant={trait.breedVal > 0 ? "default" : "secondary"}
                            className="text-xs"
                          >
                            {trait.breedVal > 0 ? '+' : ''}{trait.breedVal.toFixed(2)}
                          </Badge>
                        </div>
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-muted-foreground">백분위</span>
                          <span className="font-semibold text-foreground">{trait.percentile.toFixed(1)}%</span>
                        </div>
                        <Progress value={trait.percentile} className="h-1.5" />
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-muted-foreground">실측값</span>
                          <span className="font-semibold text-foreground">
                            {trait.actualValue} {trait.unit}
                          </span>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        )
      })}
    </div>
  )
}
