"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, Trash2 } from "lucide-react"
import { useTransition } from "react"

import { Button } from "@/components/ui/button"
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 { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { ScrollArea } from "@/components/ui/scroll-area"

// 기존 서비스 함수 import
import { 
  getEsgEvaluationDetails, 
  createEsgEvaluationWithItemsEnhanced, 
  updateEsgEvaluationWithItems 
} from "../service" // 기존 서비스 파일 경로에 맞게 수정

import { EsgEvaluationsView } from "@/db/schema"

// 폼 스키마 정의
const evaluationFormSchema = z.object({
  serialNumber: z.string().min(1, "시리얼번호는 필수입니다"),
  category: z.string().min(1, "분류는 필수입니다"),
  inspectionItem: z.string().min(1, "점검항목은 필수입니다"),
  evaluationItems: z.array(
    z.object({
      evaluationItem: z.string().min(1, "평가항목은 필수입니다"),
      evaluationItemDescription: z.string().min(1, "평가항목 설명은 필수입니다"),
      answerOptions: z.array(
        z.object({
          answerText: z.string().min(1, "답변 내용은 필수입니다"),
          score: z.coerce.number().min(0, "점수는 0 이상이어야 합니다"),
        })
      ).min(1, "최소 1개의 답변 옵션이 필요합니다"),
    })
  ).min(1, "최소 1개의 평가항목이 필요합니다"),
})

type EvaluationFormData = z.infer<typeof evaluationFormSchema>

interface EsgEvaluationFormSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  evaluation: EsgEvaluationsView | null
  onSuccess: () => void
}

export function EsgEvaluationFormSheet({
  open,
  onOpenChange,
  evaluation,
  onSuccess,
}: EsgEvaluationFormSheetProps) {
  const [isPending, startTransition] = useTransition()
  const isEdit = !!evaluation

  const form = useForm<EvaluationFormData>({
    resolver: zodResolver(evaluationFormSchema),
    defaultValues: {
      serialNumber: "",
      category: "",
      inspectionItem: "",
      evaluationItems: [
        {
          evaluationItem: "",
          evaluationItemDescription: "",
          answerOptions: [
            { answerText: "", score: 0 },
            { answerText: "", score: 0 },
          ],
        },
      ],
    },
  })


  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "evaluationItems",
  })

  // 편집 모드일 때 기존 데이터 로드
  React.useEffect(() => {
    if (open && isEdit && evaluation) {
      // 기존 서비스 함수를 사용하여 상세 데이터 로드
      startTransition(async () => {
        try {
          const details = await getEsgEvaluationDetails(evaluation.id)
          console.log(details)
          
          if (details) {
            form.reset({
              serialNumber: details.serialNumber,
              category: details.category,
              inspectionItem: details.inspectionItem,
              evaluationItems: details.evaluationItems?.map((item) => ({
                evaluationItem: item.evaluationItem,
                evaluationItemDescription: item.evaluationItemDescription,
                answerOptions: item.answerOptions?.map((option) => ({
                  answerText: option.answerText,
                  score: parseFloat(option.score),
                })) || [],
              })) || [],
            })
          }
        } catch (error) {
          console.error('Error loading evaluation for edit:', error)
          toast.error(error instanceof Error ? error.message : '편집할 데이터를 불러오는데 실패했습니다.')
        }
      })
    } else if (open && !isEdit) {
      // 새 생성 모드
      form.reset({
        serialNumber: "",
        category: "",
        inspectionItem: "",
        evaluationItems: [
          {
            evaluationItem: "",
            evaluationItemDescription: "",
            answerOptions: [
              { answerText: "", score: 0 },
              { answerText: "", score: 0 },
            ],
          },
        ],
      })
    }
  }, [open, isEdit, evaluation, form])

  const onSubmit = async (data: EvaluationFormData) => {
    startTransition(async () => {
      try {
        // 폼 데이터를 서비스 함수에 맞는 형태로 변환
        const evaluationData = {
          serialNumber: data.serialNumber,
          category: data.category,
          inspectionItem: data.inspectionItem,
        }

        const items = data.evaluationItems.map(item => ({
          evaluationItem: item.evaluationItem,
          evaluationItemDescription: item.evaluationItemDescription,
          answerOptions: item.answerOptions.map(option => ({
            answerText: option.answerText,
            score: option.score,
          }))
        }))

        if (isEdit && evaluation) {
          // 수정 - 전체 평가표 수정
          await updateEsgEvaluationWithItems(evaluation.id, evaluationData, items)
          toast.success('평가표가 수정되었습니다.')
        } else {
          // 생성 - 평가표와 항목들 함께 생성
          await createEsgEvaluationWithItemsEnhanced(evaluationData, items)
          toast.success('평가표가 생성되었습니다.')
        }
        
        onSuccess()
        onOpenChange(false)
      } catch (error) {
        console.error('Error saving evaluation:', error)
        toast.error(
          error instanceof Error ? error.message : '저장 중 오류가 발생했습니다.'
        )
      }
    })
  }

  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 pb-6">
          <SheetTitle>
            {isEdit ? 'ESG 평가표 수정' : '새 ESG 평가표 생성'}
          </SheetTitle>
          <SheetDescription>
            {isEdit
              ? '평가표의 정보를 수정합니다.'
              : '새로운 ESG 평가표를 생성합니다.'}
          </SheetDescription>
        </SheetHeader>

        <Form {...form}>
          <form 
            onSubmit={form.handleSubmit(onSubmit)} 
            className="flex flex-col flex-1 min-h-0"
          >
            {/* 스크롤 가능한 콘텐츠 영역 */}
            <ScrollArea className="flex-1 pr-4">
              <div className="space-y-6 pb-6">
                {/* 기본 정보 */}
                <Card>
                  <CardHeader>
                    <CardTitle>기본 정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <FormField
                      control={form.control}
                      name="serialNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>시리얼번호</FormLabel>
                          <FormControl>
                            <Input placeholder="P-1" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="category"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>분류</FormLabel>
                          <FormControl>
                            <Input placeholder="정보공시" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="inspectionItem"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>점검항목</FormLabel>
                          <FormControl>
                          <Input placeholder="ESG 정보공시 형식" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>

                {/* 평가항목들 */}
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>평가항목들</CardTitle>
                        <CardDescription>
                          각 평가항목과 해당 답변 옵션들을 설정합니다.
                        </CardDescription>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          append({
                            evaluationItem: "",
                            evaluationItemDescription: "",
                            answerOptions: [
                              { answerText: "", score: 0 },
                              { answerText: "", score: 0 },
                            ],
                          })
                        }
                        disabled={isPending}
                      >
                        <Plus className="w-4 h-4 mr-2" />
                        항목 추가
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {fields.map((field, index) => (
                        <EvaluationItemForm
                          key={field.id}
                          index={index}
                          form={form}
                          onRemove={() => remove(index)}
                          canRemove={fields.length > 1}
                          disabled={isPending}
                        />
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </ScrollArea>

            {/* 고정 버튼 영역 */}
            <div className="flex-shrink-0 flex justify-end gap-2 pt-4 border-t bg-background">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isPending}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending
                  ? '저장 중...'
                  : isEdit
                  ? '수정하기'
                  : '생성하기'}
              </Button>
            </div>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}

