"use client"

import * as React from "react"
import { useRouter, useParams } from "next/navigation"
import { useForm, useWatch, useFieldArray } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"
import { Loader2, ChevronsUpDown, Check, Plus, Trash2, Copy } from "lucide-react"

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 {
  Form,
  FormField,
  FormItem,
  FormControl,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandList,
  CommandGroup,
  CommandItem,
  CommandEmpty,
} from "@/components/ui/command"
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from "@/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { cn } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { useTranslation } from "@/i18n/client"

import type { CreateTagSchema } from "@/lib/tags/validations"
import { createTagSchema } from "@/lib/tags/validations"
import {
  createTag,
  getSubfieldsByTagType,
  getClassOptions,
  type ClassOption,
  TagTypeOption,
} from "@/lib/tags/service"
import { ScrollArea } from "@/components/ui/scroll-area"

// Updated to support multiple rows and subclass
interface MultiTagFormValues {
  class: string;
  tagType: string;
  subclass: string;  // 새로 추가된 서브클래스 필드
  rows: Array<{
    [key: string]: string;
    tagNo: string;
    description: string;
  }>;
}

// SubFieldDef for clarity
interface SubFieldDef {
  name: string
  label: string
  type: "select" | "text"
  options?: { value: string; label: string }[]
  expression?: string
  delimiter?: string
}

// 업데이트된 클래스 옵션 인터페이스 (서브클래스 정보 포함)
interface UpdatedClassOption extends ClassOption {
  tagTypeCode: string
  tagTypeDescription?: string
  subclasses: {
    id: string;
    desc: string;
  }[]  // 서브클래스 배열 추가
  subclassRemark: Record<string, string>  // 서브클래스 리마크 추가
}

interface AddTagDialogProps {
  selectedPackageId: number
}

