"use client";

import React, { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { RefreshCw, Save, ArrowLeft, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { BatchAPI, BatchConfig, BatchMapping, ConnectionInfo } from "@/lib/api/batch";

interface BatchColumnInfo {
  column_name: string;
  data_type: string;
  is_nullable: string;
}

// 배치 타입 감지 함수
const detectBatchType = (mapping: BatchMapping): 'db-to-db' | 'restapi-to-db' | 'db-to-restapi' => {
  const fromType = mapping.from_connection_type;
  const toType = mapping.to_connection_type;
  
  if (fromType === 'restapi' && (toType === 'internal' || toType === 'external')) {
    return 'restapi-to-db';
  } else if ((fromType === 'internal' || fromType === 'external') && toType === 'restapi') {
    return 'db-to-restapi';
  } else {
    return 'db-to-db';
  }
};

export default function BatchEditPage() {
  const params = useParams();
  const router = useRouter();
  const batchId = parseInt(params.id as string);

  // 기본 상태
  const [loading, setLoading] = useState(false);
  const [batchConfig, setBatchConfig] = useState<BatchConfig | null>(null);
  const [batchName, setBatchName] = useState("");
  const [cronSchedule, setCronSchedule] = useState("0 12 * * *");
  const [description, setDescription] = useState("");
  const [isActive, setIsActive] = useState("Y");

  // 연결 정보
  const [connections, setConnections] = useState<ConnectionInfo[]>([]);
  const [fromConnection, setFromConnection] = useState<ConnectionInfo | null>(null);
  const [toConnection, setToConnection] = useState<ConnectionInfo | null>(null);
  
  // 테이블 및 컬럼 정보
  const [fromTables, setFromTables] = useState<string[]>([]);
  const [toTables, setToTables] = useState<string[]>([]);
  const [fromTable, setFromTable] = useState("");
  const [toTable, setToTable] = useState("");
  const [fromColumns, setFromColumns] = useState<BatchColumnInfo[]>([]);
  const [toColumns, setToColumns] = useState<BatchColumnInfo[]>([]);
  
  // 매핑 정보
  const [mappings, setMappings] = useState<BatchMapping[]>([]);
  
  // 배치 타입 감지
  const [batchType, setBatchType] = useState<'db-to-db' | 'restapi-to-db' | 'db-to-restapi' | null>(null);

  // 페이지 로드 시 배치 정보 조회
  useEffect(() => {
    if (batchId) {
      loadBatchConfig();
      loadConnections();
    }
  }, [batchId]);

  // 연결 정보가 로드된 후 배치 설정의 연결 정보 설정
  useEffect(() => {
    if (batchConfig && connections.length > 0 && batchConfig.batch_mappings && batchConfig.batch_mappings.length > 0) {
      const firstMapping = batchConfig.batch_mappings[0];
      console.log("🔗 연결 정보 설정 시작:", firstMapping);
      
      // FROM 연결 정보 설정
      if (firstMapping.from_connection_type === 'internal') {
        setFromConnection({ type: 'internal', name: '내부 DB' });
        // 내부 DB 테이블 목록 로드
        BatchAPI.getTablesFromConnection({ type: 'internal', name: '내부 DB' }).then(tables => {
          console.log("📋 FROM 테이블 목록:", tables);
          setFromTables(tables);
          
          // 컬럼 정보도 로드
          if (firstMapping.from_table_name) {
            BatchAPI.getTableColumns({ type: 'internal', name: '내부 DB' }, firstMapping.from_table_name).then(columns => {
              console.log("📊 FROM 컬럼 목록:", columns);
              setFromColumns(columns);
            });
          }
        });
      } else if (firstMapping.from_connection_id) {
        const fromConn = connections.find(c => c.id === firstMapping.from_connection_id);
        if (fromConn) {
          setFromConnection(fromConn);
          // 외부 DB 테이블 목록 로드
          BatchAPI.getTablesFromConnection(fromConn).then(tables => {
            console.log("📋 FROM 테이블 목록:", tables);
            setFromTables(tables);
            
            // 컬럼 정보도 로드
            if (firstMapping.from_table_name) {
              BatchAPI.getTableColumns(fromConn, firstMapping.from_table_name).then(columns => {
                console.log("📊 FROM 컬럼 목록:", columns);
                setFromColumns(columns);
              });
            }
          });
        }
      }
      
      // TO 연결 정보 설정
      if (firstMapping.to_connection_type === 'internal') {
        setToConnection({ type: 'internal', name: '내부 DB' });
        // 내부 DB 테이블 목록 로드
        BatchAPI.getTablesFromConnection({ type: 'internal', name: '내부 DB' }).then(tables => {
          console.log("📋 TO 테이블 목록:", tables);
          setToTables(tables);
          
          // 컬럼 정보도 로드
          if (firstMapping.to_table_name) {
            BatchAPI.getTableColumns({ type: 'internal', name: '내부 DB' }, firstMapping.to_table_name).then(columns => {
              console.log("📊 TO 컬럼 목록:", columns);
              setToColumns(columns);
            });
          }
        });
      } else if (firstMapping.to_connection_id) {
        const toConn = connections.find(c => c.id === firstMapping.to_connection_id);
        if (toConn) {
          setToConnection(toConn);
          // 외부 DB 테이블 목록 로드
          BatchAPI.getTablesFromConnection(toConn).then(tables => {
            console.log("📋 TO 테이블 목록:", tables);
            setToTables(tables);
            
            // 컬럼 정보도 로드
            if (firstMapping.to_table_name) {
              BatchAPI.getTableColumns(toConn, firstMapping.to_table_name).then(columns => {
                console.log("📊 TO 컬럼 목록:", columns);
                setToColumns(columns);
              });
            }
          });
        }
      }
    }
  }, [batchConfig, connections]);

  // 배치 설정 조회
  const loadBatchConfig = async () => {
    try {
      setLoading(true);
      console.log("🔍 배치 설정 조회 시작:", batchId);
      
      const config = await BatchAPI.getBatchConfig(batchId);
      console.log("📋 조회된 배치 설정:", config);
      
      setBatchConfig(config);
      setBatchName(config.batch_name);
      setCronSchedule(config.cron_schedule);
      setDescription(config.description || "");
      setIsActive(config.is_active || "Y");
      
      if (config.batch_mappings && config.batch_mappings.length > 0) {
        console.log("📊 매핑 정보:", config.batch_mappings);
        console.log("📊 매핑 개수:", config.batch_mappings.length);
        config.batch_mappings.forEach((mapping, idx) => {
          console.log(`📊 매핑 #${idx + 1}:`, {
            from: `${mapping.from_column_name} (${mapping.from_column_type})`,
            to: `${mapping.to_column_name} (${mapping.to_column_type})`,
            type: mapping.mapping_type
          });
        });
        setMappings(config.batch_mappings);
        
        // 첫 번째 매핑에서 연결 및 테이블 정보 추출
        const firstMapping = config.batch_mappings[0];
        setFromTable(firstMapping.from_table_name);
        setToTable(firstMapping.to_table_name);
        
        // 배치 타입 감지
        const detectedBatchType = detectBatchType(firstMapping);
        setBatchType(detectedBatchType);
        console.log("🎯 감지된 배치 타입:", detectedBatchType);
        
        // FROM 연결 정보 설정
        if (firstMapping.from_connection_type === 'internal') {
          setFromConnection({ type: 'internal', name: '내부 DB' });
        } else if (firstMapping.from_connection_id) {
          // 외부 연결은 connections 로드 후 설정
          setTimeout(() => {
            const fromConn = connections.find(c => c.id === firstMapping.from_connection_id);
            if (fromConn) {
              setFromConnection(fromConn);
            }
          }, 100);
        }
        
        // TO 연결 정보 설정
        if (firstMapping.to_connection_type === 'internal') {
          setToConnection({ type: 'internal', name: '내부 DB' });
        } else if (firstMapping.to_connection_id) {
          // 외부 연결은 connections 로드 후 설정
          setTimeout(() => {
            const toConn = connections.find(c => c.id === firstMapping.to_connection_id);
            if (toConn) {
              setToConnection(toConn);
            }
          }, 100);
        }
        
        console.log("🔗 테이블 정보 설정:", {
          fromTable: firstMapping.from_table_name,
          toTable: firstMapping.to_table_name,
          fromConnectionType: firstMapping.from_connection_type,
          toConnectionType: firstMapping.to_connection_type
        });
      }
      
    } catch (error) {
      console.error("❌ 배치 설정 조회 오류:", error);
      toast.error("배치 설정을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  // 연결 정보 조회
  const loadConnections = async () => {
    try {
      const connectionList = await BatchAPI.getConnections();
      setConnections(connectionList);
    } catch (error) {
      console.error("연결 정보 조회 오류:", error);
      toast.error("연결 정보를 불러오는데 실패했습니다.");
    }
  };

  // FROM 연결 변경 시
  const handleFromConnectionChange = async (connectionId: string) => {
    const connection = connections.find(c => c.id?.toString() === connectionId) || 
                     (connectionId === 'internal' ? { type: 'internal' as const, name: '내부 DB' } : null);
    
    if (connection) {
      setFromConnection(connection);
      
      try {
        const tables = await BatchAPI.getTablesFromConnection(connection);
        setFromTables(tables);
        setFromTable("");
        setFromColumns([]);
      } catch (error) {
        console.error("테이블 목록 조회 오류:", error);
        toast.error("테이블 목록을 불러오는데 실패했습니다.");
      }
    }
  };

  // TO 연결 변경 시
  const handleToConnectionChange = async (connectionId: string) => {
    const connection = connections.find(c => c.id?.toString() === connectionId) || 
                     (connectionId === 'internal' ? { type: 'internal' as const, name: '내부 DB' } : null);
    
    if (connection) {
      setToConnection(connection);
      
      try {
        const tables = await BatchAPI.getTablesFromConnection(connection);
        setToTables(tables);
        setToTable("");
        setToColumns([]);
      } catch (error) {
        console.error("테이블 목록 조회 오류:", error);
        toast.error("테이블 목록을 불러오는데 실패했습니다.");
      }
    }
  };

  // FROM 테이블 변경 시
  const handleFromTableChange = async (tableName: string) => {
    setFromTable(tableName);
    
    if (fromConnection && tableName) {
      try {
        const columns = await BatchAPI.getTableColumns(fromConnection, tableName);
        setFromColumns(columns);
      } catch (error) {
        console.error("컬럼 정보 조회 오류:", error);
        toast.error("컬럼 정보를 불러오는데 실패했습니다.");
      }
    }
  };

  // TO 테이블 변경 시
  const handleToTableChange = async (tableName: string) => {
    setToTable(tableName);
    
    if (toConnection && tableName) {
      try {
        const columns = await BatchAPI.getTableColumns(toConnection, tableName);
        setToColumns(columns);
      } catch (error) {
        console.error("컬럼 정보 조회 오류:", error);
        toast.error("컬럼 정보를 불러오는데 실패했습니다.");
      }
    }
  };

  // 매핑 추가
  const addMapping = () => {
    const newMapping: BatchMapping = {
      from_connection_type: fromConnection?.type === 'internal' ? 'internal' : 'external',
      from_connection_id: fromConnection?.type === 'internal' ? undefined : fromConnection?.id,
      from_table_name: fromTable,
      from_column_name: '',
      from_column_type: '',
      to_connection_type: toConnection?.type === 'internal' ? 'internal' : 'external',
      to_connection_id: toConnection?.type === 'internal' ? undefined : toConnection?.id,
      to_table_name: toTable,
      to_column_name: '',
      to_column_type: '',
      mapping_type: 'direct',
      mapping_order: mappings.length + 1
    };
    
    setMappings([...mappings, newMapping]);
  };

  // 매핑 삭제
  const removeMapping = (index: number) => {
    const updatedMappings = mappings.filter((_, i) => i !== index);
    setMappings(updatedMappings);
  };

  // 매핑 업데이트
  const updateMapping = (index: number, field: keyof BatchMapping, value: any) => {
    const updatedMappings = [...mappings];
    updatedMappings[index] = { ...updatedMappings[index], [field]: value };
    setMappings(updatedMappings);
  };

  // 배치 설정 저장
  const saveBatchConfig = async () => {
    if (!batchName || !cronSchedule || mappings.length === 0) {
      toast.error("필수 항목을 모두 입력해주세요.");
      return;
    }

    try {
      setLoading(true);
      
      await BatchAPI.updateBatchConfig(batchId, {
        batchName,
        description,
        cronSchedule,
        isActive,
        mappings
      });
      
      toast.success("배치 설정이 성공적으로 수정되었습니다.");
      router.push("/admin/batchmng");
      
    } catch (error) {
      console.error("배치 설정 수정 실패:", error);
      toast.error("배치 설정 수정에 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  if (loading && !batchConfig) {
    return (
      <div className="container mx-auto p-6">
        <div className="flex items-center justify-center h-64">
          <RefreshCw className="w-8 h-8 animate-spin" />
          <span className="ml-2">배치 설정을 불러오는 중...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button
            variant="outline"
            onClick={() => router.push("/admin/batchmng")}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            목록으로
          </Button>
          <h1 className="text-3xl font-bold">배치 설정 수정</h1>
        </div>
        <div className="flex space-x-2">
          <Button onClick={loadBatchConfig} variant="outline" disabled={loading}>
            <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            새로고침
          </Button>
          <Button onClick={saveBatchConfig} disabled={loading}>
            <Save className="w-4 h-4 mr-2" />
            저장
          </Button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="batchName">배치명 *</Label>
              <Input
                id="batchName"
                value={batchName}
                onChange={(e) => setBatchName(e.target.value)}
                placeholder="배치명을 입력하세요"
              />
            </div>
            <div>
              <Label htmlFor="cronSchedule">실행 스케줄 (Cron) *</Label>
              <Input
                id="cronSchedule"
                value={cronSchedule}
                onChange={(e) => setCronSchedule(e.target.value)}
                placeholder="0 12 * * *"
              />
            </div>
          </div>
          
          <div>
            <Label htmlFor="description">설명</Label>
            <Textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="배치에 대한 설명을 입력하세요"
              rows={3}
            />
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="isActive"
              checked={isActive === 'Y'}
              onCheckedChange={(checked) => setIsActive(checked ? 'Y' : 'N')}
            />
            <Label htmlFor="isActive">활성화</Label>
          </div>
        </CardContent>
      </Card>

      {/* 배치 타입 표시 */}
      {batchType && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <span>배치 타입</span>
              <Badge variant="outline">
                {batchType === 'db-to-db' && 'DB → DB'}
                {batchType === 'restapi-to-db' && 'REST API → DB'}
                {batchType === 'db-to-restapi' && 'DB → REST API'}
              </Badge>
            </CardTitle>
          </CardHeader>
        </Card>
      )}

      {/* 연결 설정 */}
      <Card>
        <CardHeader>
          <CardTitle>연결 설정</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {batchType === 'db-to-db' && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* FROM 설정 */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">FROM (소스)</h3>
              
              <div>
                <Label>연결</Label>
                <Select 
                  value={fromConnection?.type === 'internal' ? 'internal' : fromConnection?.id?.toString() || ''}
                  onValueChange={handleFromConnectionChange}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="소스 연결을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="internal">내부 DB</SelectItem>
                    {connections.filter(conn => conn.id).map((conn) => (
                      <SelectItem key={conn.id} value={conn.id!.toString()}>
                        {conn.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>테이블</Label>
                <Select value={fromTable} onValueChange={handleFromTableChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="소스 테이블을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {fromTables.map((table) => (
                      <SelectItem key={table} value={table}>
                        {table}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              </div>

              {/* TO 설정 */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">TO (대상)</h3>
              
              <div>
                <Label>연결</Label>
                <Select 
                  value={toConnection?.type === 'internal' ? 'internal' : toConnection?.id?.toString() || ''}
                  onValueChange={handleToConnectionChange}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="대상 연결을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="internal">내부 DB</SelectItem>
                    {connections.filter(conn => conn.id).map((conn) => (
                      <SelectItem key={conn.id} value={conn.id!.toString()}>
                        {conn.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>테이블</Label>
                <Select value={toTable} onValueChange={handleToTableChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="대상 테이블을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {toTables.map((table) => (
                      <SelectItem key={table} value={table}>
                        {table}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              </div>
            </div>
          )}

          {batchType === 'restapi-to-db' && (
            <div className="space-y-6">
              <div className="text-center py-4 bg-blue-50 rounded-lg">
                <h3 className="text-lg font-semibold text-blue-800">REST API → DB 배치</h3>
                <p className="text-sm text-blue-600">외부 REST API에서 데이터를 가져와 데이터베이스에 저장합니다.</p>
              </div>
              
              {mappings.length > 0 && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>API URL</Label>
                    <Input value={mappings[0]?.from_api_url || ''} readOnly />
                  </div>
                  <div>
                    <Label>API 엔드포인트</Label>
                    <Input value={mappings[0]?.from_table_name || ''} readOnly />
                  </div>
                  <div>
                    <Label>HTTP 메서드</Label>
                    <Input value={mappings[0]?.from_api_method || 'GET'} readOnly />
                  </div>
                  <div>
                    <Label>대상 테이블</Label>
                    <Input value={mappings[0]?.to_table_name || ''} readOnly />
                  </div>
                </div>
              )}
            </div>
          )}

          {batchType === 'db-to-restapi' && (
            <div className="space-y-6">
              <div className="text-center py-4 bg-green-50 rounded-lg">
                <h3 className="text-lg font-semibold text-green-800">DB → REST API 배치</h3>
                <p className="text-sm text-green-600">데이터베이스에서 데이터를 가져와 외부 REST API로 전송합니다.</p>
              </div>
              
              {mappings.length > 0 && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>소스 테이블</Label>
                    <Input value={mappings[0]?.from_table_name || ''} readOnly />
                  </div>
                  <div>
                    <Label>API URL</Label>
                    <Input value={mappings[0]?.to_api_url || ''} readOnly />
                  </div>
                  <div>
                    <Label>API 엔드포인트</Label>
                    <Input value={mappings[0]?.to_table_name || ''} readOnly />
                  </div>
                  <div>
                    <Label>HTTP 메서드</Label>
                    <Input value={mappings[0]?.to_api_method || 'POST'} readOnly />
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 컬럼 매핑 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            {batchType === 'db-to-db' && '컬럼 매핑'}
            {batchType === 'restapi-to-db' && 'API 필드 → DB 컬럼 매핑'}
            {batchType === 'db-to-restapi' && 'DB 컬럼 → API 필드 매핑'}
            {batchType === 'db-to-db' && (
              <Button onClick={addMapping} size="sm">
                <Plus className="w-4 h-4 mr-2" />
                매핑 추가
              </Button>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {mappings.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              {batchType === 'db-to-db' && '매핑을 추가해주세요.'}
              {batchType === 'restapi-to-db' && 'API 필드와 DB 컬럼 매핑 정보가 없습니다.'}
              {batchType === 'db-to-restapi' && 'DB 컬럼과 API 필드 매핑 정보가 없습니다.'}
            </div>
          ) : (
            <div className="space-y-4">
              {batchType === 'db-to-db' && mappings.map((mapping, index) => (
                <div key={index} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <h4 className="font-medium">매핑 #{index + 1}</h4>
                      {mapping.from_column_name && mapping.to_column_name && (
                        <p className="text-sm text-gray-600">
                          {mapping.from_column_name} → {mapping.to_column_name}
                        </p>
                      )}
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => removeMapping(index)}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>FROM 컬럼</Label>
                      <Select
                        value={mapping.from_column_name || ''}
                        onValueChange={(value) => {
                          console.log(`📝 FROM 컬럼 변경: ${value}`);
                          updateMapping(index, 'from_column_name', value);
                          // 컬럼 타입도 함께 업데이트
                          const selectedColumn = fromColumns.find(col => col.column_name === value);
                          if (selectedColumn) {
                            updateMapping(index, 'from_column_type', selectedColumn.data_type);
                          }
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="소스 컬럼 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {fromColumns.map((column) => (
                            <SelectItem key={column.column_name} value={column.column_name}>
                              {column.column_name} ({column.data_type})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {fromColumns.length === 0 && (
                        <p className="text-xs text-gray-500 mt-1">
                          소스 테이블을 선택하면 컬럼 목록이 표시됩니다.
                        </p>
                      )}
                    </div>
                    
                    <div>
                      <Label>TO 컬럼</Label>
                      <Select
                        value={mapping.to_column_name || ''}
                        onValueChange={(value) => {
                          console.log(`📝 TO 컬럼 변경: ${value}`);
                          updateMapping(index, 'to_column_name', value);
                          // 컬럼 타입도 함께 업데이트
                          const selectedColumn = toColumns.find(col => col.column_name === value);
                          if (selectedColumn) {
                            updateMapping(index, 'to_column_type', selectedColumn.data_type);
                          }
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="대상 컬럼 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {toColumns.map((column) => (
                            <SelectItem key={column.column_name} value={column.column_name}>
                              {column.column_name} ({column.data_type})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {toColumns.length === 0 && (
                        <p className="text-xs text-gray-500 mt-1">
                          대상 테이블을 선택하면 컬럼 목록이 표시됩니다.
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              ))}
              
              {batchType === 'restapi-to-db' && mappings.map((mapping, index) => (
                <div key={index} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <h4 className="font-medium">매핑 #{index + 1}</h4>
                      <p className="text-sm text-gray-600">
                        API 필드: {mapping.from_column_name} → DB 컬럼: {mapping.to_column_name}
                      </p>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>API 필드명</Label>
                      <Input value={mapping.from_column_name || ''} readOnly />
                    </div>
                    <div>
                      <Label>DB 컬럼명</Label>
                      <Input value={mapping.to_column_name || ''} readOnly />
                    </div>
                  </div>
                </div>
              ))}
              
              {batchType === 'db-to-restapi' && mappings.map((mapping, index) => (
                <div key={index} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <h4 className="font-medium">매핑 #{index + 1}</h4>
                      <p className="text-sm text-gray-600">
                        DB 컬럼: {mapping.from_column_name} → API 필드: {mapping.to_column_name}
                      </p>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label>DB 컬럼명</Label>
                      <Input value={mapping.from_column_name || ''} readOnly />
                    </div>
                    <div>
                      <Label>API 필드명</Label>
                      <Input value={mapping.to_column_name || ''} readOnly />
                    </div>
                  </div>
                  
                  {mapping.to_api_body && (
                    <div className="mt-4">
                      <Label>Request Body 템플릿</Label>
                      <Textarea 
                        value={mapping.to_api_body} 
                        readOnly 
                        rows={3}
                        className="font-mono text-sm"
                      />
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 저장 버튼 */}
      <div className="flex justify-end space-x-4">
        <Button
          variant="outline"
          onClick={() => router.push("/admin/batchmng")}
        >
          취소
        </Button>
        <Button
          onClick={saveBatchConfig}
          disabled={loading || mappings.length === 0}
          className="flex items-center space-x-2"
        >
          {loading ? (
            <RefreshCw className="h-4 w-4 animate-spin" />
          ) : (
            <Save className="h-4 w-4" />
          )}
          <span>{loading ? "저장 중..." : "배치 설정 저장"}</span>
        </Button>
      </div>
    </div>
  );
}
