"use client";

/**
 * V2Biz 설정 패널
 * 토스식 단계별 UX: 비즈니스 타입 카드 선택 -> 타입별 설정 -> 고급 설정(접힘)
 */

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 { Switch } from "@/components/ui/switch";
import {
  GitBranch,
  LayoutGrid,
  MapPin,
  Hash,
  FolderTree,
  ArrowRightLeft,
  Link2,
  Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
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;
}

const BIZ_TYPE_CARDS = [
  { value: "flow", icon: GitBranch, title: "플로우", description: "워크플로우를 구성해요" },
  { value: "rack", icon: LayoutGrid, title: "랙 구조", description: "창고 렉 위치를 관리해요" },
  { value: "map", icon: MapPin, title: "지도", description: "위치 정보를 표시해요" },
  { value: "numbering", icon: Hash, title: "채번 규칙", description: "자동 번호를 생성해요" },
  { value: "category", icon: FolderTree, title: "카테고리", description: "분류 체계를 관리해요" },
  { value: "data-mapping", icon: ArrowRightLeft, title: "데이터 매핑", description: "테이블 간 매핑해요" },
  { value: "related-data", icon: Link2, title: "관련 데이터", description: "연결된 데이터를 조회해요" },
] as const;

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]);

  const bizType = config.bizType || config.type || "flow";

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 비즈니스 타입 선택 (카드) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">어떤 비즈니스 기능을 사용하나요?</p>
        <div className="grid grid-cols-2 gap-2">
          {BIZ_TYPE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = bizType === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("bizType", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-3 text-center transition-all min-h-[80px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <Icon className="h-5 w-5 mb-1.5 text-primary" />
                <span className="text-xs font-medium leading-tight">{card.title}</span>
                <span className="text-[10px] text-muted-foreground leading-tight mt-0.5">{card.description}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 2단계: 타입별 설정 ─── */}

      {/* 플로우 설정 */}
      {bizType === "flow" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <GitBranch className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">플로우 설정</span>
          </div>

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">플로우 ID</span>
            <Input
              type="number"
              value={config.flowId || ""}
              onChange={(e) => updateConfig("flowId", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="플로우 ID"
              className="h-7 w-[160px] text-xs"
            />
          </div>

          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">편집 가능</p>
              <p className="text-[11px] text-muted-foreground">플로우를 직접 수정할 수 있어요</p>
            </div>
            <Switch
              checked={config.editable || false}
              onCheckedChange={(checked) => updateConfig("editable", checked)}
            />
          </div>

          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">미니맵 표시</p>
              <p className="text-[11px] text-muted-foreground">전체 구조를 한눈에 볼 수 있어요</p>
            </div>
            <Switch
              checked={config.showMinimap || false}
              onCheckedChange={(checked) => updateConfig("showMinimap", checked)}
            />
          </div>
        </div>
      )}

      {/* 랙 구조 설정 */}
      {bizType === "rack" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <LayoutGrid className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">랙 구조 설정</span>
          </div>

          <div className="space-y-2">
            <p className="text-xs text-muted-foreground">렉 크기</p>
            <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>

          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">라벨 표시</p>
              <p className="text-[11px] text-muted-foreground">각 셀에 위치 라벨이 표시돼요</p>
            </div>
            <Switch
              checked={config.showLabels !== false}
              onCheckedChange={(checked) => updateConfig("showLabels", checked)}
            />
          </div>
        </div>
      )}

      {/* 채번 규칙 설정 */}
      {bizType === "numbering" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Hash className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">채번 규칙 설정</span>
          </div>

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">채번 규칙 ID</span>
            <Input
              type="number"
              value={config.ruleId || ""}
              onChange={(e) => updateConfig("ruleId", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="규칙 ID"
              className="h-7 w-[160px] text-xs"
            />
          </div>

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">접두사</span>
            <Input
              value={config.prefix || ""}
              onChange={(e) => updateConfig("prefix", e.target.value)}
              placeholder="예: INV-"
              className="h-7 w-[160px] text-xs"
            />
          </div>

          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">자동 생성</p>
              <p className="text-[11px] text-muted-foreground">저장할 때 번호가 자동으로 생성돼요</p>
            </div>
            <Switch
              checked={config.autoGenerate !== false}
              onCheckedChange={(checked) => updateConfig("autoGenerate", checked)}
            />
          </div>
        </div>
      )}

      {/* 카테고리 설정 */}
      {bizType === "category" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <FolderTree className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">카테고리 설정</span>
          </div>

          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">카테고리 테이블</p>
            {loadingTables ? (
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Loader2 className="h-3 w-3 animate-spin" />
                테이블 로딩 중...
              </div>
            ) : (
              <Select
                value={config.tableName || ""}
                onValueChange={(value) => {
                  updateConfig("tableName", value);
                  updateConfig("columnName", "");
                }}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="테이블 선택" />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          {config.tableName && (
            <div>
              <p className="mb-1.5 text-xs text-muted-foreground">컬럼</p>
              {loadingColumns ? (
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <Loader2 className="h-3 w-3 animate-spin" />
                  컬럼 로딩 중...
                </div>
              ) : (
                <Select
                  value={config.columnName || ""}
                  onValueChange={(value) => updateConfig("columnName", value)}
                >
                  <SelectTrigger className="h-8 text-sm">
                    <SelectValue placeholder="컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {categoryColumns.map((col) => (
                      <SelectItem key={col.columnName} value={col.columnName}>
                        {col.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
          )}
        </div>
      )}

      {/* 데이터 매핑 설정 */}
      {bizType === "data-mapping" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <ArrowRightLeft className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">데이터 매핑 설정</span>
          </div>

          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">소스 테이블</p>
            {loadingTables ? (
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Loader2 className="h-3 w-3 animate-spin" />
                테이블 로딩 중...
              </div>
            ) : (
              <Select
                value={config.sourceTable || ""}
                onValueChange={(value) => updateConfig("sourceTable", value)}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="소스 테이블 선택" />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">대상 테이블</p>
            {loadingTables ? (
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Loader2 className="h-3 w-3 animate-spin" />
                테이블 로딩 중...
              </div>
            ) : (
              <Select
                value={config.targetTable || ""}
                onValueChange={(value) => updateConfig("targetTable", value)}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="대상 테이블 선택" />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>
        </div>
      )}

      {/* 관련 데이터 설정 */}
      {bizType === "related-data" && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Link2 className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">관련 데이터 설정</span>
          </div>

          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">관련 테이블</p>
            {loadingTables ? (
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Loader2 className="h-3 w-3 animate-spin" />
                테이블 로딩 중...
              </div>
            ) : (
              <Select
                value={config.relatedTable || ""}
                onValueChange={(value) => {
                  updateConfig("relatedTable", value);
                  updateConfig("linkColumn", "");
                }}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="관련 테이블 선택" />
                </SelectTrigger>
                <SelectContent>
                  {tables.map((table) => (
                    <SelectItem key={table.tableName} value={table.tableName}>
                      {table.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          {config.relatedTable && (
            <div>
              <p className="mb-1.5 text-xs text-muted-foreground">연결 컬럼</p>
              <Select
                value={config.linkColumn || ""}
                onValueChange={(value) => updateConfig("linkColumn", value)}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder="컬럼 선택" />
                </SelectTrigger>
                <SelectContent>
                  {relatedColumns.map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.displayName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="flex items-center justify-between py-1">
            <span className="text-xs text-muted-foreground">버튼 텍스트</span>
            <Input
              value={config.buttonText || ""}
              onChange={(e) => updateConfig("buttonText", e.target.value)}
              placeholder="관련 데이터 보기"
              className="h-7 w-[160px] text-xs"
            />
          </div>
        </div>
      )}
    </div>
  );
};

V2BizConfigPanel.displayName = "V2BizConfigPanel";

export default V2BizConfigPanel;