// 평가항목 개별 폼 컴포넌트
interface EvaluationItemFormProps {
  index: number
  form: any
  onRemove: () => void
  canRemove: boolean
  disabled?: boolean
}

function EvaluationItemForm({
  index,
  form,
  onRemove,
  canRemove,
  disabled = false,
}: EvaluationItemFormProps) {
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: `evaluationItems.${index}.answerOptions`,
  })


  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">평가항목 {index + 1}</CardTitle>
          {canRemove && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onRemove}
              className="text-destructive hover:text-destructive"
              disabled={disabled}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <FormField
          control={form.control}
          name={`evaluationItems.${index}.evaluationItem`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>평가항목</FormLabel>
              <FormControl>
              <Input placeholder="평가항목을 입력해주세요..." {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name={`evaluationItems.${index}.evaluationItemDescription`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>평가항목 설명</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="평가할 항목에 대한 설명을 입력해주세요..."
                  {...field}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm font-medium">답변 옵션들</label>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => append({ answerText: "", score: 0 })}
              disabled={disabled}
            >
              <Plus className="w-4 h-4 mr-2" />
              옵션 추가
            </Button>
          </div>
          
          <div className="space-y-2">
            {fields.map((option, optionIndex) => (
              <div key={option.id} className="flex gap-2">
                <FormField
                  control={form.control}
                  name={`evaluationItems.${index}.answerOptions.${optionIndex}.answerText`}
                  render={({ field }) => (
                    <FormItem className="flex-1">
                      <FormControl>
                        <Input 
                          placeholder="답변 내용" 
                          {...field} 
                          disabled={disabled}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name={`evaluationItems.${index}.answerOptions.${optionIndex}.score`}
                  render={({ field }) => (
                    <FormItem className="w-24">
                      <FormControl>
                        <Input
                          type="number"
                          step="0.1"
                          placeholder="점수"
                          {...field}
                          disabled={disabled}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                {fields.length > 1 && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => remove(optionIndex)}
                    className="text-destructive hover:text-destructive"
                    disabled={disabled}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                )}
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}