"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import { z } from "zod"
import { toast } from "sonner"
import { Plus, X, GripVertical, Trash2 } from "lucide-react"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { ScrollArea } from "@/components/ui/scroll-area"

import { getEsgEvaluationDetails } from "../service"

interface EsgEvaluationDetailsSheetProps {
    open: boolean
    onOpenChange: (open: boolean) => void
    evaluationId: number | null
  }
  
  export function EsgEvaluationDetailsSheet({
    open,
    onOpenChange,
    evaluationId,
  }: EsgEvaluationDetailsSheetProps) {
    const [evaluation, setEvaluation] = React.useState<any>(null)
    const [isLoading, setIsLoading] = React.useState(false)

    console.log(evaluation)
  
    // 데이터 로드
    React.useEffect(() => {
      if (open && evaluationId) {
        setIsLoading(true)
        getEsgEvaluationDetails(evaluationId)
          .then(setEvaluation)
          .catch((error) => {
            console.error('Error loading evaluation details:', error)
            toast.error('평가표 상세 정보를 불러오는데 실패했습니다.')
          })
          .finally(() => setIsLoading(false))
      }
    }, [open, evaluationId])
  
    if (!open) return null
  
    return (
      <Sheet open={open} onOpenChange={onOpenChange}>
        <SheetContent className="w-[900px] sm:max-w-[900px] flex flex-col" style={{width:900, maxWidth:900}}>
          <SheetHeader className="flex-shrink-0">
            <SheetTitle>ESG 평가표 상세보기</SheetTitle>
            <SheetDescription>
              평가표의 상세 정보와 평가항목들을 확인합니다.
            </SheetDescription>
          </SheetHeader>
  
          {isLoading ? (
            <div className="flex items-center justify-center h-32">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
              <span className="ml-2">로딩 중...</span>
            </div>
          ) : evaluation ? (
            <div className="flex-1 overflow-y-auto px-1">
              <div className="space-y-6">
                {/* 기본 정보 */}
                <Card>
                  <CardHeader>
                    <CardTitle>기본 정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <label className="text-sm font-medium">시리얼번호</label>
                      <p className="text-sm text-muted-foreground">{evaluation.serialNumber}</p>
                    </div>
                    <div>
                      <label className="text-sm font-medium">분류</label>
                      <p className="text-sm text-muted-foreground">
                        <Badge variant="secondary">{evaluation.category}</Badge>
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium">점검항목</label>
                      <p className="text-sm text-muted-foreground">{evaluation.inspectionItem}</p>
                    </div>
                  </CardContent>
                </Card>
  
                {/* 평가항목들 */}
                <Card>
                  <CardHeader>
                    <CardTitle>평가항목들 ({evaluation.evaluationItems?.length || 0}개)</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {evaluation.evaluationItems?.length > 0 ? (
                      <Accordion type="multiple" className="w-full">
                        {evaluation.evaluationItems.map((item: any, index: number) => (
                          <AccordionItem key={item.id} value={`item-${item.id}`}>
                            <AccordionTrigger className="text-left">
                              <div className="flex items-center gap-2">
                                <Badge variant="outline">{index + 1}</Badge>
                                <span className="truncate">{item.evaluationItem}</span>
                              </div>
                            </AccordionTrigger>
                            <AccordionContent>
                              <div className="space-y-3">
                                <div className="text-sm text-muted-foreground">
                                  답변 옵션들 ({item.answerOptions?.length || 0}개)
                                </div>
                                {item.answerOptions?.map((option: any, optionIndex: number) => (
                                  <div
                                    key={option.id}
                                    className="flex items-center justify-between p-3 bg-muted/50 rounded-lg"
                                  >
                                    <div className="flex items-center gap-2">
                                      <Badge variant="default" className="text-xs">
                                        {optionIndex + 1}
                                      </Badge>
                                      <span className="text-sm">{option.answerText}</span>
                                    </div>
                                    <Badge variant="secondary">
                                    {Math.floor(Number(option.score))}점

                                    </Badge>
                                  </div>
                                ))}
                              </div>
                            </AccordionContent>
                          </AccordionItem>
                        ))}
                      </Accordion>
                    ) : (
                      <p className="text-sm text-muted-foreground text-center py-8">
                        등록된 평가항목이 없습니다.
                      </p>
                    )}
                  </CardContent>
                </Card>
              </div>
            </div>
          ) : (
            <div className="text-center text-muted-foreground py-8">
              평가표를 찾을 수 없습니다.
            </div>
          )}
        </SheetContent>
      </Sheet>
    )
  }