'use client'

import { PieChart as PieChartIcon } from "lucide-react"
import { useEffect, useState } from "react"
import { apiClient } from "@/lib/api"
import { ResponsiveContainer, PieChart, Pie, Cell, Tooltip } from 'recharts'

interface DistributionData {
  name: string
  value: number
  color: string
  range: string
  description: string
}

interface GenomeDistributionDonutProps {
  farmNo: number | null
}

export function GenomeDistributionDonut({ farmNo }: GenomeDistributionDonutProps) {
  const [data, setData] = useState<DistributionData[]>([])
  const [totalCount, setTotalCount] = useState(0)
  const [loading, setLoading] = useState(true)

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

      try {
        const response = await apiClient.post('/cow/ranking', {
          filterOptions: { farmNo },
          rankingOptions: {
            criteriaType: 'GENOME',
            traitConditions: [
              { traitNm: '도체중', weight: 0.25 },
              { traitNm: '근내지방도', weight: 0.25 },
              { traitNm: '등심단면적', weight: 0.25 },
              { traitNm: '등지방두께', weight: 0.25 },
            ]
          }
        })

        const result = response.data || response
        const items = result.items || []
        setTotalCount(items.length)

        const distribution = {
          top: 0,      // 0σ 이상
          middle: 0,   // -1.0σ ~ 0σ
          bottom: 0    // -1.0σ 이하
        }

        items.forEach((item: any) => {
          const score = item.sortValue || 0
          if (score >= 0) distribution.top++
          else if (score >= -1.0) distribution.middle++
          else distribution.bottom++
        })

        setData([
          { name: '우수', value: distribution.top, color: '#10b981', range: '0σ 이상', description: '평균보다 우수해요' },
          { name: '양호', value: distribution.middle, color: '#1482B0', range: '-1.0σ ~ 0σ', description: '평균 수준이에요' },
          { name: '개선필요', value: distribution.bottom, color: '#94a3b8', range: '-1.0σ 이하', description: '조금 더 신경써요' },
        ].filter(d => d.value > 0))

      } 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>
    )
  }

  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-violet-500 to-violet-600 flex items-center justify-center shadow-md shadow-violet-500/20">
              <PieChartIcon 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">총 {totalCount}두 분포</p>
            </div>
          </div>
          <span className="px-2 py-0.5 bg-slate-100 text-slate-600 rounded-lg text-[10px] font-semibold">{totalCount}두</span>
        </div>
      </div>

      {/* 차트 */}
      <div className="p-5">
        <div className="flex flex-col items-center">
          <div className="relative w-[180px] h-[180px]">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={data}
                  cx="50%"
                  cy="50%"
                  innerRadius={54}
                  outerRadius={86}
                  paddingAngle={3}
                  dataKey="value"
                >
                  {data.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} stroke="white" strokeWidth={2} />
                  ))}
                </Pie>
                <Tooltip
                  content={({ active, payload }) => {
                    if (active && payload && payload.length) {
                      const item = payload[0].payload
                      return (
                        <div className="bg-slate-900 px-4 py-3 rounded-xl shadow-xl border border-slate-700">
                          <p className="text-white font-bold mb-2">{item.name}</p>
                          <p className="text-slate-200 text-sm">{item.description}</p>
                          <div className="mt-2 pt-2 border-t border-slate-700">
                            <p className="text-slate-300 text-sm">{item.value}두 ({Math.round(item.value / totalCount * 100)}%)</p>
                            <p className="text-slate-400 text-xs mt-1">{item.range}</p>
                          </div>
                        </div>
                      )
                    }
                    return null
                  }}
                />
              </PieChart>
            </ResponsiveContainer>
            {/* 중앙 텍스트 */}
            <div className="absolute inset-0 flex flex-col items-center justify-center">
              <span className="text-3xl font-bold text-slate-900">{totalCount}</span>
              <span className="text-xs text-slate-500 mt-1">전체</span>
            </div>
          </div>

          {/* 범례 */}
          <div className="w-full mt-5 pt-4 border-t border-slate-100">
            <div className="space-y-2.5">
              {data.map((item, idx) => (
                <div key={idx} className="flex items-center justify-between p-3 bg-slate-50 rounded-lg border border-slate-100 hover:bg-slate-100/50 transition-colors">
                  <div className="flex items-center gap-3">
                    <div className="w-4 h-4 rounded-full flex-shrink-0 shadow-sm" style={{ backgroundColor: item.color }}></div>
                    <div className="flex flex-col">
                      <span className="text-sm font-semibold text-slate-900">{item.name}</span>
                      <span className="text-[10px] text-slate-500">{item.description}</span>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-base font-bold text-slate-900">{item.value}<span className="text-xs text-slate-500 font-normal ml-0.5">두</span></p>
                    <p className="text-[10px] text-slate-500">{Math.round(item.value / totalCount * 100)}%</p>
                  </div>
                </div>
              ))}
            </div>
            <p className="text-[10px] text-slate-400 mt-4 text-center leading-relaxed">
              σ(시그마)는 유전능력 수준을 나타내요<br/>
              0보다 클수록 우수해요
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
