'use client'

import { IconTrendingDown, IconTrendingUp, IconMoodNeutral } from "@tabler/icons-react"
import { useEffect, useState } from "react"

import { Badge } from "@/components/ui/badge"
import {
  Card,
  CardAction,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/components/ui/card"
import { dashboardApi } from "@/lib/api"
import { FarmSummaryDto, FarmEvaluationDto } from "@/types/dashboard.types"

interface SectionCardsProps {
  farmNo: number
}

export function SectionCards({ farmNo }: SectionCardsProps) {
  const [summary, setSummary] = useState<FarmSummaryDto | null>(null)
  const [evaluation, setEvaluation] = useState<FarmEvaluationDto | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      if (!farmNo) {
        console.warn('farmNo가 없습니다.')
        setLoading(false)
        return
      }

      try {
        // 백엔드 API에서 실제 데이터 조회
        const [summaryData, evaluationData] = await Promise.all([
          dashboardApi.getFarmSummary(farmNo).catch(err => {
            console.error('농장 요약 조회 실패:', err)
            return null
          }),
          dashboardApi.getFarmEvaluation(farmNo).catch(err => {
            console.error('농장 평가 조회 실패:', err)
            return null
          }),
        ])

        setSummary(summaryData)
        setEvaluation(evaluationData)
      } catch (error) {
        console.error('대시보드 데이터 로드 실패:', error)

        // API 실패 시 기본값 설정
        setSummary({
          totalCows: 0,
          analysisComplete: 0,
        })
        setEvaluation(null)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [farmNo])

  if (loading) {
    return (
      <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs lg:px-6 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
        {[1, 2, 3, 4].map((i) => (
          <Card key={i} className="@container/card animate-pulse">
            <CardHeader>
              <CardDescription>로딩 중...</CardDescription>
              <CardTitle className="text-2xl font-semibold">--</CardTitle>
            </CardHeader>
          </Card>
        ))}
      </div>
    )
  }

  const totalCows = summary?.totalCows || 0
  const analysisComplete = summary?.analysisComplete || 0
  // 유전자 보유율 = (육질형 + 육량형) / 2
  const avgGeneScore = evaluation?.genePossession
    ? (evaluation.genePossession.meatQuality.averageRate + evaluation.genePossession.meatQuantity.averageRate) / 2
    : 0
  const avgGenomeScore = evaluation?.genomeScore || 0

  return (
    <div className="grid grid-cols-1 gap-5 px-4 lg:px-6 sm:grid-cols-2 xl:grid-cols-4">
      <Card className="shadow-sm hover:shadow-md transition-all duration-200 border-l-4 border-l-blue-500">
        <CardHeader className="pb-3">
          <CardDescription className="text-xs font-semibold uppercase tracking-wide">전체 개체 수</CardDescription>
          <CardTitle className="text-3xl font-bold text-foreground mt-2">{totalCows}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2 text-sm">
            <div className="h-2 w-2 rounded-full bg-green-500"></div>
            <p className="text-muted-foreground">
              분석 완료 <span className="font-semibold text-foreground">{analysisComplete}마리</span>
            </p>
          </div>
        </CardContent>
      </Card>

      <Card className="shadow-sm hover:shadow-md transition-all duration-200 border-l-4 border-l-amber-500">
        <CardHeader className="pb-3">
          <CardDescription className="text-xs font-semibold uppercase tracking-wide">유전자 보유율</CardDescription>
          <CardTitle className="text-3xl font-bold text-foreground mt-2">{avgGeneScore.toFixed(1)}%</CardTitle>
        </CardHeader>
        <CardContent>
          <Badge className={`${avgGeneScore >= 70 ? 'badge-gene-positive' : avgGeneScore >= 50 ? 'badge-gene-neutral' : 'badge-gene-negative'} flex items-center gap-1 w-fit`}>
            {avgGeneScore >= 70 ? <IconTrendingUp className="w-3 h-3" /> : avgGeneScore >= 50 ? <IconMoodNeutral className="w-3 h-3" /> : <IconTrendingDown className="w-3 h-3" />}
            {avgGeneScore >= 70 ? '우수' : avgGeneScore >= 50 ? '보통' : '개선필요'}
          </Badge>
          <p className="text-xs text-muted-foreground mt-2">
            {avgGeneScore >= 70 ? '우량 유전자 보유율 높음' : '유전자 개선 필요'}
          </p>
        </CardContent>
      </Card>

      <Card className="shadow-sm hover:shadow-md transition-all duration-200 border-l-4 border-l-cyan-500">
        <CardHeader className="pb-3">
          <CardDescription className="text-xs font-semibold uppercase tracking-wide">유전체 평균 점수</CardDescription>
          <CardTitle className="text-3xl font-bold text-foreground mt-2">{avgGenomeScore.toFixed(1)}</CardTitle>
        </CardHeader>
        <CardContent>
          <Badge className={`${avgGenomeScore >= 70 ? 'badge-gene-positive' : avgGenomeScore >= 50 ? 'badge-gene-neutral' : 'badge-gene-negative'} flex items-center gap-1 w-fit`}>
            {avgGenomeScore >= 70 ? <IconTrendingUp className="w-3 h-3" /> : avgGenomeScore >= 50 ? <IconMoodNeutral className="w-3 h-3" /> : <IconTrendingDown className="w-3 h-3" />}
            {avgGenomeScore >= 70 ? '우수' : avgGenomeScore >= 50 ? '보통' : '개선필요'}
          </Badge>
          <p className="text-xs text-muted-foreground mt-2">
            {avgGenomeScore >= 70 ? '육질/육량 형질 우수' : '형질 개선 필요'}
          </p>
        </CardContent>
      </Card>

      <Card className="@container/card">
        <CardHeader>
          <CardDescription>유전체 점수</CardDescription>
          <CardTitle className={`text-2xl font-semibold ${
            (evaluation?.genomeScore || 0) >= 70 ? 'text-green-600' :
            (evaluation?.genomeScore || 0) >= 60 ? 'text-blue-600' :
            (evaluation?.genomeScore || 0) >= 40 ? 'text-yellow-600' :
            'text-red-600'
          }`}>
            {evaluation?.genomeScore?.toFixed(1) || '-'}점
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Badge className={
            (evaluation?.genomeScore || 0) >= 70 ? 'bg-green-100 text-green-800' :
            (evaluation?.genomeScore || 0) >= 60 ? 'bg-blue-100 text-blue-800' :
            (evaluation?.genomeScore || 0) >= 40 ? 'bg-yellow-100 text-yellow-800' :
            'bg-red-100 text-red-800'
          }>
            {(evaluation?.genomeScore || 0) >= 60 ? <IconTrendingUp className="w-4 h-4" /> : <IconMoodNeutral className="w-4 h-4" />}
            {evaluation?.genomeRank || '-'}위
          </Badge>
          <p className="text-xs text-muted-foreground mt-2">
            보은군 내 순위 (유전체 기준)
          </p>
        </CardContent>
      </Card>
    </div>
  )
}
