"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandList,
  CommandGroup,
  CommandItem,
  CommandEmpty,
} from "@/components/ui/command"
import { Check, ChevronsUpDown, Loader, Plus, Info } from "lucide-react"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

import { createGtcClauseSchema, type CreateGtcClauseSchema } from "@/lib/gtc-contract/gtc-clauses/validations"
import { createGtcClause, getGtcClausesTree } from "@/lib/gtc-contract/gtc-clauses/service"
import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { useSession } from "next-auth/react"
import { MarkdownImageEditor } from "./markdown-image-editor"

interface ClauseImage {
  id: string
  url: string
  fileName: string
  size: number
}

interface CreateGtcClauseDialogProps {
  documentId: number
  document: any
  parentClause?: GtcClauseTreeView | null
  onSuccess?: () => void
  open?: boolean
  onOpenChange?: (open: boolean) => void
  showTrigger?: boolean
}

export function CreateGtcClauseDialog({ 
  documentId, 
  document, 
  parentClause = null,
  onSuccess,
  open: controlledOpen,
  onOpenChange: controlledOnOpenChange,
  showTrigger = true
}: CreateGtcClauseDialogProps) {
  const [internalOpen, setInternalOpen] = React.useState(false)
  
  // controlled vs uncontrolled 모드
  const isControlled = controlledOpen !== undefined
  const open = isControlled ? controlledOpen : internalOpen
  const setOpen = isControlled ? controlledOnOpenChange! : setInternalOpen
  const [parentClauses, setParentClauses] = React.useState<GtcClauseTreeView[]>([])
  const [isCreatePending, startCreateTransition] = React.useTransition()
  const { data: session } = useSession()
  
  // ✅ 이미지 상태 추가
  const [images, setImages] = React.useState<ClauseImage[]>([])

  const currentUserId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : null
  }, [session])

  React.useEffect(() => {
    if (open) {
      loadParentClauses()
    }
  }, [open, documentId])

  const loadParentClauses = async () => {
    try {
      const tree = await getGtcClausesTree(documentId)
      setParentClauses(flattenTree(tree))
    } catch (error) {
      console.error("Error loading parent clauses:", error)
    }
  }

  const form = useForm<CreateGtcClauseSchema>({
    resolver: zodResolver(createGtcClauseSchema),
    defaultValues: {
      documentId,
      parentId: parentClause?.id || null,
      itemNumber: "",
      category: "",
      subtitle: "",
      content: "",
      sortOrder: 0,
      editReason: "",
    },
  })

  // ✅ 이미지와 콘텐츠 변경 핸들러
  const handleContentImageChange = (content: string, newImages: ClauseImage[]) => {
    form.setValue("content", content)
    setImages(newImages)
  }

  async function onSubmit(data: CreateGtcClauseSchema) {
    startCreateTransition(async () => {
      if (!currentUserId) {
        toast.error("로그인이 필요합니다")
        return
      }

      try {
        // ✅ 이미지 데이터도 함께 전송
        const result = await createGtcClause({
          ...data,
          images: images, // 이미지 배열 추가
          createdById: currentUserId
        })
        
        if (result.error) {
          toast.error(`에러: ${result.error}`)
          return
        }

        form.reset()
        setImages([]) // ✅ 이미지 상태 초기화
        setOpen(false)
        toast.success("GTC 조항이 생성되었습니다.")
        onSuccess?.()
      } catch (error) {
        toast.error("조항 생성 중 오류가 발생했습니다.")
      }
    })
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
      setImages([]) // ✅ 다이얼로그 닫을 때 이미지 상태 초기화
    }
    setOpen(nextOpen)
  }

  const selectedParent = parentClauses.find(c => c.id === form.watch("parentId"))

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      {showTrigger && (
        <DialogTrigger asChild>
          <Button variant="default" size="sm">
            <Plus className="mr-2 h-4 w-4" />
            {parentClause ? "하위 조항 추가" : "조항 추가"}
          </Button>
        </DialogTrigger>
      )}

      <DialogContent className="max-w-4xl h-[90vh] flex flex-col"> {/* ✅ 너비 확장 */}
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>
            {parentClause ? "하위 조항 생성" : "새 조항 생성"}
          </DialogTitle>
          <DialogDescription>
            새 GTC 조항 정보를 입력하고 <b>Create</b> 버튼을 누르세요. 이미지를 포함할 수 있습니다.
          </DialogDescription>
        </DialogHeader>

        {/* 문서 정보 표시 */}
        <div className="p-3 bg-muted/50 rounded-lg text-sm flex-shrink-0">
          <div className="font-medium mb-1">문서 정보</div>
          <div className="text-muted-foreground space-y-1">
            <div>구분: {document?.type === "standard" ? "표준" : "프로젝트"}</div>
            {document?.project && (
              <div>프로젝트: {document.project.name} ({document.project.code})</div>
            )}
            <div>리비전: v{document?.revision}</div>
          </div>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 min-h-0">
            {/* 스크롤 가능한 폼 내용 영역 */}
            <div className="flex-1 overflow-y-auto px-1">
              <div className="space-y-4 py-4">
                {/* 부모 조항 선택 */}
                <FormField
                  control={form.control}
                  name="parentId"
                  render={({ field }) => {
                    const [popoverOpen, setPopoverOpen] = React.useState(false)

                    return (
                      <FormItem>
                        <FormLabel>부모 조항 (선택사항)</FormLabel>
                        <FormControl>
                          <Popover
                            open={popoverOpen}
                            onOpenChange={setPopoverOpen}
                            modal={true}
                          >
                            <PopoverTrigger asChild>
                              <Button
                                variant="outline"
                                role="combobox"
                                aria-expanded={popoverOpen}
                                className="w-full justify-between"
                              >
                                {selectedParent
                                  ? `${selectedParent.itemNumber} - ${selectedParent.subtitle}`
                                  : "부모 조항을 선택하세요... (최상위 조항인 경우 선택 안함)"}
                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                              </Button>
                            </PopoverTrigger>

                            <PopoverContent className="w-full p-0">
                              <Command>
                                <CommandInput
                                  placeholder="부모 조항 검색..."
                                  className="h-9"
                                />
                                <CommandList>
                                  <CommandEmpty>조항을 찾을 수 없습니다.</CommandEmpty>
                                  <CommandGroup>
                                    {/* 최상위 조항 옵션 */}
                                    <CommandItem
                                      value="none"
                                      onSelect={() => {
                                        field.onChange(null)
                                        setPopoverOpen(false)
                                      }}
                                    >
                                      최상위 조항
                                      <Check
                                        className={cn(
                                          "ml-auto h-4 w-4",
                                          !field.value ? "opacity-100" : "opacity-0"
                                        )}
                                      />
                                    </CommandItem>
                                    
                                    {parentClauses.map((clause) => {
                                      const label = `${clause.itemNumber} - ${clause.subtitle}`
                                      return (
                                        <CommandItem
                                          key={clause.id}
                                          value={label}
                                          onSelect={() => {
                                            field.onChange(clause.id)
                                            setPopoverOpen(false)
                                          }}
                                        >
                                          <div className="flex items-center w-full">
                                            <span style={{ marginLeft: `${clause.depth * 12}px` }}>
                                              {label}
                                            </span>
                                          </div>
                                          <Check
                                            className={cn(
                                              "ml-auto h-4 w-4",
                                              selectedParent?.id === clause.id
                                                ? "opacity-100" 
                                                : "opacity-0"
                                            )}
                                          />
                                        </CommandItem>
                                      )
                                    })}
                                  </CommandGroup>
                                </CommandList>
                              </Command>
                            </PopoverContent>
                          </Popover>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )
                  }}
                />

                {/* 채번 */}
                <FormField
                  control={form.control}
                  name="itemNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>채번 *</FormLabel>
                      <FormControl>
                        <Input 
                          placeholder="예: 1, 1.1, 2.3.1, A, B-1 등"
                          {...field} 
                        />
                      </FormControl>
                      <FormDescription>
                        조항의 번호입니다. 영문, 숫자, 점(.), 하이픈(-), 언더스코어(_)를 사용할 수 있습니다.
                      </FormDescription>
                      <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="subtitle"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>소제목 *</FormLabel>
                      <FormControl>
                        <Input 
                          placeholder="예: PREAMBLE, DEFINITIONS, GENERAL CONDITIONS 등"
                          {...field} 
                        />
                      </FormControl>
                      <FormDescription>
                        조항의 제목입니다. 문서에서 헤더로 표시됩니다.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* ✅ 상세항목 - MarkdownImageEditor 사용 */}
                <FormField
                  control={form.control}
                  name="content"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>상세항목 (선택사항)</FormLabel>
                      <FormControl>
                        <MarkdownImageEditor
                          content={field.value || ""}
                          images={images}
                          onChange={handleContentImageChange}
                          placeholder="조항의 상세 내용을 입력하세요... 이미지를 추가하려면 '이미지 추가' 버튼을 클릭하세요."
                          rows={8}
                        />
                      </FormControl>
                      <FormDescription>
                        조항의 실제 내용입니다. 텍스트와 이미지를 조합할 수 있으며, 하위 조항들을 그룹핑하는 제목용 조항인 경우 비워둘 수 있습니다.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* 편집 사유 */}
                <FormField
                  control={form.control}
                  name="editReason"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>편집 사유 (선택사항)</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="조항 생성 사유를 입력하세요..."
                          {...field}
                          rows={2}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* 고정된 푸터 */}
            <DialogFooter className="flex-shrink-0 border-t pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
                disabled={isCreatePending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isCreatePending}>
                {isCreatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                Create
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}

// 트리를 평면 배열로 변환하는 유틸리티 함수
function flattenTree(tree: any[]): any[] {
  const result: any[] = []
  
  function traverse(nodes: any[]) {
    for (const node of nodes) {
      result.push(node)
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    }
  }
  
  traverse(tree)
  return result
}