'use client'

import { ArrowUpRight, ArrowDownRight, TrendingUp, TrendingDown } from "lucide-react"
import { useEffect, useState } from "react"
import { apiClient } from "@/lib/api"

interface GenomeData {
  trait: string
  score: number
  type: string
}

interface GenomeStrengthsWeaknessesProps {
  farmNo?: number | null
}

export function GenomeStrengthsWeaknesses({ farmNo }: GenomeStrengthsWeaknessesProps) {
  const [allMetrics, setAllMetrics] = useState<GenomeData[]>([])
  const [loading, setLoading] = useState(true)

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

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

        const traitScores: GenomeData[] = []

        for (const trait of traits) {
          try {
            const rankingRequest = {
              filterOptions: { farmNo: farmNo },
              rankingOptions: {
                criteriaType: 'GENOME',
                traitConditions: [{ traitNm: trait.key, weight: 1.0 }]
              }
            }

            const response = await apiClient.post('/cow/ranking', rankingRequest)
            const rankingResult = response.data || response

            const scores = rankingResult.items?.map((item: any) => item.sortValue) || []
            const avgScore = scores.length > 0
              ? scores.reduce((sum: number, score: number) => sum + score, 0) / scores.length
              : 0

            traitScores.push({
              trait: trait.name,
              score: parseFloat(avgScore.toFixed(2)),
              type: '유전체'
            })
          } catch (error) {
            console.error(`[강점/약점] 형질 ${trait.name} 데이터 로드 실패:`, error)
          }
        }

        setAllMetrics(traitScores)
      } catch (error) {
        console.error('형질 점수 로드 실패:', error)
        setAllMetrics([])
      } finally {
        setLoading(false)
      }
    }

    fetchTraitScores()
  }, [farmNo])

  const strengths = [...allMetrics].sort((a, b) => b.score - a.score).slice(0, 3)
  const weaknesses = [...allMetrics].sort((a, b) => a.score - b.score).slice(0, 3)

  if (loading) {
    return (
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
        {[1, 2].map((i) => (
          <div key={i} className="bg-white rounded-xl border border-slate-100 p-4">
            <div className="flex items-center justify-center h-[140px]">
              <div className="w-6 h-6 border-2 border-slate-200 border-t-[#1482B0] rounded-full animate-spin"></div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      {/* 강점 */}
      <div
        className="bg-white rounded-xl border border-slate-100 overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-lg hover:-translate-y-1 group"
        onClick={() => window.location.href = '/dashboard/strengths-weaknesses'}
      >
        <div className="px-5 py-4 border-b border-slate-100 bg-gradient-to-r from-emerald-50 to-transparent">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-emerald-500 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/30">
                <TrendingUp className="w-5 h-5 text-white" />
              </div>
              <div>
                <h3 className="text-base font-bold text-slate-900">이 부분이 강해요</h3>
                <p className="text-xs text-slate-500 mt-0.5">보은군보다 우수한 형질</p>
              </div>
            </div>
            <span className="px-3 py-1 bg-emerald-100 text-emerald-700 rounded-lg text-xs font-bold border border-emerald-200 shadow-sm">TOP 3</span>
          </div>
        </div>
        <div className="p-5">
          {strengths.length === 0 ? (
            <div className="flex items-center justify-center py-8 text-xs text-slate-400">
              데이터가 없습니다.
            </div>
          ) : (
            <div className="space-y-3">
              {strengths.map((item, idx) => (
                <div
                  key={idx}
                  className="flex items-center justify-between p-4 bg-gradient-to-r from-emerald-50 to-transparent rounded-xl hover:from-emerald-100 hover:to-emerald-50 transition-all duration-200 border-2 border-emerald-100 group-hover:border-emerald-200 shadow-sm"
                >
                  <div className="flex items-center gap-3">
                    <span className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold shadow-md ${
                      idx === 0 ? 'bg-gradient-to-br from-emerald-500 to-emerald-600 text-white shadow-emerald-500/30' :
                      idx === 1 ? 'bg-emerald-200 text-emerald-800 border-2 border-emerald-300' :
                      'bg-emerald-100 text-emerald-700 border-2 border-emerald-200'
                    }`}>
                      {idx + 1}
                    </span>
                    <span className="text-sm font-bold text-slate-900">{item.trait}</span>
                  </div>
                  <div className="flex items-center gap-1 bg-white px-3 py-1.5 rounded-lg border border-emerald-200 shadow-sm">
                    <span className="text-lg font-bold text-emerald-600">
                      {item.score > 0 ? '+' : ''}{item.score}
                    </span>
                    <span className="text-xs text-emerald-500 font-semibold">σ</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 약점 */}
      <div
        className="bg-white rounded-xl border border-slate-100 overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-lg hover:-translate-y-1 group"
        onClick={() => window.location.href = '/dashboard/strengths-weaknesses'}
      >
        <div className="px-5 py-4 border-b border-slate-100 bg-gradient-to-r from-amber-50 to-transparent">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-amber-500 to-amber-600 flex items-center justify-center shadow-lg shadow-amber-500/30">
                <TrendingDown className="w-5 h-5 text-white" />
              </div>
              <div>
                <h3 className="text-base font-bold text-slate-900">더 좋아질 수 있어요</h3>
                <p className="text-xs text-slate-500 mt-0.5">개선하면 좋을 형질</p>
              </div>
            </div>
            <span className="px-3 py-1 bg-amber-100 text-amber-700 rounded-lg text-xs font-bold border border-amber-200 shadow-sm">BOTTOM 3</span>
          </div>
        </div>
        <div className="p-5">
          {weaknesses.length === 0 ? (
            <div className="flex items-center justify-center py-8 text-xs text-slate-400">
              데이터가 없습니다.
            </div>
          ) : (
            <div className="space-y-3">
              {weaknesses.map((item, idx) => (
                <div
                  key={idx}
                  className="flex items-center justify-between p-4 bg-gradient-to-r from-amber-50 to-transparent rounded-xl hover:from-amber-100 hover:to-amber-50 transition-all duration-200 border-2 border-amber-100 group-hover:border-amber-200 shadow-sm"
                >
                  <div className="flex items-center gap-3">
                    <span className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold shadow-md ${
                      idx === 0 ? 'bg-gradient-to-br from-amber-500 to-amber-600 text-white shadow-amber-500/30' :
                      idx === 1 ? 'bg-amber-200 text-amber-800 border-2 border-amber-300' :
                      'bg-amber-100 text-amber-700 border-2 border-amber-200'
                    }`}>
                      {idx + 1}
                    </span>
                    <span className="text-sm font-bold text-slate-900">{item.trait}</span>
                  </div>
                  <div className="flex items-center gap-1 bg-white px-3 py-1.5 rounded-lg border border-amber-200 shadow-sm">
                    <span className="text-lg font-bold text-amber-600">
                      {item.score > 0 ? '+' : ''}{item.score}
                    </span>
                    <span className="text-xs text-amber-500 font-semibold">σ</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