export function AddTagDialog({ selectedPackageId }: AddTagDialogProps) {
  const router = useRouter()
  const params = useParams()
  const lng = (params?.lng as string) || "ko"
  const { t } = useTranslation(lng, "engineering")

  const [open, setOpen] = React.useState(false)
  const [tagTypeList, setTagTypeList] = React.useState<TagTypeOption[]>([])
  const [selectedTagTypeCode, setSelectedTagTypeCode] = React.useState<string | null>(null)
  const [selectedClassOption, setSelectedClassOption] = React.useState<UpdatedClassOption | null>(null)
  const [selectedSubclass, setSelectedSubclass] = React.useState<string>("")
  const [subFields, setSubFields] = React.useState<SubFieldDef[]>([])
  const [classOptions, setClassOptions] = React.useState<UpdatedClassOption[]>([])
  const [classSearchTerm, setClassSearchTerm] = React.useState("")
  const [isLoadingClasses, setIsLoadingClasses] = React.useState(false)
  const [isLoadingSubFields, setIsLoadingSubFields] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  // ID management
  const selectIdRef = React.useRef(0)
  const getUniqueSelectId = React.useCallback(() => `select-${selectIdRef.current++}`, [])
  const fieldIdsRef = React.useRef<Record<string, string>>({})
  const classOptionIdsRef = React.useRef<Record<string, string>>({})

  console.log(selectedPackageId, "tag")

  // ---------------
  // Load Class Options (서브클래스 정보 포함)
  // ---------------
  React.useEffect(() => {
    const loadClassOptions = async () => {
      setIsLoadingClasses(true)
      try {
        // getClassOptions 함수가 서브클래스 정보도 포함하도록 수정되었다고 가정
        const result = await getClassOptions(selectedPackageId)
        setClassOptions(result)
      } catch (err) {
        toast.error(t("toast.classOptionsLoadFailed"))
      } finally {
        setIsLoadingClasses(false)
      }
    }

    if (open) {
      loadClassOptions()
    }
  }, [open, selectedPackageId])

  // ---------------
  // react-hook-form with fieldArray support for multiple rows
  // ---------------
  const form = useForm<MultiTagFormValues>({
    defaultValues: {
      tagType: "",
      class: "",
      subclass: "",  // 서브클래스 필드 추가
      rows: [{
        tagNo: "",
        description: ""
      }]
    },
  })

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

  // ---------------
  // 서브클래스별로 필터링된 서브필드 로드
  // ---------------
  async function loadFilteredSubFieldsByTagTypeCode(tagTypeCode: string, subclassRemark: string, subclass: string) {
    setIsLoadingSubFields(true)
    try {
      // 수정된 getSubfieldsByTagType 함수 호출 (subclassRemark 파라미터 추가)
      const { subFields: apiSubFields } = await getSubfieldsByTagType(tagTypeCode, selectedPackageId, subclassRemark, subclass)
      const formattedSubFields: SubFieldDef[] = apiSubFields.map(field => ({
        name: field.name,
        label: field.label,
        type: field.type,
        options: field.options || [],
        expression: field.expression ?? undefined,
        delimiter: field.delimiter ?? undefined,
      }))
      setSubFields(formattedSubFields)

      // Initialize the rows with these subfields
      const currentRows = form.getValues("rows");
      const updatedRows = currentRows.map(row => {
        const newRow = { ...row };
        formattedSubFields.forEach(field => {
          if (!newRow[field.name]) {
            newRow[field.name] = "";
          }
        });
        return newRow;
      });

      form.setValue("rows", updatedRows);
      return true
    } catch (err) {
      toast.error(t("toast.subfieldsLoadFailed"))
      setSubFields([])
      return false
    } finally {
      setIsLoadingSubFields(false)
    }
  }

  // ---------------
  // Handle class selection
  // ---------------
  async function handleSelectClass(classOption: UpdatedClassOption) {
    form.setValue("class", classOption.label)
    form.setValue("subclass", "")  // 서브클래스 초기화
    setSelectedClassOption(classOption)
    setSelectedSubclass("")

    if (classOption.tagTypeCode) {
      setSelectedTagTypeCode(classOption.tagTypeCode)
      // If you have tagTypeList, you can find the label
      const tagType = tagTypeList.find(t => t.id === classOption.tagTypeCode)
      if (tagType) {
        form.setValue("tagType", tagType.label)
      } else if (classOption.tagTypeDescription) {
        form.setValue("tagType", classOption.tagTypeDescription)
      }

      // 서브클래스가 있으면 서브필드 로딩을 하지 않고 대기
      if (classOption.subclasses && classOption.subclasses.length > 0) {
        setSubFields([])  // 서브클래스 선택을 기다림
      } else {
        // 서브클래스가 없으면 바로 서브필드 로딩
        await loadFilteredSubFieldsByTagTypeCode(classOption.tagTypeCode, "", "")
      }
    }
  }

  // ---------------
  // Handle subclass selection
  // ---------------
  async function handleSelectSubclass(subclassCode: string) {
    if (!selectedClassOption || !selectedTagTypeCode) return

    setSelectedSubclass(subclassCode)
    form.setValue("subclass", subclassCode)

    // 선택된 서브클래스의 리마크 값 가져오기
    const subclassRemarkValue = selectedClassOption.subclassRemark[subclassCode] || ""

    // 리마크 값으로 필터링된 서브필드 로드
    await loadFilteredSubFieldsByTagTypeCode(selectedTagTypeCode, subclassRemarkValue, subclassCode)
  }

  // ---------------
  // Build TagNo from subfields automatically for each row
  // ---------------
  React.useEffect(() => {
    if (subFields.length === 0) {
      return;
    }

    const subscription = form.watch((value) => {
      if (!value.rows || subFields.length === 0) {
        return;
      }

      const rows = [...value.rows];
      rows.forEach((row, rowIndex) => {
        if (!row) return;

        let combined = "";
        subFields.forEach((sf, idx) => {
          const fieldValue = row[sf.name] || "";

          // delimiter를 앞에 붙이기 (첫 번째 필드가 아니고, 현재 필드에 값이 있고, delimiter가 있는 경우)
          if (idx > 0 && fieldValue && sf.delimiter) {
            combined += sf.delimiter;
          }

          combined += fieldValue;
        });

        const currentTagNo = form.getValues(`rows.${rowIndex}.tagNo`);
        if (currentTagNo !== combined) {
          form.setValue(`rows.${rowIndex}.tagNo`, combined, {
            shouldDirty: true,
            shouldTouch: true,
            shouldValidate: true,
          });
        }
      });
    });

    return () => subscription.unsubscribe();
  }, [subFields, form]);

  // ---------------
  // Check if tag numbers are valid
  // ---------------
  const areAllTagNosValid = React.useMemo(() => {
    const rows = form.getValues("rows");
    return rows.every(row => {
      const tagNo = row.tagNo;
      return tagNo && tagNo.trim() !== "" && !tagNo.includes("??");
    });
  }, [form.watch()]);

  // ---------------
  // Submit handler for multiple tags (서브클래스 정보 포함)
  // ---------------
  async function onSubmit(data: MultiTagFormValues) {
    if (!selectedPackageId) {
      toast.error(t("toast.noSelectedPackageId"));
      return;
    }

    setIsSubmitting(true);
    try {
      const successfulTags = [];
      const failedTags = [];

      // Process each row
      for (const row of data.rows) {
        // Create tag data from the row and shared class/tagType/subclass
        const tagData: CreateTagSchema = {
          tagType: data.tagType,
          class: data.class,
          // subclass: data.subclass,  // 서브클래스 정보 추가
          tagNo: row.tagNo,
          description: row.description,
          ...Object.fromEntries(
            subFields.map(field => [field.name, row[field.name] || ""])
          ),
          // Add any required default fields from the original form
          functionCode: row.functionCode || "",
          seqNumber: row.seqNumber || "",
          valveAcronym: row.valveAcronym || "",
          processUnit: row.processUnit || "",
        };

        try {
          const res = await createTag(tagData, selectedPackageId);
          if ("error" in res) {
            console.log(res.error)
            failedTags.push({ tag: row.tagNo, error: res.error });
          } else {
            successfulTags.push(row.tagNo);
          }
        } catch (err) {
          failedTags.push({ tag: row.tagNo, error: "Unknown error" });
        }
      }

      // Show results to the user
      if (successfulTags.length > 0) {
        toast.success(`${successfulTags.length}${t("toast.tagsCreatedSuccess")}`);
      }

      if (failedTags.length > 0) {
        console.log("Failed tags:", failedTags);
        toast.error(`${failedTags.length}${t("toast.tagsCreateFailed")}`);
      }

      // Refresh the page
      router.refresh();

      // Reset the form and close dialog if all successful
      if (failedTags.length === 0) {
        form.reset();
        setOpen(false);
      }
    } catch (err) {
      toast.error(t("toast.tagProcessingFailed"));
    } finally {
      setIsSubmitting(false);
    }
  }

  // ---------------
  // Add a new row
  // ---------------
  function addRow() {
    const newRow: {
      tagNo: string;
      description: string;
      [key: string]: string;
    } = {
      tagNo: "",
      description: ""
    };

    // Add all subfields with empty values
    subFields.forEach(field => {
      newRow[field.name] = "";
    });

    append(newRow);
    setTimeout(() => form.trigger(), 0);
  }

  // ---------------
  // Duplicate row
  // ---------------
  function duplicateRow(index: number) {
    const rowToDuplicate = form.getValues(`rows.${index}`);
    const newRow: {
      tagNo: string;
      description: string;
      [key: string]: string;
    } = { ...rowToDuplicate };

    newRow.tagNo = "";
    append(newRow);
    setTimeout(() => form.trigger(), 0);
  }

  // ---------------
  // Render Class field
  // ---------------
  function renderClassField(field: any) {
    const [popoverOpen, setPopoverOpen] = React.useState(false)

    const buttonId = React.useMemo(
      () => `class-button-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
      []
    )
    const popoverContentId = React.useMemo(
      () => `class-popover-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
      []
    )
    const commandId = React.useMemo(
      () => `class-command-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
      []
    )

    return (
      <FormItem className="w-1/3">
        <FormLabel>{t("labels.class")}</FormLabel>
        <FormControl>
          <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
            <PopoverTrigger asChild>
              <Button
                key={buttonId}
                type="button"
                variant="outline"
                className="w-full justify-between relative h-9"
                disabled={isLoadingClasses}
              >
                {isLoadingClasses ? (
                  <>
                    <span>{t("messages.loadingClasses")}</span>
                    <Loader2 className="ml-2 h-4 w-4 animate-spin" />
                  </>
                ) : (
                  <>
                    <span className="truncate mr-1 flex-grow text-left">
                      {field.value || t("placeholders.selectClass")}
                    </span>
                    <ChevronsUpDown className="h-4 w-4 opacity-50 flex-shrink-0" />
                  </>
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent key={popoverContentId} className="w-[300px] p-0"style={{width:480}}>
              <Command key={commandId}>
                <CommandInput
                  key={`${commandId}-input`}
                  placeholder={t("placeholders.searchClass")}
                  value={classSearchTerm}
                  onValueChange={setClassSearchTerm}
                />

                <CommandList key={`${commandId}-list`} className="max-h-[300px]" onWheel={(e) => {
                  e.stopPropagation(); // 이벤트 전파 차단
                  const target = e.currentTarget;
                  target.scrollTop += e.deltaY; // 직접 스크롤 처리
                }}>
                  <CommandEmpty key={`${commandId}-empty`}>{t("messages.noSearchResults")}</CommandEmpty>
                  <CommandGroup key={`${commandId}-group`}>
                    {classOptions.map((opt, optIndex) => {
                      if (!classOptionIdsRef.current[opt.code]) {
                        classOptionIdsRef.current[opt.code] =
                          `class-${opt.code}-${Date.now()}-${Math.random()
                            .toString(36)
                            .slice(2, 9)}`
                      }
                      const optionId = classOptionIdsRef.current[opt.code]

                      return (
                        <CommandItem
                          key={`${optionId}-${optIndex}`}
                          onSelect={() => {
                            field.onChange(opt.label)
                            setPopoverOpen(false)
                            handleSelectClass(opt)
                          }}
                          value={opt.label}
                          className="truncate"
                          title={opt.label}
                        >
                          <span className="truncate">{opt.label}</span>
                          <Check
                            key={`${optionId}-check`}
                            className={cn(
                              "ml-auto h-4 w-4 flex-shrink-0",
                              field.value === opt.label ? "opacity-100" : "opacity-0"
                            )}
                          />
                        </CommandItem>
                      )
                    })}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>
        </FormControl>
        <FormMessage />
      </FormItem>
    )
  }

  // ---------------
  // Render Subclass field (새로 추가)
  // ---------------
  function renderSubclassField(field: any) {
    const hasSubclasses = selectedClassOption?.subclasses && selectedClassOption.subclasses.length > 0

    if (!hasSubclasses) {
      return null
    }

    return (
      <FormItem className="w-1/3">
        <FormLabel>Subclass</FormLabel>
        <FormControl>
          <Select
            value={field.value || ""}
            onValueChange={(value) => {
              field.onChange(value)
              handleSelectSubclass(value)
            }}
            disabled={!selectedClassOption}
          >
            <SelectTrigger className="h-9">
                                    <SelectValue placeholder={t("placeholders.selectSubclass")} />
            </SelectTrigger>
            <SelectContent>
              {selectedClassOption?.subclasses.map((subclass) => (
                <SelectItem key={subclass.id} value={subclass.id}>
                  {subclass.desc}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </FormControl>
        <FormMessage />
      </FormItem>
    )
  }

  // ---------------
  // Render TagType field (readonly after class selection)
  // ---------------
  function renderTagTypeField(field: any) {
    const isReadOnly = !!selectedTagTypeCode
    const inputId = React.useMemo(
      () =>
        `tag-type-input-${isReadOnly ? "readonly" : "editable"}-${Date.now()}-${Math.random()
          .toString(36)
          .slice(2, 9)}`,
      [isReadOnly]
    )

    const width = selectedClassOption?.subclasses && selectedClassOption.subclasses.length > 0 ? "w-1/3" : "w-2/3"

    return (
      <FormItem className={width}>
        <FormLabel>{t("labels.tagType")}</FormLabel>
        <FormControl>
          {isReadOnly ? (
            <div className="relative">
              <Input
                key={`tag-type-readonly-${inputId}`}
                {...field}
                readOnly
                className="h-9 bg-muted"
              />
            </div>
          ) : (
            <Input
              key={`tag-type-placeholder-${inputId}`}
              {...field}
              readOnly
              placeholder={t("placeholders.autoSetByClass")}
              className="h-9 bg-muted"
            />
          )}
        </FormControl>
        <FormMessage />
      </FormItem>
    )
  }

  // ---------------
  // Render the table of subfields
  // ---------------
  function renderTagTable() {
    if (isLoadingSubFields) {
      return (
        <div className="flex justify-center items-center py-8">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <div className="ml-3 text-muted-foreground">{t("messages.loadingFields")}</div>
        </div>
      )
    }

    if (subFields.length === 0 && selectedTagTypeCode) {
      const message = selectedClassOption?.subclasses && selectedClassOption.subclasses.length > 0
        ? t("messages.selectSubclassFirst")
        : t("messages.noFieldsForTagType")

      return (
        <div className="py-4 text-center text-muted-foreground">
          {message}
        </div>
      )
    }

    if (subFields.length === 0) {
      return (
        <div className="py-4 text-center text-muted-foreground">
          {t("messages.selectClassFirst")}
        </div>
      )
    }

    return (
      <div className="space-y-4">
        {/* 헤더 */}
        <div className="flex justify-between items-center">
          <h3 className="text-sm font-medium">{t("sections.tagItems")} ({fields.length}개)</h3>
          {!areAllTagNosValid && (
            <Badge variant="destructive" className="ml-2">
              {t("messages.invalidTagsExist")}
            </Badge>
          )}
        </div>

        {/* 테이블 컨테이너 - 가로/세로 스크롤 모두 적용 */}
        <div className="border rounded-md overflow-auto" style={{ maxHeight: '400px', maxWidth: '100%' }}>
          <div className="min-w-full overflow-x-auto">
            <Table className="w-full table-fixed">
              <TableHeader className="sticky top-0 bg-muted z-10">
                <TableRow>
                  <TableHead className="w-10 text-center">#</TableHead>
                  <TableHead className="w-[120px]">
                    <div className="font-medium">{t("labels.tagNo")}</div>
                  </TableHead>
                  <TableHead className="w-[180px]">
                    <div className="font-medium">{t("labels.description")}</div>
                  </TableHead>

                  {/* Subfields */}
                  {subFields.map((field, fieldIndex) => (
                    <TableHead
                      key={`header-${field.name}-${fieldIndex}`}
                      className="w-[120px]"
                    >
                      <div className="flex flex-col">
                        <div className="font-medium" title={field.label}>
                          {field.label}
                        </div>
                        {field.expression && (
                          <div className="text-[10px] text-muted-foreground truncate" title={field.expression}>
                            {field.expression}
                          </div>
                        )}
                      </div>
                    </TableHead>
                  ))}

                  <TableHead className="w-[100px] text-center sticky right-0 bg-muted">{t("labels.actions")}</TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                {fields.map((item, rowIndex) => (
                  <TableRow
                    key={`row-${item.id}-${rowIndex}`}
                    className={rowIndex % 2 === 0 ? "bg-background" : "bg-muted/20"}
                  >
                    {/* Row number */}
                    <TableCell className="text-center text-muted-foreground font-mono">
                      {rowIndex + 1}
                    </TableCell>

                    {/* Tag No cell */}
                    <TableCell className="p-1">
                      <FormField
                        control={form.control}
                        name={`rows.${rowIndex}.tagNo`}
                        render={({ field }) => (
                          <FormItem className="m-0 space-y-0">
                            <FormControl>
                              <div className="relative">
                                <Input
                                  {...field}
                                  readOnly
                                  className={cn(
                                    "bg-muted h-8 w-full font-mono text-sm",
                                    field.value?.includes("??") && "border-red-500 bg-red-50"
                                  )}
                                  title={field.value || ""}
                                />
                                {field.value?.includes("??") && (
                                  <div className="absolute right-2 top-1/2 transform -translate-y-1/2">
                                    <Badge variant="destructive" className="text-xs">
                                      !
                                    </Badge>
                                  </div>
                                )}
                              </div>
                            </FormControl>
                          </FormItem>
                        )}
                      />
                    </TableCell>

                    {/* Description cell */}
                    <TableCell className="p-1">
                      <FormField
                        control={form.control}
                        name={`rows.${rowIndex}.description`}
                        render={({ field }) => (
                          <FormItem className="m-0 space-y-0">
                            <FormControl>
                              <Input
                                {...field}
                                className="h-8 w-full"
                                placeholder={t("placeholders.enterDescription")}
                                title={field.value || ""}
                              />
                            </FormControl>
                          </FormItem>
                        )}
                      />
                    </TableCell>

                    {/* Subfield cells */}
                    {subFields.map((sf, sfIndex) => (
                      <TableCell
                        key={`cell-${item.id}-${rowIndex}-${sf.name}-${sfIndex}`}
                        className="p-1"
                      >
                        <FormField
                          control={form.control}
                          name={`rows.${rowIndex}.${sf.name}`}
                          render={({ field }) => (
                            <FormItem className="m-0 space-y-0">
                              <FormControl>
                                {sf.type === "select" ? (
                                  <Select
                                    value={field.value || ""}
                                    onValueChange={field.onChange}
                                  >
                                    <SelectTrigger
                                      className="w-full h-8 truncate"
                                      title={field.value || ""}
                                    >
                                      <SelectValue placeholder={t("placeholders.selectOption")} className="truncate" />
                                    </SelectTrigger>
                                    <SelectContent
                                      align="start"
                                      side="bottom"
                                      className="max-h-[200px]"
                                      style={{ minWidth: "250px", maxWidth: "350px" }}
                                    >
                                      {sf.options?.map((opt, index) => (
                                        <SelectItem
                                          key={`${rowIndex}-${sf.name}-${opt.value}-${index}`}
                                          value={opt.value}
                                          title={opt.label}
                                          className="whitespace-normal py-2 break-words"
                                        >
                                          {opt.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                ) : (
                                  <Input
                                    {...field}
                                    className="h-8 w-full"
                                    placeholder={t("placeholders.enterValue")}
                                    title={field.value || ""}
                                  />
                                )}
                              </FormControl>
                            </FormItem>
                          )}
                        />
                      </TableCell>
                    ))}

                    {/* Actions cell */}
                    <TableCell className="p-1 sticky right-0 bg-white shadow-[-4px_0_4px_rgba(0,0,0,0.05)]">
                      <div className="flex justify-center space-x-1">
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-7 w-7"
                                onClick={() => duplicateRow(rowIndex)}
                              >
                                <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent side="left">
                              <p>{t("tooltips.duplicateRow")}</p>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>

                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className={cn(
                                  "h-7 w-7",
                                  fields.length <= 1 && "opacity-50"
                                )}
                                onClick={() => fields.length > 1 && remove(rowIndex)}
                                disabled={fields.length <= 1}
                              >
                                <Trash2 className="h-3.5 w-3.5 text-red-500" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent side="left">
                              <p>{t("tooltips.deleteRow")}</p>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 행 추가 버튼 */}
          <Button
            type="button"
            variant="outline"
            className="w-full border-dashed"
            onClick={addRow}
            disabled={!selectedTagTypeCode || isLoadingSubFields || subFields.length === 0}
          >
            <Plus className="h-4 w-4 mr-2" />
            {t("buttons.addRow")}
          </Button>
        </div>
      </div>
    );
  }

  // ---------------
  // Reset IDs/states when dialog closes
  // ---------------
  React.useEffect(() => {
    if (!open) {
      fieldIdsRef.current = {}
      classOptionIdsRef.current = {}
      selectIdRef.current = 0
    }
  }, [open])

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (!o) {
          form.reset({
            tagType: "",
            class: "",
            subclass: "",
            rows: [{ tagNo: "", description: "" }]
          });
          setSelectedTagTypeCode(null);
          setSelectedClassOption(null);
          setSelectedSubclass("");
          setSubFields([]);
        }
        setOpen(o);
      }}
    >
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          {t("buttons.addTags")}
        </Button>
      </DialogTrigger>

      <DialogContent className="max-h-[90vh] max-w-[95vw]" style={{ width: 1500 }}>
        <DialogHeader>
          <DialogTitle>{t("dialogs.addFormTag")}</DialogTitle>
          <DialogDescription>
            {t("dialogs.selectClassToLoadFields")}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
          >
            {/* 클래스, 서브클래스, 태그 유형 선택 */}
            <div className="flex gap-4">
              <FormField
                key="class-field"
                control={form.control}
                name="class"
                render={({ field }) => renderClassField(field)}
              />

              <FormField
                key="subclass-field"
                control={form.control}
                name="subclass"
                render={({ field }) => renderSubclassField(field)}
              />

              <FormField
                key="tag-type-field"
                control={form.control}
                name="tagType"
                render={({ field }) => renderTagTypeField(field)}
              />
            </div>

            {/* 태그 테이블 */}
            {renderTagTable()}

            {/* 버튼 */}
            <DialogFooter>
              <div className="flex items-center gap-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    form.reset({
                      tagType: "",
                      class: "",
                      subclass: "",
                      rows: [{ tagNo: "", description: "" }]
                    });
                    setOpen(false);
                    setSubFields([]);
                    setSelectedTagTypeCode(null);
                    setSelectedClassOption(null);
                    setSelectedSubclass("");
                  }}
                  disabled={isSubmitting}
                >
                  {t("buttons.cancel")}
                </Button>
                <Button
                  type="submit"
                  disabled={isSubmitting || !areAllTagNosValid || fields.length < 1}
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {t("messages.processing")}
                    </>
                  ) : (
                    `${fields.length}${t("buttons.createTags")}`
                  )}
                </Button>
              </div>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}