'use client'

import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { TrendingUp, TrendingDown, Minus, Users, Heart, Activity } from "lucide-react"
import { IconTrendingUp, IconTrendingDown, IconMoodNeutral } from "@tabler/icons-react"
import { useEffect, useState } from "react"
import { dashboardApi, breedApi, cowApi } from "@/lib/api"
import { FarmSummaryDto, FarmEvaluationDto } from "@/types/dashboard.types"
import { useAuthStore } from "@/store/auth-store"
import { useGlobalFilter } from "@/contexts/GlobalFilterContext"

interface KPIData {
  label: string
  value: string | number
  change: number
  changeLabel: string
  icon: React.ReactNode
  color: string
  badge?: React.ReactNode
  subtext?: string
}

interface KPIDashboardProps {
  farmNo: number
}

export function KPIDashboard({ farmNo }: KPIDashboardProps) {
  const { user } = useAuthStore()
  const { filters } = useGlobalFilter()
  const [kpiData, setKpiData] = useState<KPIData[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      // farmNo가 없으면 데이터 로드하지 않음
      if (!farmNo) {
        console.warn('farmNo가 없습니다.')
        setLoading(false)
        return
      }

      setLoading(true)
      try {
        // 필터를 백엔드 DTO 형식으로 변환
        const filterDto = {
          targetGenes: filters.selectedGenes?.length > 0 ? filters.selectedGenes : undefined,
          // 추후 필요시 다른 필터 추가 가능
        }

        // 실제 API 데이터 가져오기
        const [cows, evaluationData, breedSaves] = await Promise.all([
          cowApi.findByFarmNo(farmNo).catch(() => []),
          dashboardApi.getFarmEvaluation(farmNo, filterDto).catch(() => null),
          user
            ? breedApi.findByUser(user.pkUserNo).catch(() => [])
            : Promise.resolve([]),
        ])

        // 안전하게 데이터 추출
        const totalCows = Array.isArray(cows) ? cows.length : 0
        const analysisComplete = Array.isArray(cows)
          ? cows.filter((cow: any) => cow.genomeScore !== null && cow.genomeScore !== undefined).length
          : 0
        const avgGenomeScore = evaluationData?.genomeScore ?? 0
        const breedSaveCount = Array.isArray(breedSaves) ? breedSaves.length : 0

        // KPI 데이터 구성
        setKpiData([
          {
            label: "전체 개체 수",
            value: totalCows,
            change: 0,
            changeLabel: `분석 완료: ${analysisComplete}마리`,
            icon: <Users className="h-7 w-7" />,
            color: "blue",
            subtext: `분석 완료 ${analysisComplete}마리`
          },
          {
            label: "유전체 평균",
            value: avgGenomeScore.toFixed(1),
            change: avgGenomeScore >= 70 ? 4.8 : -1.5,
            changeLabel: avgGenomeScore >= 70 ? '육질/육량 형질 우수' : '형질 개선 필요',
            icon: <Activity className="h-7 w-7" />,
            color: "cyan",
            badge: avgGenomeScore >= 70 ? (
              <Badge className="badge-gene-positive flex items-center gap-1">
                <IconTrendingUp className="w-3 h-3" /> 우수
              </Badge>
            ) : avgGenomeScore >= 50 ? (
              <Badge className="badge-gene-neutral flex items-center gap-1">
                <IconMoodNeutral className="w-3 h-3" /> 보통
              </Badge>
            ) : (
              <Badge className="badge-gene-negative flex items-center gap-1">
                <IconTrendingDown className="w-3 h-3" /> 개선필요
              </Badge>
            )
          },
          {
            label: "교배계획 저장",
            value: breedSaveCount,
            change: 0,
            changeLabel: '저장된 교배 조합',
            icon: <Heart className="h-7 w-7" />,
            color: "pink"
          }
        ])
      } catch (error) {
        console.error('KPI 데이터 로드 실패:', error)
        console.error('에러 상세:', error instanceof Error ? error.message : '알 수 없는 에러')
        // 에러 시 기본값
        setKpiData([
          {
            label: "전체 개체 수",
            value: 0,
            change: 0,
            changeLabel: "데이터 없음",
            icon: <Users className="h-7 w-7" />,
            color: "blue"
          },
          {
            label: "유전체 평균",
            value: "0.0",
            change: 0,
            changeLabel: "데이터 없음",
            icon: <Activity className="h-7 w-7" />,
            color: "cyan"
          },
          {
            label: "교배계획 저장",
            value: 0,
            change: 0,
            changeLabel: "데이터 없음",
            icon: <Heart className="h-7 w-7" />,
            color: "pink"
          }
        ])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [farmNo, user, filters.selectedGenes])

  if (loading) {
    return (
      <>
        {[1, 2, 3].map((i) => (
          <Card key={i} className="bg-slate-50/50 border-0">
            <CardContent className="p-4 md:p-5">
              <div className="animate-pulse space-y-3">
                <div className="flex items-start justify-between">
                  <div className="h-4 w-24 bg-gray-200 rounded" />
                  <div className="h-5 w-12 bg-gray-200 rounded-full" />
                </div>
                <div className="space-y-2">
                  <div className="h-10 w-16 bg-gray-300 rounded" />
                  <div className="h-3 w-32 bg-gray-200 rounded" />
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </>
    )
  }

  const getColorClasses = (color: string) => {
    const colors = {
      blue: "bg-blue-50 text-blue-700 border-blue-200",
      cyan: "bg-cyan-50 text-cyan-700 border-cyan-200",
      pink: "bg-pink-50 text-pink-700 border-pink-200",
      orange: "bg-orange-50 text-orange-700 border-orange-200"
    }
    return colors[color as keyof typeof colors] || colors.blue
  }

  const getTrendIcon = (change: number) => {
    if (change > 0) return <TrendingUp className="h-4 w-4" />
    if (change < 0) return <TrendingDown className="h-4 w-4" />
    return <Minus className="h-4 w-4" />
  }

  const getTrendColor = (change: number) => {
    if (change > 0) return "text-green-600 bg-green-50"
    if (change < 0) return "text-red-600 bg-red-50"
    return "text-gray-600 bg-gray-50"
  }

  return (
    <>
      {kpiData.map((kpi, index) => (
        <Card key={index} className="bg-slate-50/50 border-0 hover:bg-slate-100/50 transition-colors">
          <CardContent className="p-4 md:p-5">
            <div className="flex items-start justify-between mb-3">
              <p className="text-sm md:text-sm text-gray-600 font-medium">{kpi.label}</p>
              {kpi.badge ? (
                <div>{kpi.badge}</div>
              ) : kpi.change !== 0 ? (
                <div className={`flex items-center gap-1 text-xs font-medium ${
                  kpi.change > 0 ? 'text-green-600' :
                  kpi.change < 0 ? 'text-red-600' :
                  'text-gray-600'
                }`}>
                  {getTrendIcon(kpi.change)}
                  <span>{Math.abs(kpi.change)}%</span>
                </div>
              ) : null}
            </div>

            <div className="space-y-2">
              <div className="flex items-baseline gap-2">
                <p className="text-3xl md:text-4xl font-bold tracking-tight">
                  {kpi.value}
                </p>
                {index === 0 && <span className="text-sm text-gray-500">두</span>}
              </div>

              {kpi.changeLabel && (
                <p className="text-xs md:text-sm text-gray-500 line-clamp-1">{kpi.changeLabel}</p>
              )}
            </div>
          </CardContent>
        </Card>
      ))}
    </>
  )
}
