"use client";

/**
 * V2Biz 설정 패널
 * 통합 비즈니스 컴포넌트의 세부 설정을 관리합니다.
 */

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { tableTypeApi } from "@/lib/api/screen";

interface V2BizConfigPanelProps {
  config: Record<string, any>;
  onChange: (config: Record<string, any>) => void;
}

interface TableOption {
  tableName: string;
  displayName: string;
}

interface ColumnOption {
  columnName: string;
  displayName: string;
}

export const V2BizConfigPanel: React.FC<V2BizConfigPanelProps> = ({
  config,
  onChange,
}) => {
  const [tables, setTables] = useState<TableOption[]>([]);
  const [loadingTables, setLoadingTables] = useState(false);
  const [sourceColumns, setSourceColumns] = useState<ColumnOption[]>([]);
  const [targetColumns, setTargetColumns] = useState<ColumnOption[]>([]);
  const [relatedColumns, setRelatedColumns] = useState<ColumnOption[]>([]);
  const [categoryColumns, setCategoryColumns] = useState<ColumnOption[]>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);

  const updateConfig = (field: string, value: any) => {
    onChange({ ...config, [field]: value });
  };

  useEffect(() => {
    const loadTables = async () => {
      setLoadingTables(true);
      try {
        const data = await tableTypeApi.getTables();
        setTables(data.map(t => ({
          tableName: t.tableName,
          displayName: t.displayName || t.tableName
        })));
      } catch (error) {
        console.error("테이블 목록 로드 실패:", error);
      } finally {
        setLoadingTables(false);
      }
    };
    loadTables();
  }, []);

  useEffect(() => {
    const loadColumns = async () => {
      if (!config.sourceTable) { setSourceColumns([]); return; }
      try {
        const data = await tableTypeApi.getColumns(config.sourceTable);
        setSourceColumns(data.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnName || c.column_name
        })));
      } catch (error) {
        console.error("소스 컬럼 로드 실패:", error);
      }
    };
    loadColumns();
  }, [config.sourceTable]);

  useEffect(() => {
    const loadColumns = async () => {
      if (!config.targetTable) { setTargetColumns([]); return; }
      try {
        const data = await tableTypeApi.getColumns(config.targetTable);
        setTargetColumns(data.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnName || c.column_name
        })));
      } catch (error) {
        console.error("대상 컬럼 로드 실패:", error);
      }
    };
    loadColumns();
  }, [config.targetTable]);

  useEffect(() => {
    const loadColumns = async () => {
      if (!config.relatedTable) { setRelatedColumns([]); return; }
      try {
        const data = await tableTypeApi.getColumns(config.relatedTable);
        setRelatedColumns(data.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnName || c.column_name
        })));
      } catch (error) {
        console.error("관련 컬럼 로드 실패:", error);
      }
    };
    loadColumns();
  }, [config.relatedTable]);

  useEffect(() => {
    const loadColumns = async () => {
      if (!config.tableName) { setCategoryColumns([]); return; }
      setLoadingColumns(true);
      try {
        const data = await tableTypeApi.getColumns(config.tableName);
        setCategoryColumns(data.map((c: any) => ({
          columnName: c.columnName || c.column_name,
          displayName: c.displayName || c.columnName || c.column_name
        })));
      } catch (error) {
        console.error("카테고리 컬럼 로드 실패:", error);
      } finally {
        setLoadingColumns(false);
      }
    };
    loadColumns();
  }, [config.tableName]);

  return (
    <div className="space-y-1">
      {/* BUSINESS TYPE 섹션 */}
      <div className="border-b border-border/50 pb-3 mb-3">
        <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">BUSINESS TYPE</h4>
        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">비즈니스 타입</span>
          <div className="w-[140px]">
            <Select
              value={config.bizType || config.type || "flow"}
              onValueChange={(value) => updateConfig("bizType", value)}
            >
              <SelectTrigger className="h-7 text-xs">
                <SelectValue placeholder="타입 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="flow">플로우</SelectItem>
                <SelectItem value="rack">랙 구조</SelectItem>
                <SelectItem value="map">지도</SelectItem>
                <SelectItem value="numbering">채번 규칙</SelectItem>
                <SelectItem value="category">카테고리</SelectItem>
                <SelectItem value="data-mapping">데이터 매핑</SelectItem>
                <SelectItem value="related-data">관련 데이터</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

      {/* FLOW SETTINGS 섹션 */}
      {config.bizType === "flow" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">FLOW SETTINGS</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">플로우 ID</span>
            <div className="w-[140px]">
              <Input
                type="number"
                value={config.flowId || ""}
                onChange={(e) => updateConfig("flowId", e.target.value ? Number(e.target.value) : undefined)}
                placeholder="플로우 ID"
                className="h-7 text-xs"
              />
            </div>
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">편집 가능</span>
            <Checkbox
              checked={config.editable || false}
              onCheckedChange={(checked) => updateConfig("editable", checked)}
            />
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">미니맵 표시</span>
            <Checkbox
              checked={config.showMinimap || false}
              onCheckedChange={(checked) => updateConfig("showMinimap", checked)}
            />
          </div>
        </div>
      )}

      {/* RACK SETTINGS 섹션 */}
      {config.bizType === "rack" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">RACK SETTINGS</h4>
          <div className="flex gap-2">
            <div className="flex-1">
              <Label className="text-[10px] text-muted-foreground">행 수</Label>
              <Input
                type="number"
                value={config.rows || ""}
                onChange={(e) => updateConfig("rows", e.target.value ? Number(e.target.value) : undefined)}
                placeholder="5"
                min="1"
                className="h-7 text-xs"
              />
            </div>
            <div className="flex-1">
              <Label className="text-[10px] text-muted-foreground">열 수</Label>
              <Input
                type="number"
                value={config.columns || ""}
                onChange={(e) => updateConfig("columns", e.target.value ? Number(e.target.value) : undefined)}
                placeholder="10"
                min="1"
                className="h-7 text-xs"
              />
            </div>
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">라벨 표시</span>
            <Checkbox
              checked={config.showLabels !== false}
              onCheckedChange={(checked) => updateConfig("showLabels", checked)}
            />
          </div>
        </div>
      )}

      {/* NUMBERING SETTINGS 섹션 */}
      {config.bizType === "numbering" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">NUMBERING SETTINGS</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">채번 규칙 ID</span>
            <div className="w-[140px]">
              <Input
                type="number"
                value={config.ruleId || ""}
                onChange={(e) => updateConfig("ruleId", e.target.value ? Number(e.target.value) : undefined)}
                placeholder="규칙 ID"
                className="h-7 text-xs"
              />
            </div>
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">접두사</span>
            <div className="w-[140px]">
              <Input
                value={config.prefix || ""}
                onChange={(e) => updateConfig("prefix", e.target.value)}
                placeholder="예: INV-"
                className="h-7 text-xs"
              />
            </div>
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">자동 생성</span>
            <Checkbox
              checked={config.autoGenerate !== false}
              onCheckedChange={(checked) => updateConfig("autoGenerate", checked)}
            />
          </div>
        </div>
      )}

      {/* CATEGORY SETTINGS 섹션 */}
      {config.bizType === "category" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">CATEGORY SETTINGS</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">카테고리 테이블</span>
            <div className="w-[140px]">
              <Select
                value={config.tableName || ""}
                onValueChange={(value) => {
                  updateConfig("tableName", value);
                  updateConfig("columnName", "");
                }}
                disabled={loadingTables}
              >
                <SelectTrigger className="h-7 text-xs">
                  <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          {config.tableName && (
            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">컬럼</span>
              <div className="w-[140px]">
                <Select
                  value={config.columnName || ""}
                  onValueChange={(value) => updateConfig("columnName", value)}
                  disabled={loadingColumns}
                >
                  <SelectTrigger className="h-7 text-xs">
                    <SelectValue placeholder={loadingColumns ? "로딩 중..." : "컬럼 선택"} />
                  </SelectTrigger>
                  <SelectContent>
                    {categoryColumns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
        </div>
      )}

      {/* DATA MAPPING 섹션 */}
      {config.bizType === "data-mapping" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">DATA MAPPING</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">소스 테이블</span>
            <div className="w-[140px]">
              <Select
                value={config.sourceTable || ""}
                onValueChange={(value) => updateConfig("sourceTable", value)}
                disabled={loadingTables}
              >
                <SelectTrigger className="h-7 text-xs">
                  <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">대상 테이블</span>
            <div className="w-[140px]">
              <Select
                value={config.targetTable || ""}
                onValueChange={(value) => updateConfig("targetTable", value)}
                disabled={loadingTables}
              >
                <SelectTrigger className="h-7 text-xs">
                  <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      )}

      {/* RELATED DATA 섹션 */}
      {config.bizType === "related-data" && (
        <div className="border-b border-border/50 pb-3 mb-3">
          <h4 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground py-2">RELATED DATA</h4>
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">관련 테이블</span>
            <div className="w-[140px]">
              <Select
                value={config.relatedTable || ""}
                onValueChange={(value) => {
                  updateConfig("relatedTable", value);
                  updateConfig("linkColumn", "");
                }}
                disabled={loadingTables}
              >
                <SelectTrigger className="h-7 text-xs">
                  <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          {config.relatedTable && (
            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">연결 컬럼</span>
              <div className="w-[140px]">
                <Select
                  value={config.linkColumn || ""}
                  onValueChange={(value) => updateConfig("linkColumn", value)}
                >
                  <SelectTrigger className="h-7 text-xs">
                    <SelectValue placeholder="컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {relatedColumns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">버튼 텍스트</span>
            <div className="w-[140px]">
              <Input
                value={config.buttonText || ""}
                onChange={(e) => updateConfig("buttonText", e.target.value)}
                placeholder="관련 데이터 보기"
                className="h-7 text-xs"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

V2BizConfigPanel.displayName = "V2BizConfigPanel";

export default V2BizConfigPanel;
