"use client";

import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Button,
  Badge,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  Input,
  Textarea,
  Alert,
  AlertDescription,
} from "../../../../components/ui";
import { RAGEngine, RAGConfig } from "../../../../rag";
import { DocumentUploader } from "./document-uploader";
import { KnowledgeEditor } from "./knowledge-editor";
import { RAGManager } from "./rag-manager";
import {
  useKeyboardShortcuts,
  createAdminShortcuts,
} from "../../../../hooks/useKeyboardShortcuts";
import {
  useConfirmationDialog,
  confirmDelete,
  confirmAction,
} from "../../../../components/ui/confirmation-dialog";
import { useDebounce } from "../../../../hooks/usePerformance";

interface KnowledgeManagementProps {
  ragConfig?: RAGConfig;
}

type TabType = "documents" | "knowledge" | "management" | "overview";

export function KnowledgeManagement({ ragConfig }: KnowledgeManagementProps) {
  const [activeTab, setActiveTab] = useState<TabType>("overview");
  const [ragEngine, setRAGEngine] = useState<RAGEngine | null>(null);
  const [isInitializing, setIsInitializing] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [stats, setStats] = useState({
    totalDocuments: 0,
    totalKnowledgeEntries: 0,
    totalChunks: 0,
    lastActivity: null as string | null,
  });

  // Confirmation dialog for destructive actions
  const { showConfirmation, ConfirmationDialog } = useConfirmationDialog();

  // Debounced search for better performance
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearch = useDebounce(searchTerm, 300);

  useEffect(() => {
    initializeRAGEngine();
  }, [ragConfig]);

  const initializeRAGEngine = async () => {
    try {
      setIsInitializing(true);
      setError(null);

      // Use provided config or create default
      const config: RAGConfig = ragConfig || {
        embeddingModel: "text-embedding-ada-002",
        chunkSize: 1000,
        chunkOverlap: 200,
        vectorStorePath: "./vector_store",
        llmConfig: {
          modelName: "gpt-4",
          temperature: 0.7,
          maxTokens: 2000,
          apiKey: process.env.OPENAI_API_KEY || "",
        },
        supabaseConfig: {
          url: process.env.NEXT_PUBLIC_SUPABASE_URL || "",
          anonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "",
          bucket: "documents",
        },
      };

      const engine = new RAGEngine(config);
      await engine.initialize();

      setRAGEngine(engine);
      await loadStats(engine);
    } catch (err) {
      console.error("RAG Engine 초기화 실패:", err);
      setError(
        `RAG 시스템 초기화에 실패했습니다: ${
          err instanceof Error ? err.message : "알 수 없는 오류"
        }`
      );
    } finally {
      setIsInitializing(false);
    }
  };

  const loadStats = async (engine: RAGEngine) => {
    try {
      const ragStats = await engine.getStats();

      // Load knowledge entries from localStorage
      const knowledgeEntries = localStorage.getItem("knowledge-entries");
      const knowledgeCount = knowledgeEntries
        ? JSON.parse(knowledgeEntries).length
        : 0;

      setStats({
        totalDocuments: ragStats.documentCount,
        totalKnowledgeEntries: knowledgeCount,
        totalChunks: ragStats.chunkCount,
        lastActivity: new Date().toISOString(),
      });
    } catch (err) {
      console.error("통계 로드 실패:", err);
    }
  };

  const handleDocumentUploaded = async () => {
    if (ragEngine) {
      await loadStats(ragEngine);
    }
  };

  const handleKnowledgeUpdated = async () => {
    if (ragEngine) {
      await loadStats(ragEngine);
    }
  };

  const handleRetrain = async () => {
    if (!ragEngine) return;

    try {
      // Clear and reinitialize the vector store
      await ragEngine.clear();
      await ragEngine.initialize();
      await loadStats(ragEngine);
    } catch (err) {
      console.error("재훈련 실패:", err);
      setError(
        `재훈련에 실패했습니다: ${
          err instanceof Error ? err.message : "알 수 없는 오류"
        }`
      );
    }
  };

  // Enhanced retrain with confirmation
  const handleRetrainWithConfirmation = useCallback(() => {
    confirmAction(
      showConfirmation,
      "시스템 재훈련",
      "RAG 시스템을 재훈련하면 모든 벡터 데이터가 다시 생성됩니다. 계속하시겠습니까?",
      handleRetrain,
      "재훈련"
    );
  }, [showConfirmation]);

  // Clear all data with confirmation
  const handleClearData = useCallback(() => {
    confirmDelete(showConfirmation, "모든 데이터", async () => {
      if (ragEngine) {
        await ragEngine.clear();
        await loadStats(ragEngine);
      }
    });
  }, [showConfirmation, ragEngine]);

  // Keyboard shortcuts
  const shortcuts = createAdminShortcuts({
    onRefresh: () => ragEngine && loadStats(ragEngine),
    onEscape: () => setActiveTab("overview"),
    onNew: () => setActiveTab("documents"),
    onSearch: () => {
      // Focus search input if available
      const searchInput = document.querySelector(
        'input[type="search"]'
      ) as HTMLInputElement;
      if (searchInput) searchInput.focus();
    },
  });

  useKeyboardShortcuts(shortcuts);

  const tabs = [
    { id: "overview" as TabType, name: "개요", icon: "📊" },
    { id: "documents" as TabType, name: "문서 관리", icon: "📄" },
    { id: "knowledge" as TabType, name: "지식 편집", icon: "✏️" },
    { id: "management" as TabType, name: "RAG 관리", icon: "⚙️" },
  ];

  if (isInitializing) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center space-y-4">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="text-gray-600">RAG 시스템을 초기화하고 있습니다...</p>
        </div>
      </div>
    );
  }

  if (error || !ragEngine) {
    return (
      <div className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle className="text-red-600">초기화 오류</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-800 mb-4">
              {error || "RAG 엔진을 초기화할 수 없습니다."}
            </p>
            <Button onClick={initializeRAGEngine}>다시 시도</Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            🧠 지식 베이스 관리 시스템
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-gray-600 mb-4">
            RAG 기반 챗봇을 위한 통합 지식 베이스 관리 시스템입니다. 문서
            업로드, 지식 편집, 품질 모니터링을 한 곳에서 관리할 수 있습니다.
          </p>

          {/* Quick Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-blue-50 p-3 rounded-lg">
              <div className="text-2xl font-bold text-blue-600">
                {stats.totalDocuments}
              </div>
              <div className="text-sm text-blue-800">총 문서</div>
            </div>
            <div className="bg-green-50 p-3 rounded-lg">
              <div className="text-2xl font-bold text-green-600">
                {stats.totalKnowledgeEntries}
              </div>
              <div className="text-sm text-green-800">지식 항목</div>
            </div>
            <div className="bg-purple-50 p-3 rounded-lg">
              <div className="text-2xl font-bold text-purple-600">
                {stats.totalChunks}
              </div>
              <div className="text-sm text-purple-800">텍스트 청크</div>
            </div>
            <div className="bg-orange-50 p-3 rounded-lg">
              <div className="text-2xl font-bold text-orange-600">
                {stats.lastActivity ? "활성" : "비활성"}
              </div>
              <div className="text-sm text-orange-800">시스템 상태</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Navigation Tabs */}
      <Card>
        <CardContent className="p-0">
          <div className="flex border-b">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex-1 flex items-center justify-center gap-2 py-4 px-6 border-b-2 transition-colors ${
                  activeTab === tab.id
                    ? "border-blue-500 text-blue-600 bg-blue-50"
                    : "border-transparent text-gray-600 hover:text-gray-800 hover:bg-gray-50"
                }`}
              >
                <span className="text-lg">{tab.icon}</span>
                <span className="font-medium">{tab.name}</span>
              </button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Tab Content */}
      <div className="min-h-[600px]">
        {activeTab === "overview" && (
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>시스템 개요</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <h3 className="font-semibold mb-3">주요 기능</h3>
                    <ul className="space-y-2 text-sm">
                      <li className="flex items-center gap-2">
                        <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                        문서 업로드 및 자동 처리
                      </li>
                      <li className="flex items-center gap-2">
                        <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                        마크다운 기반 지식 편집
                      </li>
                      <li className="flex items-center gap-2">
                        <span className="w-2 h-2 bg-purple-500 rounded-full"></span>
                        검색 품질 모니터링
                      </li>
                      <li className="flex items-center gap-2">
                        <span className="w-2 h-2 bg-orange-500 rounded-full"></span>
                        자동 지식 격차 분석
                      </li>
                    </ul>
                  </div>
                  <div>
                    <h3 className="font-semibold mb-3">시스템 상태</h3>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span>벡터 저장소:</span>
                        <span className="text-green-600">활성</span>
                      </div>
                      <div className="flex justify-between">
                        <span>임베딩 모델:</span>
                        <span>text-embedding-ada-002</span>
                      </div>
                      <div className="flex justify-between">
                        <span>검색 엔진:</span>
                        <span className="text-green-600">하이브리드</span>
                      </div>
                      <div className="flex justify-between">
                        <span>마지막 업데이트:</span>
                        <span>
                          {stats.lastActivity
                            ? new Date(stats.lastActivity).toLocaleString()
                            : "N/A"}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>빠른 액션</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <Button
                    onClick={() => setActiveTab("documents")}
                    className="h-20 flex-col gap-2"
                  >
                    <span className="text-2xl">📄</span>
                    <span>문서 업로드</span>
                  </Button>
                  <Button
                    onClick={() => setActiveTab("knowledge")}
                    variant="outline"
                    className="h-20 flex-col gap-2"
                  >
                    <span className="text-2xl">✏️</span>
                    <span>지식 추가</span>
                  </Button>
                  <Button
                    onClick={() => setActiveTab("management")}
                    variant="outline"
                    className="h-20 flex-col gap-2"
                  >
                    <span className="text-2xl">🔍</span>
                    <span>품질 테스트</span>
                  </Button>
                  <Button
                    onClick={handleRetrainWithConfirmation}
                    variant="outline"
                    className="h-20 flex-col gap-2"
                  >
                    <span className="text-2xl">🔄</span>
                    <span>재훈련</span>
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {activeTab === "documents" && (
          <DocumentUploader
            ragEngine={ragEngine}
            onDocumentUploaded={handleDocumentUploaded}
            onDocumentDeleted={handleDocumentUploaded}
          />
        )}

        {activeTab === "knowledge" && (
          <KnowledgeEditor
            ragEngine={ragEngine}
            onEntryCreated={handleKnowledgeUpdated}
            onEntryUpdated={handleKnowledgeUpdated}
            onEntryDeleted={handleKnowledgeUpdated}
          />
        )}

        {activeTab === "management" && (
          <RAGManager
            ragEngine={ragEngine}
            onRetrainTriggered={handleRetrain}
          />
        )}
      </div>

      {/* Confirmation Dialog */}
      <ConfirmationDialog />
    </div>
  );
}
