"use client";

import React, { useState, useEffect } from "react";
import { ChartDataSource } from "@/components/admin/dashboard/types";
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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, CheckCircle, XCircle } from "lucide-react";

interface MultiDatabaseConfigProps {
  dataSource: ChartDataSource;
  onChange: (updates: Partial<ChartDataSource>) => void;
}

interface ExternalConnection {
  id: string;
  name: string;
  type: string;
}

export default function MultiDatabaseConfig({ dataSource, onChange }: MultiDatabaseConfigProps) {
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; rowCount?: number } | null>(null);
  const [externalConnections, setExternalConnections] = useState<ExternalConnection[]>([]);
  const [loadingConnections, setLoadingConnections] = useState(false);
  const [availableColumns, setAvailableColumns] = useState<string[]>([]); // 쿼리 테스트 후 발견된 컬럼 목록
  const [columnTypes, setColumnTypes] = useState<Record<string, string>>({}); // 컬럼 타입 정보
  const [sampleData, setSampleData] = useState<any[]>([]); // 샘플 데이터 (최대 3개)
  const [columnSearchTerm, setColumnSearchTerm] = useState(""); // 컬럼 검색어

  // 외부 DB 커넥션 목록 로드
  useEffect(() => {
    if (dataSource.connectionType === "external") {
      loadExternalConnections();
    }
  }, [dataSource.connectionType]);

  const loadExternalConnections = async () => {
    setLoadingConnections(true);
    try {
      // ExternalDbConnectionAPI 사용 (인증 토큰 자동 포함)
      const { ExternalDbConnectionAPI } = await import("@/lib/api/externalDbConnection");
      const connections = await ExternalDbConnectionAPI.getConnections({ is_active: "Y" });
      
      console.log("✅ 외부 DB 커넥션 로드 성공:", connections.length, "개");
      setExternalConnections(connections.map((conn: any) => ({
        id: String(conn.id),
        name: conn.connection_name,
        type: conn.db_type,
      })));
    } catch (error) {
      console.error("❌ 외부 DB 커넥션 로드 실패:", error);
      setExternalConnections([]);
    } finally {
      setLoadingConnections(false);
    }
  };

  // 쿼리 테스트
  const handleTestQuery = async () => {
    if (!dataSource.query) {
      setTestResult({ success: false, message: "SQL 쿼리를 입력해주세요" });
      return;
    }

    setTesting(true);
    setTestResult(null);

    try {
      // dashboardApi 사용 (인증 토큰 자동 포함)
      const { dashboardApi } = await import("@/lib/api/dashboard");
      
      if (dataSource.connectionType === "external" && dataSource.externalConnectionId) {
        // 외부 DB
        const { ExternalDbConnectionAPI } = await import("@/lib/api/externalDbConnection");
        const result = await ExternalDbConnectionAPI.executeQuery(
          parseInt(dataSource.externalConnectionId),
          dataSource.query
        );
        
        if (result.success && result.data) {
          const rows = Array.isArray(result.data.rows) ? result.data.rows : [];
          const rowCount = rows.length;
          
          // 컬럼 목록 및 타입 추출
          if (rows.length > 0) {
            const columns = Object.keys(rows[0]);
            setAvailableColumns(columns);
            
            // 컬럼 타입 분석
            const types: Record<string, string> = {};
            columns.forEach(col => {
              const value = rows[0][col];
              if (value === null || value === undefined) {
                types[col] = "unknown";
              } else if (typeof value === "number") {
                types[col] = "number";
              } else if (typeof value === "boolean") {
                types[col] = "boolean";
              } else if (typeof value === "string") {
                if (/^\d{4}-\d{2}-\d{2}/.test(value)) {
                  types[col] = "date";
                } else {
                  types[col] = "string";
                }
              } else {
                types[col] = "object";
              }
            });
            setColumnTypes(types);
            setSampleData(rows.slice(0, 3));
            
            console.log("📊 발견된 컬럼:", columns);
            console.log("📊 컬럼 타입:", types);
          }
          
          setTestResult({
            success: true,
            message: "쿼리 실행 성공",
            rowCount,
          });
        } else {
          setTestResult({ success: false, message: result.message || "쿼리 실행 실패" });
        }
      } else {
        // 현재 DB
        const result = await dashboardApi.executeQuery(dataSource.query);
        
        // 컬럼 목록 및 타입 추출
        if (result.rows && result.rows.length > 0) {
          const columns = Object.keys(result.rows[0]);
          setAvailableColumns(columns);
          
          // 컬럼 타입 분석
          const types: Record<string, string> = {};
          columns.forEach(col => {
            const value = result.rows[0][col];
            if (value === null || value === undefined) {
              types[col] = "unknown";
            } else if (typeof value === "number") {
              types[col] = "number";
            } else if (typeof value === "boolean") {
              types[col] = "boolean";
            } else if (typeof value === "string") {
              if (/^\d{4}-\d{2}-\d{2}/.test(value)) {
                types[col] = "date";
              } else {
                types[col] = "string";
              }
            } else {
              types[col] = "object";
            }
          });
          setColumnTypes(types);
          setSampleData(result.rows.slice(0, 3));
          
          console.log("📊 발견된 컬럼:", columns);
          console.log("📊 컬럼 타입:", types);
        }
        
        setTestResult({
          success: true,
          message: "쿼리 실행 성공",
          rowCount: result.rowCount || 0,
        });
      }
    } catch (error: any) {
      setTestResult({ success: false, message: error.message || "네트워크 오류" });
    } finally {
      setTesting(false);
    }
  };

  return (
    <div className="space-y-4 rounded-lg border p-4">
      <h5 className="text-sm font-semibold">Database 설정</h5>

      {/* 커넥션 타입 */}
      <div className="space-y-2">
        <Label className="text-xs">데이터베이스 연결</Label>
        <RadioGroup
          value={dataSource.connectionType || "current"}
          onValueChange={(value: "current" | "external") =>
            onChange({ connectionType: value })
          }
        >
          <div className="flex items-center space-x-2">
            <RadioGroupItem value="current" id={`current-\${dataSource.id}`} />
            <Label
              htmlFor={`current-\${dataSource.id}`}
              className="text-xs font-normal"
            >
              현재 데이터베이스
            </Label>
          </div>
          <div className="flex items-center space-x-2">
            <RadioGroupItem value="external" id={`external-\${dataSource.id}`} />
            <Label
              htmlFor={`external-\${dataSource.id}`}
              className="text-xs font-normal"
            >
              외부 데이터베이스
            </Label>
          </div>
        </RadioGroup>
      </div>

      {/* 외부 DB 선택 */}
      {dataSource.connectionType === "external" && (
        <div className="space-y-2">
          <Label htmlFor={`external-conn-\${dataSource.id}`} className="text-xs">
            외부 데이터베이스 선택 *
          </Label>
          {loadingConnections ? (
            <div className="flex h-10 items-center justify-center rounded-md border">
              <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
            </div>
          ) : (
            <Select
              value={dataSource.externalConnectionId || ""}
              onValueChange={(value) => onChange({ externalConnectionId: value })}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue placeholder="외부 DB 선택" />
              </SelectTrigger>
              <SelectContent>
                {externalConnections.map((conn) => (
                  <SelectItem key={conn.id} value={conn.id} className="text-xs">
                    {conn.name} ({conn.type})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
        </div>
      )}

      {/* SQL 쿼리 */}
      <div className="space-y-2">
        <Label htmlFor={`query-\${dataSource.id}`} className="text-xs">
          SQL 쿼리 *
        </Label>
        <Textarea
          id={`query-\${dataSource.id}`}
          value={dataSource.query || ""}
          onChange={(e) => onChange({ query: e.target.value })}
          placeholder="SELECT * FROM table_name WHERE ..."
          className="min-h-[120px] font-mono text-xs"
        />
        <p className="text-[10px] text-muted-foreground">
          SELECT 쿼리만 허용됩니다
        </p>
      </div>

      {/* 자동 새로고침 설정 */}
      <div className="space-y-2">
        <Label htmlFor={`refresh-${dataSource.id}`} className="text-xs">
          자동 새로고침 간격
        </Label>
        <Select
          value={String(dataSource.refreshInterval || 0)}
          onValueChange={(value) => onChange({ refreshInterval: Number(value) })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue placeholder="새로고침 안 함" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="0">새로고침 안 함</SelectItem>
            <SelectItem value="10">10초마다</SelectItem>
            <SelectItem value="30">30초마다</SelectItem>
            <SelectItem value="60">1분마다</SelectItem>
            <SelectItem value="300">5분마다</SelectItem>
            <SelectItem value="600">10분마다</SelectItem>
            <SelectItem value="1800">30분마다</SelectItem>
            <SelectItem value="3600">1시간마다</SelectItem>
          </SelectContent>
        </Select>
        <p className="text-[10px] text-muted-foreground">
          설정한 간격마다 자동으로 데이터를 다시 불러옵니다
        </p>
      </div>

      {/* 테스트 버튼 */}
      <div className="space-y-2 border-t pt-4">
        <Button
          variant="outline"
          size="sm"
          onClick={handleTestQuery}
          disabled={testing || !dataSource.query}
          className="h-8 w-full gap-2 text-xs"
        >
          {testing ? (
            <>
              <Loader2 className="h-3 w-3 animate-spin" />
              테스트 중...
            </>
          ) : (
            "쿼리 테스트"
          )}
        </Button>

        {testResult && (
          <div
            className={`flex items-center gap-2 rounded-md p-2 text-xs ${
              testResult.success
                ? "bg-green-50 text-green-700"
                : "bg-red-50 text-red-700"
            }`}
          >
            {testResult.success ? (
              <CheckCircle className="h-3 w-3" />
            ) : (
              <XCircle className="h-3 w-3" />
            )}
            <div>
              {testResult.message}
              {testResult.rowCount !== undefined && (
                <span className="ml-1">({testResult.rowCount}행)</span>
              )}
            </div>
          </div>
        )}
      </div>

      {/* 컬럼 선택 (메트릭 위젯용) - 개선된 UI */}
      {availableColumns.length > 0 && (
        <div className="space-y-3 border-t pt-4">
          <div className="flex items-center justify-between">
            <div>
              <Label className="text-sm font-semibold">메트릭 컬럼 선택</Label>
              <p className="text-xs text-muted-foreground mt-0.5">
                {dataSource.selectedColumns && dataSource.selectedColumns.length > 0
                  ? `${dataSource.selectedColumns.length}개 컬럼 선택됨`
                  : "모든 컬럼 표시"}
              </p>
            </div>
            <div className="flex gap-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => onChange({ selectedColumns: availableColumns })}
                className="h-7 text-xs"
              >
                전체
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => onChange({ selectedColumns: [] })}
                className="h-7 text-xs"
              >
                해제
              </Button>
            </div>
          </div>

          {/* 검색 */}
          {availableColumns.length > 5 && (
            <Input
              placeholder="컬럼 검색..."
              value={columnSearchTerm}
              onChange={(e) => setColumnSearchTerm(e.target.value)}
              className="h-8 text-xs"
            />
          )}

          {/* 컬럼 카드 그리드 */}
          <div className="grid grid-cols-1 gap-2 max-h-80 overflow-y-auto">
            {availableColumns
              .filter(col => 
                !columnSearchTerm || 
                col.toLowerCase().includes(columnSearchTerm.toLowerCase())
              )
              .map((col) => {
                const isSelected = 
                  !dataSource.selectedColumns || 
                  dataSource.selectedColumns.length === 0 || 
                  dataSource.selectedColumns.includes(col);
                
                const type = columnTypes[col] || "unknown";
                const typeIcon = {
                  number: "🔢",
                  string: "📝",
                  date: "📅",
                  boolean: "✓",
                  object: "📦",
                  unknown: "❓"
                }[type];
                
                const typeColor = {
                  number: "text-blue-600 bg-blue-50",
                  string: "text-gray-600 bg-gray-50",
                  date: "text-purple-600 bg-purple-50",
                  boolean: "text-green-600 bg-green-50",
                  object: "text-orange-600 bg-orange-50",
                  unknown: "text-gray-400 bg-gray-50"
                }[type];

                return (
                  <div
                    key={col}
                    onClick={() => {
                      const currentSelected = dataSource.selectedColumns && dataSource.selectedColumns.length > 0
                        ? dataSource.selectedColumns
                        : availableColumns;
                      
                      const newSelected = isSelected
                        ? currentSelected.filter(c => c !== col)
                        : [...currentSelected, col];
                      
                      onChange({ selectedColumns: newSelected });
                    }}
                    className={`
                      relative flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-all
                      ${isSelected 
                        ? "border-primary bg-primary/5 shadow-sm" 
                        : "border-border bg-card hover:border-primary/50 hover:bg-muted/50"
                      }
                    `}
                  >
                    {/* 체크박스 */}
                    <div className="flex-shrink-0 mt-0.5">
                      <div className={`
                        h-4 w-4 rounded border-2 flex items-center justify-center transition-colors
                        ${isSelected 
                          ? "border-primary bg-primary" 
                          : "border-gray-300 bg-background"
                        }
                      `}>
                        {isSelected && (
                          <svg className="h-3 w-3 text-primary-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                          </svg>
                        )}
                      </div>
                    </div>

                    {/* 컬럼 정보 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium truncate">{col}</span>
                        <span className={`text-xs px-1.5 py-0.5 rounded ${typeColor}`}>
                          {typeIcon} {type}
                        </span>
                      </div>
                      
                      {/* 샘플 데이터 */}
                      {sampleData.length > 0 && (
                        <div className="mt-1.5 text-xs text-muted-foreground">
                          <span className="font-medium">예시:</span>{" "}
                          {sampleData.slice(0, 2).map((row, i) => (
                            <span key={i}>
                              {String(row[col]).substring(0, 20)}
                              {String(row[col]).length > 20 && "..."}
                              {i < Math.min(sampleData.length - 1, 1) && ", "}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
          </div>

          {/* 검색 결과 없음 */}
          {columnSearchTerm && availableColumns.filter(col => 
            col.toLowerCase().includes(columnSearchTerm.toLowerCase())
          ).length === 0 && (
            <div className="text-center py-8 text-sm text-muted-foreground">
              "{columnSearchTerm}"에 대한 컬럼을 찾을 수 없습니다
            </div>
          )}
        </div>
      )}
    </div>
  );
}
