"use client"

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

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from "@/components/ui/command"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { useParams } from "next/navigation"

import { createDocumentClassOptionItem, getProjectKindScheduleSetting } from "@/lib/docu-list-rule/document-class/service"
import { getProjectCode } from "@/lib/projects/service"

// API 응답 타입
interface ScheduleSetting {
  COL_NM: string
  DC_OBX_USE_YN: string
  PROJ_COL_NM: string
  PROJ_COL_NM_EN: string
  SCD_VIEW_MGNT: string
  USE_YN1: string
  USE_YN2: string
}

const createOptionSchema = z.object({
  optionCode: z.string().min(1, "옵션을 선택해주세요."),
  description: z.string().optional(),
})

type CreateOptionSchema = z.infer<typeof createOptionSchema>

interface DocumentClassOptionAddDialogProps {
  documentClassId: number
  onSuccess?: () => void
}

export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: DocumentClassOptionAddDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [comboboxOpen, setComboboxOpen] = React.useState(false)
  const [isPending, startTransition] = React.useTransition()
  const [scheduleSettings, setScheduleSettings] = React.useState<ScheduleSetting[]>([])
  const [isLoading, setIsLoading] = React.useState(false)
  const params = useParams()
  const projectId = Number(params?.projectId)

  const form = useForm<CreateOptionSchema>({
    resolver: zodResolver(createOptionSchema),
    defaultValues: {
      optionCode: "",
      description: "",
    },
  })

  // Dialog가 열릴 때 데이터 로드
  React.useEffect(() => {
    if (open && projectId) {
      loadScheduleSettings()
    }
  }, [open, projectId])

  const loadScheduleSettings = async () => {
    setIsLoading(true)
    try {
      // 먼저 projectId로 프로젝트 코드 가져오기
      const projectCode = await getProjectCode(projectId)
      
      if (!projectCode) {
        toast.error("프로젝트 코드를 찾을 수 없습니다.")
        return
      }

      // 프로젝트 코드로 일정 설정 가져오기
      const settings = await getProjectKindScheduleSetting(projectCode)
      setScheduleSettings(settings)
    } catch (error) {
      console.error("Error loading schedule settings:", error)
      toast.error("옵션 목록을 불러오는 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  const handleSubmit = (data: CreateOptionSchema) => {
    startTransition(async () => {
      try {
        const result = await createDocumentClassOptionItem({
          documentClassId,
          optionCode: data.optionCode,
          description: data.description,
        })

        if (result.success) {
          toast.success("옵션이 성공적으로 추가되었습니다.")
          setOpen(false)
          form.reset()
          onSuccess?.()
        } else {
          toast.error(`옵션 추가 실패: ${result.error}`)
        }
      } catch (error) {
        console.error("Create error:", error)
        toast.error("옵션 추가 중 오류가 발생했습니다.")
      }
    })
  }

  const handleCancel = () => {
    setOpen(false)
    form.reset()
  }

  const selectedOption = scheduleSettings.find(
    (setting) => setting.COL_NM === form.watch("optionCode")
  )

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          <Plus className="mr-2 h-4 w-4" />
          옵션 추가
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>옵션 추가</DialogTitle>
          <DialogDescription>
            새로운 Document Class 옵션을 추가합니다.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="optionCode"
              render={({ field }) => (
                <FormItem className="flex flex-col">
                  <FormLabel>옵션 선택</FormLabel>
                  <Popover open={comboboxOpen} onOpenChange={setComboboxOpen}>
                    <PopoverTrigger asChild>
                      <FormControl>
                        <Button
                          variant="outline"
                          role="combobox"
                          aria-expanded={comboboxOpen}
                          className={cn(
                            "w-full justify-between",
                            !field.value && "text-muted-foreground"
                          )}
                          disabled={isLoading}
                        >
                          {isLoading
                            ? "로딩 중..."
                            : selectedOption
                            ? `${selectedOption.COL_NM} - ${selectedOption.PROJ_COL_NM}`
                            : "옵션을 선택하세요"}
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </FormControl>
                    </PopoverTrigger>
                    <PopoverContent className="w-full p-0">
                      <Command>
                        <CommandInput placeholder="옵션 검색..." />
                        <CommandEmpty>
                          {isLoading ? "로딩 중..." : "검색 결과가 없습니다."}
                        </CommandEmpty>
                        <CommandGroup
                          className="max-h-[200px] overflow-auto"
                          onWheel={(e) => {
                            e.stopPropagation();
                            const target = e.currentTarget;
                            target.scrollTop += e.deltaY;
                          }}
                        >
                          {scheduleSettings.map((setting) => (
                            <CommandItem
                              key={setting.COL_NM}
                              value={`${setting.COL_NM} ${setting.PROJ_COL_NM}`}
                              onSelect={() => {
                                form.setValue("optionCode", setting.COL_NM, { shouldValidate: true })
                                form.setValue("description", setting.PROJ_COL_NM || "", { shouldValidate: true })
                                setComboboxOpen(false)
                              }}
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-4 w-4",
                                  field.value === setting.COL_NM
                                    ? "opacity-100"
                                    : "opacity-0"
                                )}
                              />
                              <div className="flex flex-col">
                                <span className="font-medium">{setting.COL_NM}</span>
                                <span className="text-sm text-muted-foreground">
                                  {setting.PROJ_COL_NM}
                                </span>
                              </div>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <Button type="button" variant="outline" onClick={handleCancel}>
                취소
              </Button>
              <Button type="submit" disabled={isPending || !form.formState.isValid}>
                추가
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}