"use client";

import React, { useState, useCallback, useRef, useEffect } from "react";
import { Settings2, Tags, Hash } from "lucide-react";
import { cn } from "@/lib/utils";
import { CategoryColumnList } from "@/components/table-category/CategoryColumnList";
import { CategoryValueManager } from "@/components/table-category/CategoryValueManager";
import { CategoryValueManagerTree } from "@/components/table-category/CategoryValueManagerTree";
import { NumberingRuleDesigner } from "@/components/numbering-rule/NumberingRuleDesigner";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { useConfirmDialog } from "@/components/common/ConfirmDialog";
import { getCategoryValues } from "@/lib/api/tableCategoryValue";

const TABS = [
  { id: "category", label: "카테고리 설정", icon: Tags },
  { id: "numbering", label: "코드 설정", icon: Hash },
] as const;

type TabId = (typeof TABS)[number]["id"];

export default function OptionsSettingPage() {
  const [activeTab, setActiveTab] = useState<TabId>("category");

  const [selectedColumn, setSelectedColumn] = useState<string | null>(null);
  const [selectedColumnLabel, setSelectedColumnLabel] = useState("");
  const [selectedTableName, setSelectedTableName] = useState("");

  // 하위분류 사용 여부 (카테고리별 자동감지 + 수동 토글)
  const [useHierarchy, setUseHierarchy] = useState(false);
  const [hasChildRows, setHasChildRows] = useState(false);
  const [detectingHierarchy, setDetectingHierarchy] = useState(false);

  const { confirm, ConfirmDialogComponent } = useConfirmDialog();

  const [leftWidth, setLeftWidth] = useState(340);
  const [isDragging, setIsDragging] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleMouseDown = useCallback(() => {
    setIsDragging(true);
    document.body.style.cursor = "col-resize";
    document.body.style.userSelect = "none";
  }, []);

  useEffect(() => {
    if (!isDragging) return;
    const handleMouseMove = (e: MouseEvent) => {
      if (!containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      setLeftWidth(Math.max(260, Math.min(500, e.clientX - rect.left)));
    };
    const handleMouseUp = () => {
      setIsDragging(false);
      document.body.style.cursor = "";
      document.body.style.userSelect = "";
    };
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isDragging]);

  // 카테고리 선택 변경 시 하위분류 존재 여부 자동감지
  useEffect(() => {
    if (!selectedColumn || !selectedTableName) {
      setUseHierarchy(false);
      setHasChildRows(false);
      return;
    }
    const columnNameOnly = selectedColumn.includes(".")
      ? selectedColumn.split(".").pop()!
      : selectedColumn;
    let cancelled = false;
    setDetectingHierarchy(true);
    (async () => {
      const res = await getCategoryValues(selectedTableName, columnNameOnly, true);
      if (cancelled) return;
      const values = (res as any)?.data || [];
      const hasChild = Array.isArray(values)
        ? values.some(
            (v: any) =>
              (typeof v.depth === "number" && v.depth > 1) ||
              (v.parentValueId !== null && v.parentValueId !== undefined),
          )
        : false;
      setHasChildRows(hasChild);
      setUseHierarchy(hasChild);
      setDetectingHierarchy(false);
    })();
    return () => {
      cancelled = true;
    };
  }, [selectedColumn, selectedTableName]);

  const handleToggleHierarchy = useCallback(
    async (checked: boolean) => {
      if (!checked && hasChildRows) {
        const ok = await confirm(
          "이미 등록된 하위분류(중/소분류)가 있습니다.\n하위분류 사용을 해제해도 기존 데이터는 삭제되지 않으며, 다시 사용 설정 시 그대로 복원됩니다.\n계속하시겠습니까?",
          { variant: "destructive", confirmText: "해제" },
        );
        if (!ok) return;
      }
      setUseHierarchy(checked);
    },
    [hasChildRows, confirm],
  );

  const columnNameOnly = selectedColumn
    ? selectedColumn.includes(".")
      ? selectedColumn.split(".").pop()!
      : selectedColumn
    : "";

  const headerRight = selectedColumn ? (
    <div className="flex items-center gap-2">
      <Label htmlFor="use-hierarchy-switch" className="cursor-pointer text-xs">
        하위분류 사용
      </Label>
      <Switch
        id="use-hierarchy-switch"
        checked={useHierarchy}
        onCheckedChange={handleToggleHierarchy}
        disabled={detectingHierarchy}
      />
    </div>
  ) : null;

  return (
    <div className="flex h-full flex-col p-3 gap-3">
      <div className="flex items-center gap-4">
        <div className="flex items-center gap-2">
          <Settings2 className="h-4 w-4 text-primary" />
          <h1 className="text-sm font-semibold">옵션 설정</h1>
        </div>
        <div className="flex bg-muted rounded-md p-0.5 gap-0.5">
          {TABS.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={cn(
                  "flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium transition-all",
                  activeTab === tab.id
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground"
                )}
              >
                <Icon className="h-3.5 w-3.5" />
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      <div className="flex-1 min-h-0">
        {activeTab === "category" && (
          <div ref={containerRef} className="flex h-full">
            <div
              style={{ width: leftWidth }}
              className="shrink-0 border rounded-lg bg-card overflow-hidden"
            >
              <CategoryColumnList
                tableName=""
                selectedColumn={selectedColumn}
                onColumnSelect={(uniqueKey, label, tableName) => {
                  setSelectedColumn(uniqueKey);
                  setSelectedColumnLabel(label);
                  setSelectedTableName(tableName);
                }}
              />
            </div>

            <div
              onMouseDown={handleMouseDown}
              className={cn(
                "w-1.5 mx-0.5 cursor-col-resize rounded-full transition-colors shrink-0",
                isDragging ? "bg-primary" : "bg-border hover:bg-primary/50"
              )}
            />

            <div className="flex-1 min-w-0 border rounded-lg bg-card overflow-hidden">
              {selectedColumn && selectedTableName ? (
                useHierarchy ? (
                  <CategoryValueManagerTree
                    tableName={selectedTableName}
                    columnName={columnNameOnly}
                    columnLabel={selectedColumnLabel}
                    headerRight={headerRight}
                  />
                ) : (
                  <CategoryValueManager
                    tableName={selectedTableName}
                    columnName={columnNameOnly}
                    columnLabel={selectedColumnLabel}
                    headerRight={headerRight}
                  />
                )
              ) : (
                <div className="flex h-full items-center justify-center">
                  <div className="text-center space-y-2">
                    <Tags className="h-8 w-8 mx-auto text-muted-foreground/30" />
                    <p className="text-sm text-muted-foreground">좌측에서 카테고리 컬럼을 선택해주세요</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === "numbering" && (
          <div className="h-full border rounded-lg bg-card overflow-auto">
            <NumberingRuleDesigner />
          </div>
        )}
      </div>
      {ConfirmDialogComponent}
    </div>
  );
}
