"use client"

import * as React from "react"
import { useParams, useRouter } from "next/navigation";
import { useForm, useFieldArray } from "react-hook-form"
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 { createTagInForm } from "@/lib/tags/service"
import {
  getFormTagTypeMappings,
  getTagTypeByDescription,
  getSubfieldsByTagTypeForForm
} from "@/lib/forms-plant/services"
import { useTranslation } from "@/i18n/client";

// Form-specific tag mapping interface
interface FormTagMapping {
  id: number;
  tagTypeLabel: string;
  classLabel: string;
  formCode: string;
  formName: string;
  remark?: string | null;
}

// Updated to support multiple rows
interface MultiTagFormValues {
  class: string;
  tagType: string;
  rows: Array<{
    [key: string]: string;
    tagNo: string;
    description: string;
  }>;
}

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

interface AddFormTagDialogProps {
  projectId: number;
  formCode: string;
  formName?: string;
  contractItemId: number;
  packageCode: string;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}

export function AddFormTagDialog({
  projectId,
  formCode,
  formName,
  contractItemId,
  packageCode,
  open: externalOpen,
  onOpenChange: externalOnOpenChange
}: AddFormTagDialogProps) {
  const router = useRouter()
  const params = useParams();
  const lng = (params?.lng as string) || "ko";
  const { t } = useTranslation(lng, "engineering");

  // Use external control if provided, otherwise use internal state
  const [internalOpen, setInternalOpen] = React.useState(false);
  const isOpen = externalOpen !== undefined ? externalOpen : internalOpen;
  const setIsOpen = externalOnOpenChange || setInternalOpen;

  const [mappings, setMappings] = React.useState<FormTagMapping[]>([])
  const [selectedTagTypeLabel, setSelectedTagTypeLabel] = React.useState<string | null>(null)
  const [selectedTagTypeCode, setSelectedTagTypeCode] = React.useState<string | null>(null)
  const [subFields, setSubFields] = React.useState<SubFieldDef[]>([])
  const [isLoadingClasses, setIsLoadingClasses] = React.useState(false)
  const [isLoadingSubFields, setIsLoadingSubFields] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  // ID management for React keys
  const selectIdRef = React.useRef(0)
  const fieldIdsRef = React.useRef<Record<string, string>>({})
  const classOptionIdsRef = React.useRef<Record<string, string>>({})

  // ---------------
  // Load Form Tag Mappings
  // ---------------
  React.useEffect(() => {
    const loadMappings = async () => {
      if (!formCode || !projectId) return;

      setIsLoadingClasses(true);
      try {
        const result = await getFormTagTypeMappings(formCode, projectId);
        // Type safety casting
        const typedMappings: FormTagMapping[] = result.map(item => ({
          id: item.id,
          tagTypeLabel: item.tagTypeLabel,
          classLabel: item.classLabel,
          formCode: item.formCode,
          formName: item.formName,
          remark: item.remark
        }));
        setMappings(typedMappings);
      } catch (err) {
        toast.error("폼 태그 매핑 로드에 실패했습니다.");
      } finally {
        setIsLoadingClasses(false);
      }
    };

    loadMappings();
  }, [formCode, projectId]);

  // Load mappings when dialog opens
  React.useEffect(() => {
    if (isOpen) {
      const loadMappings = async () => {
        if (!formCode || !projectId) return;

        setIsLoadingClasses(true);
        try {
          const result = await getFormTagTypeMappings(formCode, projectId);
          // Type safety casting
          const typedMappings: FormTagMapping[] = result.map(item => ({
            id: item.id,
            tagTypeLabel: item.tagTypeLabel,
            classLabel: item.classLabel,
            formCode: item.formCode,
            formName: item.formName,
            remark: item.remark
          }));
          setMappings(typedMappings);
        } catch (err) {
          toast.error("폼 태그 매핑 로드에 실패했습니다.");
        } finally {
          setIsLoadingClasses(false);
        }
      };

      loadMappings();
    }
  }, [isOpen, formCode, projectId]);

  // ---------------
  // react-hook-form with fieldArray support for multiple rows
  // ---------------
  const form = useForm<MultiTagFormValues>({
    defaultValues: {
      tagType: "",
      class: "",
      rows: [{
        tagNo: "",
        description: ""
      }]
    },
  });

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

  // ---------------
  // Load subfields by TagType code
  // ---------------
  async function loadSubFieldsByTagTypeCode(tagTypeCode: string) {
    setIsLoadingSubFields(true);
    try {
      const { subFields: apiSubFields } = await getSubfieldsByTagTypeForForm(tagTypeCode, projectId);
      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("서브필드를 불러오는데 실패했습니다.");
      setSubFields([]);
      return false;
    } finally {
      setIsLoadingSubFields(false);
    }
  }

  // ---------------
  // Handle class selection
  // ---------------
  async function handleSelectClass(classLabel: string) {
    form.setValue("class", classLabel);

    // Find the mapping for this class
    const mapping = mappings.find(m => m.classLabel === classLabel);
    if (mapping) {
      setSelectedTagTypeLabel(mapping.tagTypeLabel);
      form.setValue("tagType", mapping.tagTypeLabel);

      // Get the tagTypeCode for this tagTypeLabel
      try {
        const tagType = await getTagTypeByDescription(mapping.tagTypeLabel, projectId);
        if (tagType) {
          setSelectedTagTypeCode(tagType.code);
          await loadSubFieldsByTagTypeCode(tagType.code);
        } else {
          toast.error("선택한 태그 유형을 찾을 수 없습니다.");
        }
      } catch (error) {
        toast.error("태그 유형 정보를 불러오는데 실패했습니다.");
      }
    }
  }

  // ---------------
  // 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 (!contractItemId || !projectId) {
      toast.error("필요한 정보가 없습니다.");
      return;
    }

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

      // Process each row
      for (const row of data.rows) {
        // Create tag data
        const tagData = {
          tagType: data.tagType,
          class: data.class,
          tagNo: row.tagNo,
          description: row.description,
          ...Object.fromEntries(
            subFields.map(field => [field.name, row[field.name] || ""])
          ),
          functionCode: row.functionCode || "",
          seqNumber: row.seqNumber || "",
          valveAcronym: row.valveAcronym || "",
          processUnit: row.processUnit || "",
        };

        try {
          const res = await createTagInForm(tagData, contractItemId, formCode, packageCode);
          if (res && "error" in res) {
            failedTags.push({ tag: row.tagNo, error: res.error });
          } else if (res && res.success) {
            successfulTags.push(row.tagNo);
          } else {
            // 예상치 못한 응답 처리
            console.error("Unexpected response:", res);
            failedTags.push({ tag: row.tagNo, error: "Unexpected response format" });
          }

        } catch (err) {
          failedTags.push({ tag: row.tagNo, error: "Unknown error" });
        }
      }

      // Show results to the user
      if (successfulTags.length > 0) {
        toast.success(`${successfulTags.length}개의 태그가 성공적으로 생성되었습니다!`);
      }

      if (failedTags.length > 0) {
        console.log("Failed tags:", failedTags);

        // 전체 에러 메시지 표시
        const errorMessage = failedTags
          .map(f => `${f.tag}: ${f.error}`)
          .join('\n');

        toast.error(
          <div>
            <p>{failedTags.length}개의 태그 생성 실패:</p>
            <ul className="text-sm mt-1">
              {failedTags.map((f, idx) => (
                <li key={idx}>• {f.tag}: {f.error}</li>
              ))}
            </ul>
          </div>
        );
      }

      // Refresh the page
      router.refresh();

      // Reset the form and close dialog if all successful
      if (failedTags.length === 0) {
        form.reset();
        setIsOpen(false);
      }
    } catch (err) {
      toast.error("태그 생성 처리에 실패했습니다.");
    } 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);

    // Force form validation after row is added
    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 };

    // Clear the tagNo field as it will be auto-generated
    newRow.tagNo = "";
    append(newRow);

    // Force form validation after row is duplicated
    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)}`,
      []
    )

    // Get unique class labels from mappings
    const classOptions = Array.from(new Set(mappings.map(m => m.classLabel)));

    return (
      <FormItem className="w-1/2">
        <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">
              <Command key={commandId}>
                <CommandInput
                  key={`${commandId}-input`}
                  placeholder={t("placeholders.searchClass")}
                />
                <CommandList key={`${commandId}-list`} className="max-h-[300px]">
                  <CommandEmpty key={`${commandId}-empty`}>{t("messages.noSearchResults")}</CommandEmpty>
                  <CommandGroup key={`${commandId}-group`}>
                    {classOptions.map((className, optIndex) => {
                      if (!classOptionIdsRef.current[className]) {
                        classOptionIdsRef.current[className] =
                          `class-${className}-${Date.now()}-${Math.random()
                            .toString(36)
                            .slice(2, 9)}`
                      }
                      const optionId = classOptionIdsRef.current[className]

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

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

    return (
      <FormItem className="w-1/2">
        <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) {
      return (
        <div className="py-4 text-center text-muted-foreground">
          {t("messages.noFieldsForTagType")}
        </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={`선택...`} 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.value} - {opt.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                ) : (
                                  <Input
                                    {...field}
                                    className="h-8 w-full"
                                    placeholder={`입력...`}
                                    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}
          >
            <Plus className="h-4 w-4 mr-2" />
            {t("buttons.addRow")}
          </Button>
        </div>
      </div>
    );
  }

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

  return (
    <Dialog
      open={isOpen}
      onOpenChange={(o) => {
        if (!o) {
          form.reset({
            tagType: "",
            class: "",
            rows: [{ tagNo: "", description: "" }]
          });
          setSelectedTagTypeLabel(null);
          setSelectedTagTypeCode(null);
          setSubFields([]);
        }
        setIsOpen(o);
      }}
    >
      {/* Only show the trigger if external control is not being used */}
      {externalOnOpenChange === undefined && (
        <DialogTrigger asChild>
          <Button variant="outline" size="sm">
            <Plus className="mr-2 size-4" />
            {t("buttons.addTags")}
          </Button>
        </DialogTrigger>
      )}

      <DialogContent className="max-h-[90vh] max-w-[95vw]" style={{ width: 1500 }}>
        <DialogHeader>
          <DialogTitle>{t("dialogs.addFormTag")} - {formName || formCode}</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="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: "",
                      rows: [{ tagNo: "", description: "" }]
                    });
                    setIsOpen(false);
                    setSubFields([]);
                    setSelectedTagTypeLabel(null);
                    setSelectedTagTypeCode(null);
                  }}
                  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.create")}`
                  )}
                </Button>
              </div>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}