'use client'

import { AppSidebar } from "@/components/layout/app-sidebar"
import { SiteHeader } from "@/components/layout/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Trophy, ChevronLeft, TrendingUp, Award, Star } from "lucide-react"
import { useRouter } from "next/navigation"
import { AuthGuard } from "@/components/auth/auth-guard"

export default function TopCowsPage() {
  const router = useRouter()

  // 더미 데이터 - 실제로는 백엔드에서 가져와야 함
  const topCows = [
    {
      rank: 1,
      cowNo: '001122334401',
      name: 'KOR 001122334401',
      score: 85.2,
      grade: 'A',
      birthDate: '2021-03-15',
      age: '3년 8개월',
      lactationCount: 2,
      traits: {
        carcassWeight: 92,
        marbling: 88,
        eyeMuscleArea: 90,
        backfatThickness: 82,
        bodyConformation: 95
      },
      strengths: ['체형', '도체중', '등심단면적'],
      weaknesses: ['등지방두께'],
      recentPerformance: {
        carcassWeight: 485,
        marblingScore: 7,
        eyeMuscleArea: 95
      },
      recommendations: '체형이 매우 우수한 개체입니다. 등지방두께 개선을 위한 KPN 선택을 권장합니다.'
    },
    {
      rank: 2,
      cowNo: '001122334402',
      name: 'KOR 001122334402',
      score: 82.7,
      grade: 'A',
      birthDate: '2020-11-20',
      age: '4년 0개월',
      lactationCount: 3,
      traits: {
        carcassWeight: 88,
        marbling: 94,
        eyeMuscleArea: 86,
        backfatThickness: 85,
        bodyConformation: 90
      },
      strengths: ['근내지방도', '체형', '도체중'],
      weaknesses: ['등심단면적'],
      recentPerformance: {
        carcassWeight: 465,
        marblingScore: 8,
        eyeMuscleArea: 88
      },
      recommendations: '근내지방도가 탁월한 개체입니다. 등심단면적 개선을 위한 교배 전략이 필요합니다.'
    },
    {
      rank: 3,
      cowNo: '001122334403',
      name: 'KOR 001122334403',
      score: 79.1,
      grade: 'A',
      birthDate: '2021-05-10',
      age: '3년 6개월',
      lactationCount: 2,
      traits: {
        carcassWeight: 90,
        marbling: 85,
        eyeMuscleArea: 88,
        backfatThickness: 75,
        bodyConformation: 87
      },
      strengths: ['도체중', '등심단면적'],
      weaknesses: ['등지방두께', '체형'],
      recentPerformance: {
        carcassWeight: 495,
        marblingScore: 6,
        eyeMuscleArea: 92
      },
      recommendations: '도체중이 우수한 개체입니다. 등지방두께와 체형 개선에 집중할 필요가 있습니다.'
    },
    {
      rank: 4,
      cowNo: '001122334404',
      name: 'KOR 001122334404',
      score: 76.5,
      grade: 'A',
      birthDate: '2020-08-25',
      age: '4년 3개월',
      lactationCount: 3,
      traits: {
        carcassWeight: 84,
        marbling: 82,
        eyeMuscleArea: 85,
        backfatThickness: 90,
        bodyConformation: 88
      },
      strengths: ['등지방두께', '체형'],
      weaknesses: ['근내지방도'],
      recentPerformance: {
        carcassWeight: 455,
        marblingScore: 5,
        eyeMuscleArea: 87
      },
      recommendations: '등지방두께가 매우 우수한 개체입니다. 근내지방도 개선을 위한 KPN 선택이 필요합니다.'
    },
    {
      rank: 5,
      cowNo: '001122334405',
      name: 'KOR 001122334405',
      score: 73.8,
      grade: 'A',
      birthDate: '2021-01-18',
      age: '3년 10개월',
      lactationCount: 2,
      traits: {
        carcassWeight: 86,
        marbling: 80,
        eyeMuscleArea: 83,
        backfatThickness: 88,
        bodyConformation: 85
      },
      strengths: ['등지방두께', '도체중'],
      weaknesses: ['근내지방도', '등심단면적'],
      recentPerformance: {
        carcassWeight: 470,
        marblingScore: 5,
        eyeMuscleArea: 85
      },
      recommendations: '균형 잡힌 개체입니다. 근내지방도 향상을 위한 교배가 권장됩니다.'
    },
    {
      rank: 6,
      cowNo: '001122334406',
      name: 'KOR 001122334406',
      score: 71.2,
      grade: 'B',
      birthDate: '2020-12-05',
      age: '3년 11개월',
      lactationCount: 2,
      traits: {
        carcassWeight: 82,
        marbling: 78,
        eyeMuscleArea: 81,
        backfatThickness: 84,
        bodyConformation: 83
      },
      strengths: ['등지방두께', '도체중'],
      weaknesses: ['근내지방도', '체형'],
      recentPerformance: {
        carcassWeight: 445,
        marblingScore: 4,
        eyeMuscleArea: 82
      },
      recommendations: '전반적으로 평균 이상인 개체입니다. 근내지방도와 체형 개선이 필요합니다.'
    },
    {
      rank: 7,
      cowNo: '001122334407',
      name: 'KOR 001122334407',
      score: 68.9,
      grade: 'B',
      birthDate: '2021-06-22',
      age: '3년 5개월',
      lactationCount: 2,
      traits: {
        carcassWeight: 80,
        marbling: 76,
        eyeMuscleArea: 79,
        backfatThickness: 82,
        bodyConformation: 81
      },
      strengths: ['등지방두께'],
      weaknesses: ['근내지방도', '등심단면적', '체형'],
      recentPerformance: {
        carcassWeight: 430,
        marblingScore: 4,
        eyeMuscleArea: 80
      },
      recommendations: '개선 여지가 많은 개체입니다. 근내지방도와 체형 강화가 필요합니다.'
    },
    {
      rank: 8,
      cowNo: '001122334408',
      name: 'KOR 001122334408',
      score: 65.5,
      grade: 'B',
      birthDate: '2020-09-30',
      age: '4년 2개월',
      lactationCount: 3,
      traits: {
        carcassWeight: 78,
        marbling: 74,
        eyeMuscleArea: 77,
        backfatThickness: 80,
        bodyConformation: 79
      },
      strengths: ['등지방두께'],
      weaknesses: ['근내지방도', '등심단면적', '도체중', '체형'],
      recentPerformance: {
        carcassWeight: 415,
        marblingScore: 3,
        eyeMuscleArea: 78
      },
      recommendations: '전반적인 개선이 필요한 개체입니다. 종합적인 개량 전략을 수립하세요.'
    }
  ]

  return (
    <AuthGuard>
    <SidebarProvider>
      <AppSidebar />
      <SidebarInset>
        <SiteHeader />
        <div className="flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6 lg:p-8">
          {/* 헤더 */}
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => router.back()}
              className="h-8 w-8"
            >
              <ChevronLeft className="h-5 w-5" />
            </Button>
            <div className="flex-1">
              <h1 className="text-2xl font-bold tracking-tight">우수 개체 순위</h1>
              <p className="text-sm text-muted-foreground mt-1">
                유전체 점수 기준 전체 개체 순위
              </p>
            </div>
          </div>

          {/* 요약 카드 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card>
              <CardContent className="p-6">
                <div className="text-sm text-muted-foreground mb-1">전체 개체</div>
                <div className="text-3xl font-bold">{topCows.length}두</div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="text-sm text-muted-foreground mb-1">A등급</div>
                <div className="text-3xl font-bold text-blue-600">
                  {topCows.filter(cow => cow.grade === 'A').length}두
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="text-sm text-muted-foreground mb-1">평균 점수</div>
                <div className="text-3xl font-bold text-purple-600">
                  {(topCows.reduce((sum, cow) => sum + cow.score, 0) / topCows.length).toFixed(1)}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="text-sm text-muted-foreground mb-1">최고 점수</div>
                <div className="text-3xl font-bold text-emerald-600">
                  {Math.max(...topCows.map(cow => cow.score)).toFixed(1)}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 개체 상세 리스트 */}
          <div className="space-y-4">
            {topCows.map((cow, idx) => (
              <Card key={idx} className="overflow-hidden hover:shadow-lg transition-shadow">
                <CardHeader className="bg-gradient-to-r from-slate-50 to-blue-50/30 border-b">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-4">
                      <div className={`w-14 h-14 rounded-full flex items-center justify-center text-xl font-bold shadow-md ${
                        cow.rank === 1 ? 'bg-gradient-to-br from-yellow-400 to-yellow-500 text-white' :
                        cow.rank === 2 ? 'bg-gradient-to-br from-slate-300 to-slate-400 text-white' :
                        cow.rank === 3 ? 'bg-gradient-to-br from-amber-600 to-amber-700 text-white' :
                        'bg-slate-100 text-slate-700'
                      }`}>
                        {cow.rank}
                      </div>
                      <div>
                        <CardTitle className="text-xl flex items-center gap-2">
                          {cow.name}
                          <Badge className={
                            cow.grade === 'A' ? 'bg-blue-100 text-blue-700 border-blue-200' :
                            'bg-slate-100 text-slate-700 border-slate-200'
                          }>
                            {cow.grade}등급
                          </Badge>
                          {cow.rank <= 3 && (
                            <Trophy className="h-5 w-5 text-yellow-500" />
                          )}
                        </CardTitle>
                        <CardDescription className="mt-1">
                          개체번호: {cow.cowNo} · 나이: {cow.age} · 산차: {cow.lactationCount}산
                        </CardDescription>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-3xl font-bold text-blue-600">{cow.score}</div>
                      <div className="text-sm text-muted-foreground">점</div>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {/* 좌측: 형질 점수 */}
                    <div>
                      <h4 className="text-sm font-semibold text-slate-900 mb-3 flex items-center gap-2">
                        <Star className="h-4 w-4 text-blue-600" />
                        형질별 점수
                      </h4>
                      <div className="space-y-3">
                        {Object.entries(cow.traits).map(([trait, score]) => {
                          const traitNames: Record<string, string> = {
                            carcassWeight: '도체중',
                            marbling: '근내지방도',
                            eyeMuscleArea: '등심단면적',
                            backfatThickness: '등지방두께',
                            bodyConformation: '체형'
                          }
                          const getScoreColor = (score: number) => {
                            if (score >= 90) return 'bg-blue-600'
                            if (score >= 80) return 'bg-blue-500'
                            if (score >= 70) return 'bg-blue-400'
                            return 'bg-slate-400'
                          }
                          return (
                            <div key={trait} className="space-y-1">
                              <div className="flex justify-between text-sm">
                                <span className="text-slate-700">{traitNames[trait]}</span>
                                <span className="font-bold text-slate-900">{score}점</span>
                              </div>
                              <div className="w-full bg-slate-200 rounded-full h-2.5">
                                <div
                                  className={`${getScoreColor(score)} h-2.5 rounded-full transition-all`}
                                  style={{ width: `${score}%` }}
                                ></div>
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>

                    {/* 우측: 성능 데이터 및 분석 */}
                    <div className="space-y-4">
                      {/* 최근 성적 */}
                      <div>
                        <h4 className="text-sm font-semibold text-slate-900 mb-3 flex items-center gap-2">
                          <TrendingUp className="h-4 w-4 text-emerald-600" />
                          예상 도체 성적
                        </h4>
                        <div className="grid grid-cols-3 gap-3">
                          <div className="bg-emerald-50 p-3 rounded-lg border border-emerald-100">
                            <div className="text-xs text-emerald-700 mb-1">도체중</div>
                            <div className="text-lg font-bold text-emerald-600">
                              {cow.recentPerformance.carcassWeight}
                            </div>
                            <div className="text-xs text-emerald-600">kg</div>
                          </div>
                          <div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
                            <div className="text-xs text-blue-700 mb-1">근내지방</div>
                            <div className="text-lg font-bold text-blue-600">
                              {cow.recentPerformance.marblingScore}
                            </div>
                            <div className="text-xs text-blue-600">번</div>
                          </div>
                          <div className="bg-purple-50 p-3 rounded-lg border border-purple-100">
                            <div className="text-xs text-purple-700 mb-1">등심단면적</div>
                            <div className="text-lg font-bold text-purple-600">
                              {cow.recentPerformance.eyeMuscleArea}
                            </div>
                            <div className="text-xs text-purple-600">cm²</div>
                          </div>
                        </div>
                      </div>

                      {/* 강점/약점 */}
                      <div>
                        <h4 className="text-sm font-semibold text-slate-900 mb-2">강점 / 약점</h4>
                        <div className="space-y-2">
                          <div className="flex items-start gap-2">
                            <span className="text-xs text-emerald-700 font-semibold mt-0.5">강점:</span>
                            <div className="flex flex-wrap gap-1">
                              {cow.strengths.map((strength, i) => (
                                <Badge key={i} className="bg-emerald-100 text-emerald-700 border-emerald-200 text-xs">
                                  {strength}
                                </Badge>
                              ))}
                            </div>
                          </div>
                          <div className="flex items-start gap-2">
                            <span className="text-xs text-amber-700 font-semibold mt-0.5">약점:</span>
                            <div className="flex flex-wrap gap-1">
                              {cow.weaknesses.map((weakness, i) => (
                                <Badge key={i} className="bg-amber-100 text-amber-700 border-amber-200 text-xs">
                                  {weakness}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 권장사항 */}
                      <div className="bg-blue-50/50 p-3 rounded-lg border border-blue-100">
                        <h4 className="text-xs font-semibold text-blue-900 mb-1">💡 권장사항</h4>
                        <p className="text-xs text-blue-700 leading-relaxed">
                          {cow.recommendations}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* 하단 액션 버튼 */}
                  <div className="mt-6 pt-4 border-t flex gap-2">
                    <Button
                      variant="default"
                      onClick={() => router.push(`/cow/${cow.cowNo}`)}
                      className="flex-1"
                    >
                      개체 상세정보
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => router.push(`/dashboard/recommended-kpn?cowNo=${cow.cowNo}`)}
                      className="flex-1"
                    >
                      추천 KPN 보기
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
    </AuthGuard>
  )
}
