"use client"

import * as React from "react"
import { getMaterialDetail } from "../services"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"

import { formatDate } from "@/lib/utils"

interface MaterialDetailDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  matnr: string | null
}

export function MaterialDetailDialog({
  open,
  onOpenChange,
  matnr,
}: MaterialDetailDialogProps) {
  const [data, setData] = React.useState<Awaited<ReturnType<typeof getMaterialDetail>> | null>(null)
  const [loading, setLoading] = React.useState(false)

  React.useEffect(() => {
    if (open && matnr) {
      setLoading(true)
      getMaterialDetail(matnr)
        .then(setData)
        .finally(() => setLoading(false))
    }
  }, [open, matnr])

  if (!matnr) return null

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl h-[90vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>자재마스터 상세정보</DialogTitle>
          <DialogDescription>
            자재코드: {matnr}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="space-y-4 p-4">
            <Skeleton className="h-8 w-full" />
            <Skeleton className="h-32 w-full" />
            <Skeleton className="h-32 w-full" />
          </div>
        ) : data ? (
          <Tabs defaultValue="basic" className="w-full flex flex-col flex-1 min-h-0">
            <TabsList className="grid w-full grid-cols-5 flex-shrink-0">
              <TabsTrigger value="basic">기본정보</TabsTrigger>
              <TabsTrigger value="characteristics">특성할당</TabsTrigger>
              <TabsTrigger value="classifications">클래스할당</TabsTrigger>
              <TabsTrigger value="descriptions">설명</TabsTrigger>
              <TabsTrigger value="units">단위</TabsTrigger>
            </TabsList>

            <div className="flex-1 overflow-y-auto min-h-0 mt-4">

              <TabsContent value="basic" className="mt-0">
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-semibold mb-3">기본 자재 정보</h3>
                    <Table>
                      <TableBody>
                        <TableRow>
                          <TableCell className="font-medium w-1/4">자재코드 (MATNR)</TableCell>
                          <TableCell>{data.material.MATNR || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">자재명 (ZZNAME)</TableCell>
                          <TableCell>{data.material.ZZNAME || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">프로젝트 (ZZPJT)</TableCell>
                          <TableCell>{data.material.ZZPJT || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">구 자재번호 (BISMT)</TableCell>
                          <TableCell>{data.material.BISMT || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">자재그룹 (MATKL)</TableCell>
                          <TableCell>{data.material.MATKL || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">자재유형 (MTART)</TableCell>
                          <TableCell>{data.material.MTART || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">기본단위 (MEINS)</TableCell>
                          <TableCell>{data.material.MEINS || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">산업섹터 (MBRSH)</TableCell>
                          <TableCell>{data.material.MBRSH || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">사업부 (SPART)</TableCell>
                          <TableCell>{data.material.SPART || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">규격 (ZZSPEC)</TableCell>
                          <TableCell>{data.material.ZZSPEC || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">설명 (ZZDESC)</TableCell>
                          <TableCell>{data.material.ZZDESC || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">PLM ID (ZZPLMID)</TableCell>
                          <TableCell>{data.material.ZZPLMID || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">삭제플래그 (LVORM)</TableCell>
                          <TableCell>
                            {data.material.LVORM ? (
                              <Badge variant="destructive">삭제됨</Badge>
                            ) : (
                              <Badge variant="secondary">활성</Badge>
                            )}
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">자재상태 (MSTAE)</TableCell>
                          <TableCell>{data.material.MSTAE || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">총 중량 (BRGEW)</TableCell>
                          <TableCell>{data.material.BRGEW || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">순 중량 (NTGEW)</TableCell>
                          <TableCell>{data.material.NTGEW || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">중량단위 (GEWEI)</TableCell>
                          <TableCell>{data.material.GEWEI || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">크기/치수 (GROES)</TableCell>
                          <TableCell>{data.material.GROES || "-"}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">생성일시</TableCell>
                          <TableCell>{formatDate(data.material.createdAt, "KR")}</TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell className="font-medium">수정일시</TableCell>
                          <TableCell>{formatDate(data.material.updatedAt, "KR")}</TableCell>
                        </TableRow>
                      </TableBody>
                    </Table>
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="characteristics" className="mt-0">
                <div>
                  <h3 className="text-lg font-semibold mb-3">특성 할당 정보</h3>
                  {data.characteristics.length === 0 && (
                    <p className="text-muted-foreground mb-4">특성 할당 정보가 없습니다.</p>
                  )}
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>특성명 (ATNAM)</TableHead>
                        <TableHead>특성값 (ATWRT)</TableHead>
                        <TableHead>특성내역 (ATBEZ)</TableHead>
                        <TableHead>특성값내역 (ATWTB)</TableHead>
                        <TableHead>클래스번호 (CLASS)</TableHead>
                        <TableHead>클래스유형 (KLART)</TableHead>
                        <TableHead>측정단위 (ATAWE)</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.characteristics.length > 0 ? (
                        data.characteristics.map((char, index) => (
                          <TableRow key={index}>
                            <TableCell className="font-medium">{char.ATNAM || "-"}</TableCell>
                            <TableCell>{char.ATWRT || "-"}</TableCell>
                            <TableCell>{char.ATBEZ || "-"}</TableCell>
                            <TableCell>{char.ATWTB || "-"}</TableCell>
                            <TableCell>{char.CLASS || "-"}</TableCell>
                            <TableCell>{char.KLART || "-"}</TableCell>
                            <TableCell>{char.ATAWE || "-"}</TableCell>
                          </TableRow>
                        ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={7} className="text-center text-muted-foreground">
                            데이터가 없습니다
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              <TabsContent value="classifications" className="mt-0">
                <div>
                  <h3 className="text-lg font-semibold mb-3">클래스 할당 정보</h3>
                  {data.classifications.length === 0 && (
                    <p className="text-muted-foreground mb-4">클래스 할당 정보가 없습니다.</p>
                  )}
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>클래스번호 (CLASS)</TableHead>
                        <TableHead>클래스유형 (KLART)</TableHead>
                        <TableHead>생성일시</TableHead>
                        <TableHead>수정일시</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.classifications.length > 0 ? (
                        data.classifications.map((cls, index) => (
                          <TableRow key={index}>
                            <TableCell className="font-medium">{cls.CLASS || "-"}</TableCell>
                            <TableCell>{cls.KLART || "-"}</TableCell>
                            <TableCell>{formatDate(cls.createdAt, "KR")}</TableCell>
                            <TableCell>{formatDate(cls.updatedAt, "KR")}</TableCell>
                          </TableRow>
                        ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={4} className="text-center text-muted-foreground">
                            데이터가 없습니다
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              <TabsContent value="descriptions" className="mt-0">
                <div>
                  <h3 className="text-lg font-semibold mb-3">자재 설명 정보</h3>
                  {data.descriptions.length === 0 && (
                    <p className="text-muted-foreground mb-4">자재 설명 정보가 없습니다.</p>
                  )}
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>자재설명 (MAKTX)</TableHead>
                        <TableHead>언어 (SPRAS)</TableHead>
                        <TableHead>생성일시</TableHead>
                        <TableHead>수정일시</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.descriptions.length > 0 ? (
                        data.descriptions.map((desc, index) => (
                          <TableRow key={index}>
                            <TableCell className="font-medium">{desc.MAKTX || "-"}</TableCell>
                            <TableCell>{desc.SPRAS || "-"}</TableCell>
                            <TableCell>{formatDate(desc.createdAt, "KR")}</TableCell>
                            <TableCell>{formatDate(desc.updatedAt, "KR")}</TableCell>
                          </TableRow>
                        ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={4} className="text-center text-muted-foreground">
                            데이터가 없습니다
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              <TabsContent value="units" className="mt-0">
                <div>
                  <h3 className="text-lg font-semibold mb-3">단위 정보</h3>
                  {data.units.length === 0 && (
                    <p className="text-muted-foreground mb-4">단위 정보가 없습니다.</p>
                  )}
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>대체단위 (MEINH)</TableHead>
                        <TableHead>분모 (UMREN)</TableHead>
                        <TableHead>분자 (UMREZ)</TableHead>
                        <TableHead>길이 (LAENG)</TableHead>
                        <TableHead>폭 (BREIT)</TableHead>
                        <TableHead>높이 (HOEHE)</TableHead>
                        <TableHead>부피 (VOLUM)</TableHead>
                        <TableHead>부피단위 (VOLEH)</TableHead>
                        <TableHead>총중량 (BRGEW)</TableHead>
                        <TableHead>중량단위 (GEWEI)</TableHead>
                        <TableHead>치수단위 (MEABM)</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.units.length > 0 ? (
                        data.units.map((unit, index) => (
                          <TableRow key={index}>
                            <TableCell className="font-medium">{unit.MEINH || "-"}</TableCell>
                            <TableCell>{unit.UMREN || "-"}</TableCell>
                            <TableCell>{unit.UMREZ || "-"}</TableCell>
                            <TableCell>{unit.LAENG || "-"}</TableCell>
                            <TableCell>{unit.BREIT || "-"}</TableCell>
                            <TableCell>{unit.HOEHE || "-"}</TableCell>
                            <TableCell>{unit.VOLUM || "-"}</TableCell>
                            <TableCell>{unit.VOLEH || "-"}</TableCell>
                            <TableCell>{unit.BRGEW || "-"}</TableCell>
                            <TableCell>{unit.GEWEI || "-"}</TableCell>
                            <TableCell>{unit.MEABM || "-"}</TableCell>
                          </TableRow>
                        ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={11} className="text-center text-muted-foreground">
                            데이터가 없습니다
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>
            </div>
          </Tabs>
        ) : (
          <div className="text-center py-8">
            <p className="text-muted-foreground">데이터를 찾을 수 없습니다.</p>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}
