'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { mptApi, MptDto } from "@/lib/api"
import { Activity, CheckCircle2, XCircle } from 'lucide-react'
import { CowNumberDisplay } from "@/components/common/cow-number-display"
import { CowDetail } from "@/types/cow.types"
import { GenomeRequestDto } from "@/lib/api"
import { MPT_REFERENCE_RANGES } from "@/constants/mpt-reference"

// 혈액화학검사 카테고리별 항목
const MPT_CATEGORIES = [
  { name: '에너지 대사', items: ['glucose', 'cholesterol', 'nefa', 'bcs'], color: 'bg-muted/50' },
  { name: '단백질 대사', items: ['totalProtein', 'albumin', 'globulin', 'agRatio', 'bun'], color: 'bg-muted/50' },
  { name: '간기능', items: ['ast', 'ggt', 'fattyLiverIdx'], color: 'bg-muted/50' },
  { name: '미네랄', items: ['calcium', 'phosphorus', 'caPRatio', 'magnesium'], color: 'bg-muted/50' },
  { name: '기타', items: ['creatinine'], color: 'bg-muted/50' },
]

// 측정값 상태 판정
function getMptValueStatus(key: string, value: number | null): 'normal' | 'warning' | 'danger' | 'unknown' {
  if (value === null || value === undefined) return 'unknown'
  const ref = MPT_REFERENCE_RANGES[key]
  if (!ref || ref.lowerLimit === null || ref.upperLimit === null) return 'unknown'
  if (value >= ref.lowerLimit && value <= ref.upperLimit) return 'normal'
  const margin = (ref.upperLimit - ref.lowerLimit) * 0.1
  if (value >= ref.lowerLimit - margin && value <= ref.upperLimit + margin) return 'warning'
  return 'danger'
}

interface MptTableProps {
  cowShortNo?: string
  cowNo?: string
  farmNo?: number
  cow?: CowDetail | null
  genomeRequest?: GenomeRequestDto | null
}

