'use client'

import { useEffect, useState } from "react"
import { useParams, useRouter, useSearchParams } from "next/navigation"
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 { Progress } from "@/components/ui/progress"
import { cowApi } from "@/lib/api/cow.api"
import { mptApi, MptDto, MptReferenceRange } from "@/lib/api/mpt.api"
import { CowDetail } from "@/types/cow.types"
import { Activity, AlertCircle, CheckCircle } from "lucide-react"
import { CowNavigation } from "../_components/navigation"
import { useToast } from "@/hooks/use-toast"
import { AuthGuard } from "@/components/auth/auth-guard"

// 측정값이 정상 범위 내인지 확인
function isWithinRange(
  value: number,
  itemKey: string,
  references: Record<string, MptReferenceRange>
): 'normal' | 'high' | 'low' | 'unknown' {
  const reference = references[itemKey]
  if (!reference || reference.upperLimit === null || reference.lowerLimit === null) {
    return 'unknown'
  }
  if (value > reference.upperLimit) return 'high'
  if (value < reference.lowerLimit) return 'low'
  return 'normal'
}

export default function ReproductionPage() {
  const params = useParams()
  const router = useRouter()
  const searchParams = useSearchParams()
  const cowNo = params.cowNo as string
  const from = searchParams.get('from')
  const { toast } = useToast()

  const [cow, setCow] = useState<CowDetail | null>(null)
  const [mptData, setMptData] = useState<MptDto[]>([])
  const [loading, setLoading] = useState(true)
  const [references, setReferences] = useState<Record<string, MptReferenceRange>>({})
  const [refLoading, setRefLoading] = useState(true)

  // 참조값 로드
  useEffect(() => {
    const loadReference = async () => {
      try {
        const data = await mptApi.getReferenceValues()
        setReferences(data.references)
      } catch (error) {
        console.error('MPT 참조값 로드 실패:', error)
      } finally {
        setRefLoading(false)
      }
    }
    loadReference()
  }, [])

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)

        // 개체 기본 정보
        const cowData = await cowApi.findOne(cowNo)
        const cowDetail: CowDetail = {
          ...cowData,
          age: cowData.cowBirthDt
            ? Math.floor((new Date().getTime() - new Date(cowData.cowBirthDt).getTime()) / (1000 * 60 * 60 * 24 * 365))
            : undefined,
        }
        setCow(cowDetail)

        // 암소인 경우만 MPT 정보 조회
        if (cowData.cowSex === 'F') {
          try {
            const data = await mptApi.findByCowId(cowNo)
            setMptData(data)
          } catch (err) {
            console.error('MPT 정보 조회 실패:', err)
          }
        }

      } catch (err) {
        console.error('번식 데이터 조회 실패:', err)
        toast({
          variant: "destructive",
          title: "데이터 로드 실패",
          description: "번식능력 정보를 불러올 수 없습니다",
        })
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [cowNo, toast])

  if (loading || refLoading || !cow) {
    return (
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          <div className="flex items-center justify-center h-96">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-muted-foreground">데이터를 불러오는 중...</p>
            </div>
          </div>
        </SidebarInset>
      </SidebarProvider>
    )
  }

  // 수소인 경우
  if (cow.cowSex !== 'F') {
    return (
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          {/* 탭 네비게이션 */}
          <div className="max-w-full lg:max-w-7xl xl:max-w-[1600px] 2xl:max-w-[1920px] mx-auto px-4 md:px-6 lg:px-12 xl:px-16 py-3">
            <CowNavigation cowNo={cowNo} />
          </div>

          <main className="flex-1 overflow-y-auto p-6">
            <div className="max-w-full lg:max-w-7xl xl:max-w-[1600px] 2xl:max-w-[1920px] mx-auto space-y-6">
              <div className="flex items-center gap-2 pb-2 border-b border-border">
                <Activity className="w-5 h-5 text-foreground" />
                <div>
                  <h2 className="text-lg font-bold text-foreground">번식능력</h2>
                  <p className="text-sm text-muted-foreground">번식 이력 및 MPT 혈액검사 결과</p>
                </div>
              </div>

              <Card>
                <CardContent className="pt-6 text-center">
                  <AlertCircle className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                  <p className="text-sm font-semibold mb-2">수소 개체</p>
                  <p className="text-xs text-muted-foreground">
                    번식능력 정보는 암소 개체만 확인할 수 있습니다
                  </p>
                </CardContent>
              </Card>
            </div>
          </main>
        </SidebarInset>
      </SidebarProvider>
    )
  }

  // MPT 데이터 정리
  const mptItems = mptData.length > 0 ? [
    { name: '혈당', value: mptData[0].glucose, fieldName: 'glucose' },
    { name: '콜레스테롤', value: mptData[0].cholesterol, fieldName: 'cholesterol' },
    { name: 'NEFA', value: mptData[0].nefa, fieldName: 'nefa' },
    { name: '알부민', value: mptData[0].albumin, fieldName: 'albumin' },
    { name: '총글로불린', value: mptData[0].globulin, fieldName: 'globulin' },
    { name: 'A/G', value: mptData[0].agRatio, fieldName: 'agRatio' },
    { name: '요소태질소(BUN)', value: mptData[0].bun, fieldName: 'bun' },
    { name: 'AST', value: mptData[0].ast, fieldName: 'ast' },
    { name: 'GGT', value: mptData[0].ggt, fieldName: 'ggt' },
    { name: '지방간 지수', value: mptData[0].fattyLiverIdx, fieldName: 'fattyLiverIdx' },
    { name: '칼슘', value: mptData[0].calcium, fieldName: 'calcium' },
    { name: '인', value: mptData[0].phosphorus, fieldName: 'phosphorus' },
    { name: '칼슘/인', value: mptData[0].caPRatio, fieldName: 'caPRatio' },
    { name: '마그네슘', value: mptData[0].magnesium, fieldName: 'magnesium' },
    { name: '크레아틴', value: mptData[0].creatine, fieldName: 'creatine' },
  ] : []

  const normalItems = mptItems.filter(item => {
    if (item.value === undefined || item.value === null) return false
    return isWithinRange(item.value, item.fieldName, references) === 'normal'
  })

  const healthScore = mptItems.length > 0 ? Math.round((normalItems.length / mptItems.length) * 100) : 0

  return (
    <AuthGuard>
    <SidebarProvider>
      <AppSidebar />
      <SidebarInset>
        <SiteHeader />
        {/* 탭 네비게이션 */}
        <div className="max-w-full lg:max-w-7xl xl:max-w-[1600px] 2xl:max-w-[1920px] mx-auto px-4 md:px-6 lg:px-12 xl:px-16 py-3">
          <CowNavigation cowNo={cowNo} />
        </div>

        <main className="flex-1 overflow-y-auto p-4 pb-12 md:p-6 md:pb-12 lg:px-12 lg:py-6 lg:pb-12 xl:px-16 xl:py-6 xl:pb-12">
          <div className="max-w-full lg:max-w-7xl xl:max-w-[1600px] 2xl:max-w-[1920px] mx-auto space-y-6">
            {/* 페이지 타이틀 */}
            <div className="flex items-center gap-2 pb-2 border-b border-border">
              <Activity className="w-5 h-5 text-foreground" />
              <div>
                <h2 className="text-lg font-bold text-foreground">번식능력</h2>
                <p className="text-sm text-muted-foreground">번식 이력 및 MPT 혈액검사 결과</p>
              </div>
            </div>

            {/* MPT 혈액검사 결과 */}
            {mptData.length > 0 ? (
              <>
                <Card>
                  <CardHeader>
                    <CardTitle>건강 점수</CardTitle>
                    <CardDescription>전체 MPT 항목 대비 정상 비율</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="text-4xl font-bold">{healthScore}점</div>
                          <div className="text-sm text-muted-foreground">
                            정상 {normalItems.length}개 / 전체 {mptItems.length}개
                          </div>
                        </div>
                        <div className={`text-5xl ${healthScore >= 80 ? 'text-green-500' : healthScore >= 60 ? 'text-yellow-500' : 'text-orange-500'}`}>
                          {healthScore >= 80 ? <CheckCircle /> : <AlertCircle />}
                        </div>
                      </div>
                      <Progress value={healthScore} className="h-3" />
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>MPT 혈액검사 상세</CardTitle>
                    <CardDescription>
                      검사일: {mptData[0].testDt
                        ? new Date(mptData[0].testDt).toLocaleDateString('ko-KR')
                        : '정보 없음'}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                      {mptItems.map((item, idx) => {
                        const isNormal = item.value !== undefined && item.value !== null && isWithinRange(item.value, item.fieldName, references) === 'normal'
                        const reference = references[item.fieldName]

                        return (
                          <div key={idx} className={`p-3 rounded-lg border ${isNormal ? 'bg-green-50 border-green-200' : 'bg-orange-50 border-orange-200'}`}>
                            <div className="text-xs font-medium text-muted-foreground mb-1">{item.name}</div>
                            <div className="text-lg font-bold">{item.value?.toFixed(2) || '-'}</div>
                            {reference && (
                              <div className="text-xs text-muted-foreground mt-1">
                                정상: {reference.lowerLimit} ~ {reference.upperLimit}
                              </div>
                            )}
                            <div className="mt-1">
                              {isNormal ? (
                                <Badge variant="default" className="text-xs">정상</Badge>
                              ) : (
                                <Badge variant="destructive" className="text-xs">주의</Badge>
                              )}
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </CardContent>
                </Card>
              </>
            ) : (
              <Card>
                <CardContent className="pt-6 text-center">
                  <AlertCircle className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                  <p className="text-sm font-semibold mb-2">MPT 검사 기록 없음</p>
                  <p className="text-xs text-muted-foreground">
                    혈액검사를 진행하여 건강 상태를 확인하세요
                  </p>
                </CardContent>
              </Card>
            )}
          </div>
        </main>
      </SidebarInset>
    </SidebarProvider>
    </AuthGuard>
  )
}
