'use client'

import { Target } from "lucide-react"
import { useEffect, useState } from "react"
import { apiClient } from "@/lib/api"
import { ResponsiveContainer, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, Tooltip } from 'recharts'

interface TraitScore {
  trait: string
  diff: number
  myFarm: number
  region: number
}

interface GenomeRadarChartProps {
  farmNo: number | null
}

export function GenomeRadarChart({ farmNo }: GenomeRadarChartProps) {
  const [data, setData] = useState<TraitScore[]>([])
  const [loading, setLoading] = useState(true)

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

      try {
        const traits = [
          { name: '도체중', key: '도체중' },
          { name: '근내지방', key: '근내지방도' },
          { name: '등심단면적', key: '등심단면적' },
          { name: '등지방', key: '등지방두께' },
          { name: '12개월체중', key: '12개월령체중' },
        ]

        const results: TraitScore[] = []

        for (const trait of traits) {
          try {
            const farmResponse = await apiClient.post('/cow/ranking', {
              filterOptions: { farmNo },
              rankingOptions: {
                criteriaType: 'GENOME',
                traitConditions: [{ traitNm: trait.key, weight: 1.0 }]
              }
            })

            const globalResponse = await apiClient.post('/cow/ranking/global', {
              rankingOptions: {
                criteriaType: 'GENOME',
                traitConditions: [{ traitNm: trait.key, weight: 1.0 }]
              }
            })

            const farmResult = farmResponse.data || farmResponse
            const globalResult = globalResponse.data || globalResponse

            const farmScores = farmResult.items?.map((item: any) => {
              const traitDetail = item.details?.find((d: any) => d.code === trait.key)
              return traitDetail?.value ?? item.sortValue ?? 0
            }) || []
            const farmAvgScore = farmScores.length > 0
              ? farmScores.reduce((sum: number, s: number) => sum + s, 0) / farmScores.length
              : 0

            const globalScores = globalResult.items?.map((item: any) => {
              const traitDetail = item.details?.find((d: any) => d.code === trait.key)
              return traitDetail?.value ?? item.sortValue ?? 0
            }) || []
            const regionAvgScore = globalScores.length > 0
              ? globalScores.reduce((sum: number, s: number) => sum + s, 0) / globalScores.length
              : 0

            const diff = farmAvgScore - regionAvgScore

            results.push({
              trait: trait.name,
              diff: parseFloat(diff.toFixed(2)),
              myFarm: parseFloat(farmAvgScore.toFixed(2)),
              region: parseFloat(regionAvgScore.toFixed(2))
            })
          } catch (error) {
            console.error(`형질 ${trait.name} 로드 실패:`, error)
          }
        }

        setData(results)
      } catch (error) {
        console.error('레이더 차트 데이터 로드 실패:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [farmNo])

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-100 p-4">
        <div className="flex items-center justify-center h-[280px]">
          <div className="w-6 h-6 border-2 border-slate-200 border-t-[#1482B0] rounded-full animate-spin"></div>
        </div>
      </div>
    )
  }

  const validDiffs = data.filter(d => !isNaN(d.diff))
  const avgDiff = validDiffs.length > 0
    ? validDiffs.reduce((sum, d) => sum + d.diff, 0) / validDiffs.length
    : 0

  return (
    <div className="bg-white rounded-xl border border-slate-100 overflow-hidden">
      {/* 헤더 */}
      <div className="px-4 py-3 border-b border-slate-100">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-sky-500 to-sky-600 flex items-center justify-center shadow-md shadow-sky-500/20">
              <Target className="w-4 h-4 text-white" />
            </div>
            <div>
              <h3 className="text-sm font-semibold text-slate-900">카테고리별 결과</h3>
              <p className="text-[10px] text-slate-500">주요 형질 평균 비교</p>
            </div>
          </div>
          <div className={`px-2.5 py-1 rounded-lg text-xs font-bold border ${avgDiff >= 0
            ? 'bg-emerald-50 text-emerald-700 border-emerald-200'
            : 'bg-red-50 text-red-600 border-red-200'
            }`}>
            평균 {avgDiff > 0 ? '+' : ''}{avgDiff.toFixed(2)}σ
          </div>
        </div>
      </div>

      {/* 차트 */}
      <div className="p-5">
        <div className="bg-gradient-to-br from-slate-50 to-blue-50/30 rounded-xl p-4">
          <ResponsiveContainer width="100%" height={240}>
            <RadarChart data={data} margin={{ top: 30, right: 40, bottom: 30, left: 40 }}>
              <defs>
                <linearGradient id="radarGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#1482B0" stopOpacity={0.4} />
                  <stop offset="100%" stopColor="#1482B0" stopOpacity={0.1} />
                </linearGradient>
              </defs>
              <PolarGrid
                stroke="#cbd5e1"
                strokeWidth={1.5}
                strokeOpacity={0.5}
              />
              <PolarAngleAxis
                dataKey="trait"
                tick={{ fontSize: 13, fill: '#334155', fontWeight: 600 }}
                tickLine={false}
              />
              <PolarRadiusAxis
                angle={90}
                domain={[-1.5, 1.5]}
                tick={{ fontSize: 10, fill: '#64748b' }}
                tickCount={4}
                axisLine={false}
              />
              <Radar
                name="보은군 평균"
                dataKey={() => 0}
                stroke="#94a3b8"
                fill="none"
                strokeWidth={2}
                strokeDasharray="5 3"
                strokeOpacity={0.6}
              />
              <Radar
                name="내농장"
                dataKey="diff"
                stroke="#1482B0"
                fill="url(#radarGradient)"
                strokeWidth={3}
                dot={{
                  fill: '#fff',
                  strokeWidth: 3,
                  stroke: '#1482B0',
                  r: 6,
                  strokeOpacity: 1
                }}
              />
              <Tooltip
                content={({ active, payload }) => {
                  if (active && payload && payload.length) {
                    const item = payload[0]?.payload
                    const diff = item?.diff ?? 0
                    const myFarm = item?.myFarm ?? 0
                    const region = item?.region ?? 0

                    return (
                      <div className="bg-slate-900 px-4 py-3 rounded-xl text-sm shadow-xl border border-slate-700">
                        <p className="text-white font-bold mb-2">{item?.trait}</p>
                        <div className="space-y-1 text-slate-300 text-xs">
                          <p>내농장: <span className="text-[#1482B0] font-semibold">{myFarm > 0 ? '+' : ''}{myFarm}σ</span></p>
                          <p>보은군: <span className="text-slate-400">{region > 0 ? '+' : ''}{region}σ</span></p>
                        </div>
                        <div className={`mt-2 pt-2 border-t border-slate-700 font-bold ${diff >= 0.3 ? 'text-emerald-400' :
                          diff <= -0.3 ? 'text-amber-400' :
                            'text-slate-300'
                          }`}>
                          {diff >= 0.3 ? '▲' : diff <= -0.3 ? '▼' : '='} {diff > 0 ? '+' : ''}{diff.toFixed(2)}σ
                        </div>
                      </div>
                    )
                  }
                  return null
                }}
              />
            </RadarChart>
          </ResponsiveContainer>
        </div>

        {/* 범례 */}
        <div className="flex items-center justify-center gap-6 mt-4 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-5 h-0.5 bg-slate-400 opacity-60" style={{ borderTop: '2px dashed #94a3b8' }}></div>
            <span className="text-xs text-slate-600">보은군 평균</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded-full bg-white border-3 border-[#1482B0] shadow-sm"></div>
            <span className="text-xs text-slate-900 font-semibold">내 농장</span>
          </div>
        </div>

        {/* 형질별 수치 */}
        <div className="grid grid-cols-5 gap-2 mt-4 pt-4 border-t border-slate-200">
          {data.map((item, idx) => (
            <div key={idx} className="text-center">
              <p className="text-[10px] text-slate-500 mb-1 truncate font-medium">{item.trait}</p>
              <p className={`text-sm font-bold ${item.diff >= 0.3 ? 'text-emerald-600' :
                item.diff <= -0.3 ? 'text-amber-600' :
                  'text-slate-700'
                }`}>
                {item.diff > 0 ? '+' : ''}{item.diff.toFixed(1)}
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