export function MptTable({ cowShortNo, cowNo, farmNo, cow, genomeRequest }: MptTableProps) {
  const [mptData, setMptData] = useState<MptDto[]>([])
  const [selectedMpt, setSelectedMpt] = useState<MptDto | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchMptData = async () => {
      if (!cowShortNo) return

      setLoading(true)
      try {
        const data = await mptApi.findByCowShortNo(cowShortNo)
        setMptData(data)
        if (data.length > 0) {
          setSelectedMpt(data[0])
        }
      } catch (error) {
        console.error('MPT 데이터 로드 실패:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchMptData()
  }, [cowShortNo])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <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>
    )
  }

  return (
    <div className="space-y-6">
      {/* 개체 정보 섹션 */}
      <h3 className="text-lg lg:text-xl font-bold text-foreground">개체 정보</h3>
      <Card className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
        <CardContent className="p-0">
          {/* 데스크탑: 가로 그리드 */}
          <div className="hidden lg:grid lg:grid-cols-4 divide-x divide-border">
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">개체번호</span>
              </div>
              <div className="px-5 py-4">
                <CowNumberDisplay cowId={cowNo || ''} variant="highlight" className="text-2xl font-bold text-foreground" />
              </div>
            </div>
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">생년월일</span>
              </div>
              <div className="px-5 py-4">
                <span className="text-2xl font-bold text-foreground">
                  {cow?.cowBirthDt ? new Date(cow.cowBirthDt).toLocaleDateString('ko-KR') : '-'}
                </span>
              </div>
            </div>
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">월령</span>
              </div>
              <div className="px-5 py-4">
                <span className="text-2xl font-bold text-foreground">
                  {cow?.cowBirthDt
                    ? `${Math.floor((new Date().getTime() - new Date(cow.cowBirthDt).getTime()) / (1000 * 60 * 60 * 24 * 30.44))}개월`
                    : '-'}
                </span>
              </div>
            </div>
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">성별</span>
              </div>
              <div className="px-5 py-4">
                <span className="text-2xl font-bold text-foreground">
                  {cow?.cowSex === 'F' ? '암' : cow?.cowSex === 'M' ? '수' : '-'}
                </span>
              </div>
            </div>
          </div>
          {/* 모바일: 좌우 배치 리스트 */}
          <div className="lg:hidden divide-y divide-border">
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">개체번호</span>
              <div className="flex-1 px-4 py-3.5">
                <CowNumberDisplay cowId={cowNo || ''} variant="highlight" className="text-base font-bold text-foreground" />
              </div>
            </div>
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">생년월일</span>
              <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                {cow?.cowBirthDt ? new Date(cow.cowBirthDt).toLocaleDateString('ko-KR') : '-'}
              </span>
            </div>
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">월령</span>
              <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                {cow?.cowBirthDt
                  ? `${Math.floor((new Date().getTime() - new Date(cow.cowBirthDt).getTime()) / (1000 * 60 * 60 * 24 * 30.44))}개월`
                  : '-'}
              </span>
            </div>
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">성별</span>
              <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                {cow?.cowSex === 'F' ? '암' : cow?.cowSex === 'M' ? '수' : '-'}
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 혈통정보 섹션 */}
      <h3 className="text-lg lg:text-xl font-bold text-foreground">혈통정보</h3>
      <Card className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
        <CardContent className="p-0">
          {/* 데스크탑: 가로 그리드 */}
          <div className="hidden lg:grid lg:grid-cols-2 divide-x divide-border">
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">부 KPN번호</span>
              </div>
              <div className="px-5 py-4 flex items-center justify-between gap-3">
                <span className="text-2xl font-bold text-foreground break-all">
                  {cow?.sireKpn && cow.sireKpn !== '0' ? cow.sireKpn : '-'}
                </span>
                {(() => {
                  const chipSireName = genomeRequest?.chipSireName
                  if (chipSireName === '일치') {
                    return (
                      <span className="flex items-center gap-1.5 bg-muted/50 text-primary-foreground text-sm font-semibold px-3 py-1.5 rounded-full shrink-0">
                        <CheckCircle2 className="w-4 h-4" />
                        <span>일치</span>
                      </span>
                    )
                  } else if (chipSireName && chipSireName !== '일치') {
                    return (
                      <span className="flex items-center gap-1.5 bg-red-500 text-white text-sm font-semibold px-3 py-1.5 rounded-full shrink-0">
                        <XCircle className="w-4 h-4" />
                        <span>불일치</span>
                      </span>
                    )
                  } else {
                    return null
                  }
                })()}
              </div>
            </div>
            <div>
              <div className="bg-muted/50 px-5 py-3 border-b border-border">
                <span className="text-base font-semibold text-muted-foreground">모 개체번호</span>
              </div>
              <div className="px-5 py-4 flex items-center justify-between gap-3">
                {cow?.damCowId && cow.damCowId !== '0' ? (
                  <CowNumberDisplay cowId={cow.damCowId} variant="highlight" className="text-2xl font-bold text-foreground" />
                ) : (
                  <span className="text-2xl font-bold text-foreground">-</span>
                )}
                {(() => {
                  const chipDamName = genomeRequest?.chipDamName
                  if (chipDamName === '일치') {
                    return (
                      <span className="flex items-center gap-1.5 bg-muted/50 text-primary-foreground text-sm font-semibold px-3 py-1.5 rounded-full shrink-0">
                        <CheckCircle2 className="w-4 h-4" />
                        <span>일치</span>
                      </span>
                    )
                  } else if (chipDamName === '불일치') {
                    return (
                      <span className="flex items-center gap-1.5 bg-red-500 text-white text-sm font-semibold px-3 py-1.5 rounded-full shrink-0">
                        <XCircle className="w-4 h-4" />
                        <span>불일치</span>
                      </span>
                    )
                  } else if (chipDamName === '이력제부재') {
                    return (
                      <span className="flex items-center gap-1.5 bg-amber-500 text-white text-sm font-semibold px-3 py-1.5 rounded-full shrink-0">
                        <XCircle className="w-4 h-4" />
                        <span>이력제부재</span>
                      </span>
                    )
                  } else {
                    return null
                  }
                })()}
              </div>
            </div>
          </div>
          {/* 모바일: 좌우 배치 리스트 */}
          <div className="lg:hidden divide-y divide-border">
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">부 KPN번호</span>
              <div className="flex-1 px-4 py-3.5 flex items-center justify-between gap-2">
                <span className="text-base font-bold text-foreground break-all">
                  {cow?.sireKpn && cow.sireKpn !== '0' ? cow.sireKpn : '-'}
                </span>
                {(() => {
                  const chipSireName = genomeRequest?.chipSireName
                  if (chipSireName === '일치') {
                    return (
                      <span className="flex items-center gap-1 bg-muted/50 text-primary-foreground text-xs font-semibold px-2 py-1 rounded-full shrink-0">
                        <CheckCircle2 className="w-3 h-3" />
                        <span>일치</span>
                      </span>
                    )
                  } else if (chipSireName && chipSireName !== '일치') {
                    return (
                      <span className="flex items-center gap-1 bg-red-500 text-white text-xs font-semibold px-2 py-1 rounded-full shrink-0">
                        <XCircle className="w-3 h-3" />
                        <span>불일치</span>
                      </span>
                    )
                  } else {
                    return null
                  }
                })()}
              </div>
            </div>
            <div className="flex items-center">
              <span className="w-28 shrink-0 bg-muted/50 px-4 py-3.5 text-base font-medium text-muted-foreground">모 개체번호</span>
              <div className="flex-1 px-4 py-3.5 flex items-center justify-between gap-2">
                {cow?.damCowId && cow.damCowId !== '0' ? (
                  <CowNumberDisplay cowId={cow.damCowId} variant="highlight" className="text-base font-bold text-foreground" />
                ) : (
                  <span className="text-base font-bold text-foreground">-</span>
                )}
                {(() => {
                  const chipDamName = genomeRequest?.chipDamName
                  if (chipDamName === '일치') {
                    return (
                      <span className="flex items-center gap-1 bg-muted/50 text-primary-foreground text-xs font-semibold px-2 py-1 rounded-full shrink-0">
                        <CheckCircle2 className="w-3 h-3" />
                        <span>일치</span>
                      </span>
                    )
                  } else if (chipDamName === '불일치') {
                    return (
                      <span className="flex items-center gap-1 bg-red-500 text-white text-xs font-semibold px-2 py-1 rounded-full shrink-0">
                        <XCircle className="w-3 h-3" />
                        <span>불일치</span>
                      </span>
                    )
                  } else if (chipDamName === '이력제부재') {
                    return (
                      <span className="flex items-center gap-1 bg-amber-500 text-white text-xs font-semibold px-2 py-1 rounded-full shrink-0">
                        <XCircle className="w-3 h-3" />
                        <span>이력제부재</span>
                      </span>
                    )
                  } else {
                    return null
                  }
                })()}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 검사 정보 */}
      {selectedMpt && (
        <>
          <h3 className="text-lg lg:text-xl font-bold text-foreground">검사 정보</h3>
          <Card className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
            <CardContent className="p-0">
              <div className="hidden lg:grid lg:grid-cols-4 divide-x divide-border">
                <div>
                  <div className="bg-muted/50 px-5 py-3 border-b border-border">
                    <span className="text-base font-semibold text-muted-foreground">검사일자</span>
                  </div>
                  <div className="px-5 py-4">
                    <span className="text-2xl font-bold text-foreground">
                      {selectedMpt.testDt ? new Date(selectedMpt.testDt).toLocaleDateString('ko-KR') : '-'}
                    </span>
                  </div>
                </div>
                <div>
                  <div className="bg-muted/50 px-5 py-3 border-b border-border">
                    <span className="text-base font-semibold text-muted-foreground">월령</span>
                  </div>
                  <div className="px-5 py-4">
                    <span className="text-2xl font-bold text-foreground">
                      {selectedMpt.monthAge ? `${selectedMpt.monthAge}개월` : '-'}
                    </span>
                  </div>
                </div>
                <div>
                  <div className="bg-muted/50 px-5 py-3 border-b border-border">
                    <span className="text-base font-semibold text-muted-foreground">산차</span>
                  </div>
                  <div className="px-5 py-4">
                    <span className="text-2xl font-bold text-foreground">
                      {selectedMpt.parity ? `${selectedMpt.parity}산차` : '-'}
                    </span>
                  </div>
                </div>
                <div>
                  <div className="bg-muted/50 px-5 py-3 border-b border-border">
                    <span className="text-base font-semibold text-muted-foreground">유량</span>
                  </div>
                  <div className="px-5 py-4">
                    <span className="text-2xl font-bold text-foreground">
                      {selectedMpt.milkYield ? `${selectedMpt.milkYield}kg` : '-'}
                    </span>
                  </div>
                </div>
              </div>
              {/* 모바일 */}
              <div className="lg:hidden divide-y divide-border">
                <div className="flex items-center">
                  <span className="w-24 shrink-0 bg-muted/50 px-4 py-3.5 text-sm font-medium text-muted-foreground">검사일자</span>
                  <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                    {selectedMpt.testDt ? new Date(selectedMpt.testDt).toLocaleDateString('ko-KR') : '-'}
                  </span>
                </div>
                <div className="flex items-center">
                  <span className="w-24 shrink-0 bg-muted/50 px-4 py-3.5 text-sm font-medium text-muted-foreground">월령</span>
                  <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                    {selectedMpt.monthAge ? `${selectedMpt.monthAge}개월` : '-'}
                  </span>
                </div>
                <div className="flex items-center">
                  <span className="w-24 shrink-0 bg-muted/50 px-4 py-3.5 text-sm font-medium text-muted-foreground">산차</span>
                  <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                    {selectedMpt.parity ? `${selectedMpt.parity}산차` : '-'}
                  </span>
                </div>
                <div className="flex items-center">
                  <span className="w-24 shrink-0 bg-muted/50 px-4 py-3.5 text-sm font-medium text-muted-foreground">유량</span>
                  <span className="flex-1 px-4 py-3.5 text-base font-bold text-foreground">
                    {selectedMpt.milkYield ? `${selectedMpt.milkYield}kg` : '-'}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        </>
      )}

      {/* 혈액화학검사 결과 테이블 */}
      <h3 className="text-lg lg:text-xl font-bold text-foreground">혈액화학검사 결과</h3>
      <Card className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground w-28">카테고리</th>
                  <th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">검사항목</th>
                  <th className="px-4 py-3 text-center text-sm font-semibold text-muted-foreground w-24">측정값</th>
                  <th className="px-4 py-3 text-center text-sm font-semibold text-muted-foreground w-20">하한값</th>
                  <th className="px-4 py-3 text-center text-sm font-semibold text-muted-foreground w-20">상한값</th>
                  <th className="px-4 py-3 text-center text-sm font-semibold text-muted-foreground w-20">단위</th>
                  <th className="px-4 py-3 text-center text-sm font-semibold text-muted-foreground w-20">상태</th>
                </tr>
              </thead>
              <tbody>
                {MPT_CATEGORIES.map((category) => (
                  category.items.map((itemKey, itemIdx) => {
                    const ref = MPT_REFERENCE_RANGES[itemKey]
                    const value = selectedMpt ? (selectedMpt[itemKey as keyof MptDto] as number | null) : null
                    const status = getMptValueStatus(itemKey, value)

                    return (
                      <tr key={itemKey} className="border-b border-border hover:bg-muted/30">
                        {itemIdx === 0 && (
                          <td
                            rowSpan={category.items.length}
                            className={`px-4 py-3 text-sm font-semibold text-foreground ${category.color} align-middle text-center`}
                          >
                            {category.name}
                          </td>
                        )}
                        <td className="px-4 py-3 text-sm font-medium text-foreground">{ref?.name || itemKey}</td>
                        <td className="px-4 py-3 text-center">
                          <span className={`text-lg font-bold ${
                            status === 'normal' ? 'text-green-600' :
                            status === 'warning' ? 'text-amber-600' :
                            status === 'danger' ? 'text-red-600' :
                            'text-muted-foreground'
                          }`}>
                            {value !== null && value !== undefined ? value.toFixed(2) : '-'}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-center text-sm text-muted-foreground">{ref?.lowerLimit ?? '-'}</td>
                        <td className="px-4 py-3 text-center text-sm text-muted-foreground">{ref?.upperLimit ?? '-'}</td>
                        <td className="px-4 py-3 text-center text-sm text-muted-foreground">{ref?.unit || '-'}</td>
                        <td className="px-4 py-3 text-center">
                          {value !== null && value !== undefined ? (
                            <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-semibold ${
                              status === 'normal' ? 'bg-green-100 text-green-700' :
                              status === 'warning' ? 'bg-amber-100 text-amber-700' :
                              status === 'danger' ? 'bg-red-100 text-red-700' :
                              'bg-slate-100 text-slate-500'
                            }`}>
                              {status === 'normal' ? '정상' :
                               status === 'warning' ? '주의' :
                               status === 'danger' ? '이상' : '-'}
                            </span>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </td>
                      </tr>
                    )
                  })
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 검사 이력 (여러 검사 결과가 있을 경우) */}
      {mptData.length > 1 && (
        <>
          <h3 className="text-lg lg:text-xl font-bold text-foreground">검사 이력</h3>
          <Card className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
            <CardContent className="p-4">
              <div className="flex flex-wrap gap-2">
                {mptData.map((mpt, idx) => (
                  <Button
                    key={mpt.pkMptNo}
                    variant={selectedMpt?.pkMptNo === mpt.pkMptNo ? "default" : "outline"}
                    size="sm"
                    onClick={() => setSelectedMpt(mpt)}
                  >
                    {mpt.testDt ? new Date(mpt.testDt).toLocaleDateString('ko-KR') : `검사 ${idx + 1}`}
                  </Button>
                ))}
              </div>
            </CardContent>
          </Card>
        </>
      )}

      {/* 데이터 없음 안내 */}
      {/* {!selectedMpt && (
        <Card className="bg-slate-50 border border-border rounded-2xl">
          <CardContent className="p-8 text-center">
            <Activity className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-foreground mb-2">혈액화학검사 데이터 없음</h3>
            <p className="text-sm text-muted-foreground">
              이 개체는 아직 혈액화학검사(MPT) 결과가 등록되지 않았습니다.
            </p>
          </CardContent>
        </Card>
      )} */}
    </div>
  )
}
