'use client'

import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { User, CheckCircle2, BarChart3 } from "lucide-react"
import { CowDetail } from "@/types/cow.types"
import { GenomeTrait as GenomeTraitType } from "@/types/genome.types"
import { ResponsiveContainer, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, Legend, Tooltip as RechartsTooltip } from 'recharts'

interface CowCompareModalProps {
  isOpen: boolean
  onClose: () => void
  compareCowsData: { cow: CowDetail; genome: GenomeTraitType[] }[]
  transformGenomeData: (genomeData: GenomeTraitType[]) => any[]
  CATEGORIES: string[]
  TRAIT_COLORS: string[]
}

export function CowCompareModal({
  isOpen,
  onClose,
  compareCowsData,
  transformGenomeData,
  CATEGORIES,
  TRAIT_COLORS
}: CowCompareModalProps) {
  if (!isOpen || compareCowsData.length === 0) return null

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white w-full max-w-6xl max-h-[90vh] rounded-lg overflow-hidden flex flex-col">
        {/* 헤더 */}
        <div className="p-4 border-b border-border flex items-center justify-between bg-primary/5">
          <div>
            <h2 className="text-lg font-bold flex items-center gap-2">
              <BarChart3 className="w-5 h-5 text-primary" />
              개체 유전체 비교
            </h2>
            <p className="text-sm text-muted-foreground mt-1">
              {compareCowsData.length}개 개체 비교
            </p>
          </div>
          <Button onClick={onClose} variant="ghost" size="sm">
            닫기
          </Button>
        </div>

        {/* 비교 내용 */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* 개체 카드들 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
            {compareCowsData.map((cowData, idx) => {
              const genomeTraits = transformGenomeData(cowData.genome)
              const avgBreedVal = genomeTraits.length > 0
                ? genomeTraits.reduce((sum: number, t: any) => sum + t.breedVal, 0) / genomeTraits.length
                : 0
              const avgPercentile = genomeTraits.length > 0
                ? genomeTraits.reduce((sum: number, t: any) => sum + t.percentile, 0) / genomeTraits.length
                : 0

              return (
                <Card key={cowData.cow.pkCowNo} className={idx === 0 ? 'border-2 border-primary' : ''}>
                  <CardHeader className={idx === 0 ? 'bg-primary/5' : ''}>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle className="text-base">{cowData.cow.cowId || cowData.cow.pkCowNo}</CardTitle>
                        {cowData.cow.cowId && (
                          <CardDescription>{cowData.cow.cowId}</CardDescription>
                        )}
                      </div>
                      {idx === 0 && (
                        <Badge className="bg-primary text-white">현재 개체</Badge>
                      )}
                    </div>
                  </CardHeader>
                  <CardContent className="pt-4">
                    <div className="space-y-3">
                      <div className="text-center p-3 bg-muted/30 rounded-lg">
                        <div className="text-xs text-muted-foreground mb-1">종합 육종가</div>
                        <div className="text-2xl font-bold text-primary">
                          {avgBreedVal > 0 ? '+' : ''}{avgBreedVal.toFixed(2)}σ
                        </div>
                        <div className="text-xs text-muted-foreground mt-1">
                          상위 {(100 - avgPercentile).toFixed(1)}%
                        </div>
                      </div>

                      <div className="text-xs space-y-1">
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">생년월일</span>
                          <span className="font-semibold">
                            {cowData.cow.cowBirthDt
                              ? new Date(cowData.cow.cowBirthDt).toLocaleDateString('ko-KR')
                              : 'N/A'}
                          </span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">나이</span>
                          <span className="font-semibold">
                            {cowData.cow.age ? `${cowData.cow.age}세` : 'N/A'}
                          </span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">평가 형질 수</span>
                          <span className="font-semibold">{genomeTraits.length}개</span>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            })}
          </div>

          {/* 카테고리별 비교 차트 */}
          <Card>
            <CardHeader>
              <CardTitle>카테고리별 육종가 비교</CardTitle>
              <CardDescription>각 개체의 카테고리별 평균 표준화육종가</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-96">
                <ResponsiveContainer width="100%" height="100%">
                  <RadarChart>
                    <PolarGrid stroke="#e2e8f0" />
                    <PolarAngleAxis
                      dataKey="category"
                      tick={{ fill: '#64748b', fontSize: 12 }}
                    />
                    <PolarRadiusAxis
                      angle={90}
                      domain={[-1, 2]}
                      tick={{ fill: '#64748b', fontSize: 10 }}
                    />
                    <RechartsTooltip />
                    <Legend />
                    {compareCowsData.map((cowData, idx) => {
                      const genomeTraits = transformGenomeData(cowData.genome)
                      const categoryData = CATEGORIES.map(cat => {
                        const traits = genomeTraits.filter((t: any) => t.category === cat)
                        const avgBreedVal = traits.length > 0
                          ? traits.reduce((sum: number, t: any) => sum + t.breedVal, 0) / traits.length
                          : 0
                        return {
                          category: cat,
                          value: avgBreedVal
                        }
                      })

                      const cowLabel = cowData.cow.cowId || String(cowData.cow.pkCowNo)
                      return (
                        <Radar
                          key={cowData.cow.pkCowNo}
                          name={idx === 0 ? `${cowLabel} (현재)` : cowLabel}
                          dataKey="value"
                          stroke={TRAIT_COLORS[idx % TRAIT_COLORS.length]}
                          fill={TRAIT_COLORS[idx % TRAIT_COLORS.length]}
                          fillOpacity={idx === 0 ? 0.6 : 0.3}
                          strokeWidth={idx === 0 ? 3 : 2}
                        />
                      )
                    })}
                  </RadarChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>

          {/* 형질별 비교 테이블 */}
          <Card className="mt-4">
            <CardHeader>
              <CardTitle>주요 형질 비교 (Top 10)</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-muted/50 border-b-2">
                    <tr>
                      <th className="px-3 py-2 text-left font-semibold sticky left-0 bg-muted/50">형질명</th>
                      {compareCowsData.map((cowData, idx) => {
                        const cowLabel = cowData.cow.cowId || String(cowData.cow.pkCowNo)
                        return (
                          <th key={cowData.cow.pkCowNo} className="px-3 py-2 text-center font-semibold">
                            {idx === 0 ? `${cowLabel}\n(현재)` : cowLabel}
                          </th>
                        )
                      })}
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {transformGenomeData(compareCowsData[0].genome).slice(0, 10).map((trait: any) => (
                      <tr key={trait.id} className="hover:bg-muted/30">
                        <td className="px-3 py-2 font-medium sticky left-0 bg-white">
                          {trait.name}
                        </td>
                        {compareCowsData.map((cowData) => {
                          const genomeTraits = transformGenomeData(cowData.genome)
                          const matchTrait = genomeTraits.find((t: any) => t.name === trait.name)
                          return (
                            <td key={cowData.cow.pkCowNo} className="px-3 py-2 text-center">
                              {matchTrait ? (
                                <div>
                                  <div className={`font-bold ${matchTrait.breedVal > 0 ? 'text-primary' : 'text-muted-foreground'}`}>
                                    {matchTrait.breedVal > 0 ? '+' : ''}{matchTrait.breedVal.toFixed(2)}σ
                                  </div>
                                  <div className="text-xs text-muted-foreground">
                                    {matchTrait.percentile.toFixed(1)}%
                                  </div>
                                </div>
                              ) : (
                                <span className="text-muted-foreground">N/A</span>
                              )}
                            </td>
                          )
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 푸터 */}
        <div className="p-4 border-t border-border bg-muted/30 flex justify-end">
          <Button onClick={onClose}>
            닫기
          </Button>
        </div>
      </div>
    </div>
  )
}
