"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 { Separator } from "@/components/ui/separator";
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-4">
      {/* 비즈니스 타입 */}
      <div className="space-y-2">
        <Label className="text-xs font-medium">비즈니스 타입</Label>
        <Select
          value={config.bizType || config.type || "flow"}
          onValueChange={(value) => updateConfig("bizType", value)}
        >
          <SelectTrigger className="h-8 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>

      <Separator />

      {/* 플로우 설정 */}
      {config.bizType === "flow" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">플로우 설정</Label>
          
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">플로우 ID</Label>
            <Input
              type="number"
              value={config.flowId || ""}
              onChange={(e) => updateConfig("flowId", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="플로우 ID"
              className="h-8 text-xs"
            />
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="editable"
              checked={config.editable || false}
              onCheckedChange={(checked) => updateConfig("editable", checked)}
            />
            <label htmlFor="editable" className="text-xs">편집 가능</label>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="showMinimap"
              checked={config.showMinimap || false}
              onCheckedChange={(checked) => updateConfig("showMinimap", checked)}
            />
            <label htmlFor="showMinimap" className="text-xs">미니맵 표시</label>
          </div>
        </div>
      )}

      {/* 랙 구조 설정 */}
      {config.bizType === "rack" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">랙 설정</Label>
          
          <div className="grid grid-cols-2 gap-2">
            <div className="space-y-2">
              <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-8 text-xs"
              />
            </div>
            <div className="space-y-2">
              <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-8 text-xs"
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="showLabels"
              checked={config.showLabels !== false}
              onCheckedChange={(checked) => updateConfig("showLabels", checked)}
            />
            <label htmlFor="showLabels" className="text-xs">라벨 표시</label>
          </div>
        </div>
      )}

      {/* 채번 규칙 설정 */}
      {config.bizType === "numbering" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">채번 설정</Label>
          
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">채번 규칙 ID</Label>
            <Input
              type="number"
              value={config.ruleId || ""}
              onChange={(e) => updateConfig("ruleId", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="규칙 ID"
              className="h-8 text-xs"
            />
          </div>

          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">접두사</Label>
            <Input
              value={config.prefix || ""}
              onChange={(e) => updateConfig("prefix", e.target.value)}
              placeholder="예: INV-"
              className="h-8 text-xs"
            />
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="autoGenerate"
              checked={config.autoGenerate !== false}
              onCheckedChange={(checked) => updateConfig("autoGenerate", checked)}
            />
            <label htmlFor="autoGenerate" className="text-xs">자동 생성</label>
          </div>
        </div>
      )}

      {/* 카테고리 설정 */}
      {config.bizType === "category" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">카테고리 설정</Label>
          
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">카테고리 테이블</Label>
            <Select
              value={config.tableName || ""}
              onValueChange={(value) => {
                updateConfig("tableName", value);
                updateConfig("columnName", "");
              }}
              disabled={loadingTables}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
              </SelectTrigger>
              <SelectContent>
                {tables.map((table) => (
                  <SelectItem key={table.tableName} value={table.tableName}>
                    {table.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {config.tableName && (
            <div className="space-y-2">
              <Label className="text-[10px] text-muted-foreground">컬럼</Label>
              <Select
                value={config.columnName || ""}
                onValueChange={(value) => updateConfig("columnName", value)}
                disabled={loadingColumns}
              >
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue placeholder={loadingColumns ? "로딩 중..." : "컬럼 선택"} />
                </SelectTrigger>
                <SelectContent>
                  {categoryColumns.map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}
        </div>
      )}

      {/* 데이터 매핑 설정 */}
      {config.bizType === "data-mapping" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">매핑 설정</Label>
          
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">소스 테이블</Label>
            <Select
              value={config.sourceTable || ""}
              onValueChange={(value) => updateConfig("sourceTable", value)}
              disabled={loadingTables}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
              </SelectTrigger>
              <SelectContent>
                {tables.map((table) => (
                  <SelectItem key={table.tableName} value={table.tableName}>
                    {table.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">대상 테이블</Label>
            <Select
              value={config.targetTable || ""}
              onValueChange={(value) => updateConfig("targetTable", value)}
              disabled={loadingTables}
            >
              <SelectTrigger className="h-8 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.bizType === "related-data" && (
        <div className="space-y-3">
          <Label className="text-xs font-medium">관련 데이터 설정</Label>
          
          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">관련 테이블</Label>
            <Select
              value={config.relatedTable || ""}
              onValueChange={(value) => {
                updateConfig("relatedTable", value);
                updateConfig("linkColumn", "");
              }}
              disabled={loadingTables}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder={loadingTables ? "로딩 중..." : "테이블 선택"} />
              </SelectTrigger>
              <SelectContent>
                {tables.map((table) => (
                  <SelectItem key={table.tableName} value={table.tableName}>
                    {table.displayName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {config.relatedTable && (
            <div className="space-y-2">
              <Label className="text-[10px] text-muted-foreground">연결 컬럼</Label>
              <Select
                value={config.linkColumn || ""}
                onValueChange={(value) => updateConfig("linkColumn", value)}
              >
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue placeholder="컬럼 선택" />
                </SelectTrigger>
                <SelectContent>
                  {relatedColumns.map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="space-y-2">
            <Label className="text-[10px] text-muted-foreground">버튼 텍스트</Label>
            <Input
              value={config.buttonText || ""}
              onChange={(e) => updateConfig("buttonText", e.target.value)}
              placeholder="관련 데이터 보기"
              className="h-8 text-xs"
            />
          </div>
        </div>
      )}
    </div>
  );
};

V2BizConfigPanel.displayName = "V2BizConfigPanel";

export default V2BizConfigPanel;
