'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { mptApi, MptDto, MptReferenceRange, MptCategory } from "@/lib/api/mpt.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/genome.api"

// 측정값 상태 판정: 안전(safe) / 주의(caution)
function getMptValueStatus(
  key: string,
  value: number | null,
  references: Record<string, MptReferenceRange>
): 'safe' | 'caution' | 'unknown' {
  if (value === null || value === undefined) return 'unknown'
  const ref = references[key]
  if (!ref || ref.lowerLimit === null || ref.upperLimit === null) return 'unknown'
  // 하한값 ~ 상한값 사이면 안전, 그 외 주의
  if (value >= ref.lowerLimit && value <= ref.upperLimit) return 'safe'
  return 'caution'
}

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)
  const [references, setReferences] = useState<Record<string, MptReferenceRange>>({})
  const [categories, setCategories] = useState<MptCategory[]>([])
  const [refLoading, setRefLoading] = useState(true)

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

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

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

    fetchMptData()
  }, [cowNo])

  if (loading || refLoading) {
    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-[1.5rem] 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-3 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">
                  {(() => {
                    const sex = cow?.cowSex?.toUpperCase?.() || cow?.cowSex
                    if (sex === 'F' || sex === '암' || sex === '2') return '암소'
                    if (sex === 'M' || sex === '수' || sex === '1') return '수소'
                    return '-'
                  })()}
                </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">
                {(() => {
                  const sex = cow?.cowSex?.toUpperCase?.() || cow?.cowSex
                  if (sex === 'F' || sex === '암' || sex === '2') return '암소'
                  if (sex === 'M' || sex === '수' || sex === '1') return '수소'
                  return '-'
                })()}
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 검사 정보 */}
      {selectedMpt && (
        <>
          <h3 className="text-lg lg:!text-[1.5rem] 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">
                      {cow?.cowBirthDt && selectedMpt.testDt
                        ? `${Math.floor((new Date(selectedMpt.testDt).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">
                      {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">
                    {cow?.cowBirthDt && selectedMpt.testDt
                      ? `${Math.floor((new Date(selectedMpt.testDt).getTime() - new Date(cow.cowBirthDt).getTime()) / (1000 * 60 * 60 * 24 * 30.44))}개월`
                      : '-'}
                  </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>
        </>
      )}

      {/* 혈액화학검사 결과 테이블 - selectedMpt가 있을 때만 표시 */}
      {selectedMpt ? (
      <>
      <h3 className="text-lg lg:!text-[1.5rem] font-bold text-foreground">혈액화학검사 결과</h3>

      {/* 데스크탑: 테이블 */}
      <Card className="hidden lg:block bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-[1.5rem]">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '12%' }}>카테고리</th>
                  <th className="px-4 py-3 text-left font-semibold text-muted-foreground" style={{ width: '18%' }}>검사항목</th>
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '15%' }}>측정값</th>
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '12%' }}>하한값</th>
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '12%' }}>상한값</th>
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '15%' }}>단위</th>
                  <th className="px-4 py-3 text-center font-semibold text-muted-foreground" style={{ width: '16%' }}>상태</th>
                </tr>
              </thead>
              <tbody>
                {categories.map((category) => (
                  category.items.map((itemKey, itemIdx) => {
                    const ref = references[itemKey]
                    const value = selectedMpt ? (selectedMpt[itemKey as keyof MptDto] as number | null) : null
                    const status = getMptValueStatus(itemKey, value, references)

                    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 font-semibold text-foreground ${category.color} align-middle text-center`}
                          >
                            {category.name}
                          </td>
                        )}
                        <td className="px-4 py-3 font-medium text-foreground">{ref?.name || itemKey}</td>
                        <td className="px-4 py-3 text-center">
                          <span className={`font-bold ${
                            status === 'safe' ? 'text-green-600' :
                            status === 'caution' ? 'text-amber-600' :
                            'text-muted-foreground'
                          }`}>
                            {value !== null && value !== undefined ? value.toFixed(2) : '-'}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-center text-muted-foreground">{ref?.lowerLimit ?? '-'}</td>
                        <td className="px-4 py-3 text-center text-muted-foreground">{ref?.upperLimit ?? '-'}</td>
                        <td className="px-4 py-3 text-center 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-4 py-1 rounded-full font-semibold ${
                              status === 'safe' ? 'bg-green-100 text-green-700' :
                              status === 'caution' ? 'bg-amber-100 text-amber-700' :
                              'bg-slate-100 text-slate-500'
                            }`}>
                              {status === 'safe' ? '안전' : status === 'caution' ? '주의' : '-'}
                            </span>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </td>
                      </tr>
                    )
                  })
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 모바일: 카드 레이아웃 */}
      <div className="lg:hidden space-y-4">
        {categories.map((category) => (
          <Card key={category.key} className="bg-white border border-border shadow-sm rounded-2xl overflow-hidden">
            <div className="bg-muted/50 px-4 py-3 border-b border-border">
              <span className="text-sm font-semibold text-foreground">{category.name}</span>
            </div>
            <CardContent className="p-0 divide-y divide-border">
              {category.items.map((itemKey) => {
                const ref = references[itemKey]
                const value = selectedMpt ? (selectedMpt[itemKey as keyof MptDto] as number | null) : null
                const status = getMptValueStatus(itemKey, value, references)

                return (
                  <div key={itemKey} className="py-2">
                    <div className="flex items-center border-b border-border/50">
                      <span className="w-20 shrink-0 bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">검사항목</span>
                      <span className="flex-1 px-3 py-2 text-sm font-semibold text-foreground">{ref?.name || itemKey}</span>
                    </div>
                    <div className="flex items-center border-b border-border/50">
                      <span className="w-20 shrink-0 bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">측정값</span>
                      <div className="flex-1 px-3 py-2 flex items-center justify-between">
                        <span className={`text-base font-bold ${
                          status === 'safe' ? 'text-green-600' :
                          status === 'caution' ? 'text-amber-600' :
                          'text-muted-foreground'
                        }`}>
                          {value !== null && value !== undefined ? value.toFixed(2) : '-'}
                        </span>
                        {value !== null && value !== undefined ? (
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${
                            status === 'safe' ? 'bg-green-100 text-green-700' :
                            status === 'caution' ? 'bg-amber-100 text-amber-700' :
                            'bg-slate-100 text-slate-500'
                          }`}>
                            {status === 'safe' ? '안전' : status === 'caution' ? '주의' : '-'}
                          </span>
                        ) : null}
                      </div>
                    </div>
                    <div className="flex items-center">
                      <span className="w-20 shrink-0 bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">참조범위</span>
                      <span className="flex-1 px-3 py-2 text-sm text-muted-foreground">
                        {ref?.lowerLimit ?? '-'} ~ {ref?.upperLimit ?? '-'} {ref?.unit || ''}
                      </span>
                    </div>
                  </div>
                )
              })}
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 검사 이력 (여러 검사 결과가 있을 경우) */}
      {mptData.length > 1 && (
        <>
          <h3 className="text-lg lg:text-xl font-bold text-foreground">검사 이력</h3>
          <Card className="inspt_hist 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>
        </>
      )}
      </>
      ) : (
        /* 데이터 없음 안내 */
        <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">
              이 개체는 번식능력검사를 진행하지 않아 분석보고서를 제공할 수 없습니다.
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
