"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { AdminSidebar } from "@/components/layout/admin-sidebar"
import { AdminHeader } from "@/components/layout/admin-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useAuthStore } from "@/store/auth-store"
import { AuthGuard } from "@/components/auth/auth-guard"
import {
  IconSearch,
  IconDownload,
  IconChartBar,
  IconUser,
  IconAlertCircle,
  IconFileText,
  IconEye,
} from "@tabler/icons-react"

// 농장주별 집계 데이터 타입
interface FarmOwnerData {
  farmOwner: string
  totalAnimals: number
  completedAnalysis: number
  animals: AnimalGenomeData[]
}

interface AnimalGenomeData {
  animalNo: string
  sire?: string
  dam?: string
  weight12m?: number
  carcassWeight?: number
  eyeMuscleArea?: number
  backfatThickness?: number
  marblingScore?: number
  traitsData?: {
    [key: string]: string | number | null
  }
}

// FarmOwnerData는 실제 API에서 가져올 예정이므로 MOCK_DATA 제거

function GenomeMappingContent() {
  const { user } = useAuthStore()
  const router = useRouter()
  const [searchQuery, setSearchQuery] = React.useState("")
  const [selectedFarmOwner, setSelectedFarmOwner] = React.useState<FarmOwnerData | null>(null)
  const [detailModalOpen, setDetailModalOpen] = React.useState(false)
  const [selectedAnimal, setSelectedAnimal] = React.useState<AnimalGenomeData | null>(null)
  const [farmOwnerData, setFarmOwnerData] = React.useState<FarmOwnerData[]>([])
  const [isLoading, setIsLoading] = React.useState(true)

  React.useEffect(() => {
    const isAdmin = user?.userRole === 'ADMIN'
    if (user && !isAdmin) {
      alert('관리자만 접근 가능합니다.')
      router.push('/dashboard')
    }
  }, [user, router])

  // 농장주별 집계 데이터 로드
  React.useEffect(() => {
    const fetchFarmOwnerData = async () => {
      try {
        setIsLoading(true)
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/genome/farm-owner-summary`)

        if (!response.ok) {
          throw new Error('데이터 조회에 실패했습니다.')
        }

        const data = await response.json()
        setFarmOwnerData(data)
      } catch (error) {
        console.error('데이터 로드 실패:', error)
        alert('데이터를 불러오는 중 오류가 발생했습니다.')
      } finally {
        setIsLoading(false)
      }
    }

    if (user) {
      fetchFarmOwnerData()
    }
  }, [user])

  const isAdmin = user?.userRole === 'ADMIN'
  if (!user || !isAdmin) {
    return null
  }

  // 검색 필터링
  const filteredData = farmOwnerData.filter((data) =>
    data.farmOwner.toLowerCase().includes(searchQuery.toLowerCase())
  )

  // 전체 통계
  const totalFarmOwners = farmOwnerData.length
  const totalAnimals = farmOwnerData.reduce((sum, data) => sum + data.totalAnimals, 0)
  const totalCompleted = farmOwnerData.reduce((sum, data) => sum + data.completedAnalysis, 0)
  const completionRate = totalAnimals > 0 ? ((totalCompleted / totalAnimals) * 100).toFixed(1) : '0.0'

  const handleViewDetails = (farmOwner: FarmOwnerData) => {
    setSelectedFarmOwner(farmOwner)
  }

  const handleViewAnimalDetail = (animal: AnimalGenomeData) => {
    setSelectedAnimal(animal)
    setDetailModalOpen(true)
  }

  const handleExportExcel = () => {
    // TODO: 엑셀 다운로드 구현
    alert('엑셀 다운로드 기능은 백엔드 API와 연동 후 구현됩니다.')
  }

  const handleExportFarmOwnerData = (farmOwner: string) => {
    // TODO: 농장주별 엑셀 다운로드
    alert(`${farmOwner}의 데이터를 다운로드합니다.`)
  }

  return (
    <SidebarInset>
      <AdminHeader
        breadcrumbs={[
          { label: "관리자", href: "/admin" },
          { label: "농장주별 집계" }
        ]}
      />

      <div className="flex flex-1 flex-col gap-2">
        <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
          {/* 헤더 */}
          <div className="px-4 lg:px-6">
            <div className="rounded-lg p-6 border" style={{ backgroundColor: '#3b82f610' }}>
              <h1 className="text-2xl font-bold mb-2">농장주별 유전체 데이터 집계</h1>
              <p className="text-sm text-muted-foreground">
                업로드된 데이터를 기반으로 농장주별 유전체 분석 결과를 조회합니다.
              </p>
            </div>
          </div>

          {/* 전체 통계 */}
          <div className="px-4 lg:px-6">
            <div className="grid gap-4 md:grid-cols-4">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">총 농장주 수</CardTitle>
                  <IconUser className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{totalFarmOwners}명</div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">총 개체 수</CardTitle>
                  <IconChartBar className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{totalAnimals}두</div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">분석 완료</CardTitle>
                  <IconFileText className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{totalCompleted}두</div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">완료율</CardTitle>
                  <IconChartBar className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{completionRate}%</div>
                </CardContent>
              </Card>
            </div>
          </div>

          {/* 검색 및 필터 */}
          <div className="px-4 lg:px-6">
            <Card>
              <CardHeader>
                <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                  <CardTitle>농장주 목록</CardTitle>
                  <div className="flex gap-2">
                    <div className="relative flex-1 md:flex-initial">
                      <IconSearch className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="농장주명 검색..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-9 w-full md:w-[200px]"
                      />
                    </div>
                    <Button onClick={handleExportExcel} variant="outline">
                      <IconDownload className="h-4 w-4 mr-2" />
                      전체 다운로드
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <div className="text-center py-12">
                    <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" />
                    <p className="mt-4 text-muted-foreground">데이터를 불러오는 중...</p>
                  </div>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>농장주명</TableHead>
                        <TableHead className="text-right">총 개체 수</TableHead>
                        <TableHead className="text-right">분석 완료</TableHead>
                        <TableHead className="text-right">미완료</TableHead>
                        <TableHead className="text-right">완료율</TableHead>
                        <TableHead className="text-right">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredData.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                            <IconAlertCircle className="h-8 w-8 mx-auto mb-2" />
                            <p>{farmOwnerData.length === 0 ? '업로드된 데이터가 없습니다.' : '검색 결과가 없습니다.'}</p>
                          </TableCell>
                        </TableRow>
                      ) : (
                      filteredData.map((data) => {
                        const pending = data.totalAnimals - data.completedAnalysis
                        const rate = ((data.completedAnalysis / data.totalAnimals) * 100).toFixed(1)
                        return (
                          <TableRow key={data.farmOwner}>
                            <TableCell className="font-medium">{data.farmOwner}</TableCell>
                            <TableCell className="text-right">{data.totalAnimals}두</TableCell>
                            <TableCell className="text-right">
                              <span className="text-green-600 font-semibold">
                                {data.completedAnalysis}두
                              </span>
                            </TableCell>
                            <TableCell className="text-right">
                              <span className={pending > 0 ? "text-orange-600" : "text-muted-foreground"}>
                                {pending}두
                              </span>
                            </TableCell>
                            <TableCell className="text-right">
                              <Badge
                                variant={parseFloat(rate) >= 90 ? "default" : "secondary"}
                              >
                                {rate}%
                              </Badge>
                            </TableCell>
                            <TableCell className="text-right">
                              <div className="flex justify-end gap-2">
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => handleViewDetails(data)}
                                >
                                  <IconEye className="h-4 w-4 mr-1" />
                                  상세보기
                                </Button>
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => handleExportFarmOwnerData(data.farmOwner)}
                                >
                                  <IconDownload className="h-4 w-4" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        )
                      })
                    )}
                    </TableBody>
                  </Table>
                )}
              </CardContent>
            </Card>
          </div>

          {/* 선택된 농장주 상세 정보 */}
          {selectedFarmOwner && (
            <div className="px-4 lg:px-6">
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle>{selectedFarmOwner.farmOwner}님의 개체 목록</CardTitle>
                      <CardDescription>
                        총 {selectedFarmOwner.animals.length}두의 유전체 분석 데이터
                      </CardDescription>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setSelectedFarmOwner(null)}
                    >
                      닫기
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  {selectedFarmOwner.animals.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground">
                      <IconAlertCircle className="h-8 w-8 mx-auto mb-2" />
                      <p>표시할 개체 데이터가 없습니다.</p>
                      <p className="text-xs mt-1">
                        실제 데이터는 백엔드 API와 연동 후 표시됩니다.
                      </p>
                    </div>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>개체번호</TableHead>
                          <TableHead>부</TableHead>
                          <TableHead>모</TableHead>
                          <TableHead className="text-right">12개월령체중</TableHead>
                          <TableHead className="text-right">도체중</TableHead>
                          <TableHead className="text-right">근내지방도</TableHead>
                          <TableHead className="text-right">작업</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {selectedFarmOwner.animals.map((animal) => (
                          <TableRow key={animal.animalNo}>
                            <TableCell className="font-medium">
                              {animal.animalNo}
                            </TableCell>
                            <TableCell>{animal.sire || '-'}</TableCell>
                            <TableCell>{animal.dam || '-'}</TableCell>
                            <TableCell className="text-right">
                              {animal.weight12m?.toFixed(1) || '-'}
                            </TableCell>
                            <TableCell className="text-right">
                              {animal.carcassWeight?.toFixed(1) || '-'}
                            </TableCell>
                            <TableCell className="text-right">
                              {animal.marblingScore?.toFixed(1) || '-'}
                            </TableCell>
                            <TableCell className="text-right">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleViewAnimalDetail(animal)}
                              >
                                <IconEye className="h-4 w-4" />
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  )}
                </CardContent>
              </Card>
            </div>
          )}
        </div>
      </div>

      {/* 개체 상세 정보 모달 */}
      <Dialog open={detailModalOpen} onOpenChange={setDetailModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>개체 상세 정보</DialogTitle>
            <DialogDescription>
              개체번호: {selectedAnimal?.animalNo}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {/* 기본 정보 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">부</p>
                <p className="font-semibold">{selectedAnimal?.sire || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">모</p>
                <p className="font-semibold">{selectedAnimal?.dam || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">12개월령체중</p>
                <p className="font-semibold">{selectedAnimal?.weight12m?.toFixed(1) || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">도체중</p>
                <p className="font-semibold">{selectedAnimal?.carcassWeight?.toFixed(1) || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">등심단면적</p>
                <p className="font-semibold">{selectedAnimal?.eyeMuscleArea?.toFixed(1) || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">등지방두께</p>
                <p className="font-semibold">{selectedAnimal?.backfatThickness?.toFixed(1) || '-'}</p>
              </div>
              <div className="border rounded-lg p-3">
                <p className="text-sm text-muted-foreground mb-1">근내지방도</p>
                <p className="font-semibold">{selectedAnimal?.marblingScore?.toFixed(1) || '-'}</p>
              </div>
            </div>

            {/* 전체 형질 데이터 (접을 수 있는 섹션) */}
            {selectedAnimal?.traitsData && Object.keys(selectedAnimal.traitsData).length > 0 && (
              <details className="border rounded-lg p-3">
                <summary className="cursor-pointer font-semibold text-sm">전체 형질 데이터 보기</summary>
                <div className="grid grid-cols-2 gap-4 mt-4">
                  {Object.entries(selectedAnimal.traitsData).map(([key, value]) => (
                    <div key={key} className="border-l-2 border-blue-500 pl-3 py-1">
                      <p className="text-xs text-muted-foreground mb-1">{key}</p>
                      <p className="text-sm font-medium">{value}</p>
                    </div>
                  ))}
                </div>
              </details>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </SidebarInset>
  )
}

export default function GenomeMappingPage() {
  return (
    <AuthGuard>
      <SidebarProvider>
        <AdminSidebar />
        <GenomeMappingContent />
      </SidebarProvider>
    </AuthGuard>
  )
}
