"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui";
import { Button } from "@/components/ui";
import { Input } from "@/components/ui";
import { Modal, ModalContent, ModalHeader, ModalTitle } from "@/components/ui";
import { RAGEngine } from "@/rag";

interface KnowledgeEntry {
  id: string;
  title: string;
  content: string;
  category: string;
  tags: string[];
  createdAt: string;
  updatedAt: string;
  status: "active" | "draft" | "archived";
  description?: string;
  priority?: "high" | "medium" | "low";
}

interface KnowledgeEditorProps {
  ragEngine: RAGEngine;
  onEntryCreated?: (entry: KnowledgeEntry) => void;
  onEntryUpdated?: (entry: KnowledgeEntry) => void;
  onEntryDeleted?: (entryId: string) => void;
}

export function KnowledgeEditor({
  ragEngine,
  onEntryCreated,
  onEntryUpdated,
  onEntryDeleted,
}: KnowledgeEditorProps) {
  const [entries, setEntries] = useState<KnowledgeEntry[]>([]);
  const [filteredEntries, setFilteredEntries] = useState<KnowledgeEntry[]>([]);
  const [editingEntry, setEditingEntry] = useState<KnowledgeEntry | null>(null);
  const [isEditorOpen, setIsEditorOpen] = useState(false);
  const [isBulkMode, setIsBulkMode] = useState(false);
  const [selectedEntries, setSelectedEntries] = useState<Set<string>>(
    new Set()
  );

  // Form states
  const [formData, setFormData] = useState<Partial<KnowledgeEntry>>({
    title: "",
    content: "",
    category: "",
    tags: [],
    description: "",
    priority: "medium",
    status: "active",
  });

  // Filter states
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [tagFilter, setTagFilter] = useState("");

  // Auto-save states
  const [lastSaved, setLastSaved] = useState<Date | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  // Validation states
  const [validationErrors, setValidationErrors] = useState<
    Record<string, string>
  >({});
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const autoSaveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Categories and tags from existing entries
  const categories = [
    ...new Set(entries.map((e) => e.category).filter(Boolean)),
  ];
  const allTags = [...new Set(entries.flatMap((e) => e.tags).filter(Boolean))];

  const loadEntries = useCallback(async () => {
    try {
      // This would load knowledge entries from your storage/database
      // For now, we'll use localStorage as a mock
      const stored = localStorage.getItem("knowledge-entries");
      if (stored) {
        const loadedEntries = JSON.parse(stored);
        setEntries(loadedEntries);
        setFilteredEntries(loadedEntries);
      }
    } catch (err) {
      console.error("지식 항목 로드 실패:", err);
      setError("지식 항목을 불러오는데 실패했습니다.");
    }
  }, []);

  useEffect(() => {
    loadEntries();
  }, [loadEntries]);

  // Filter entries
  useEffect(() => {
    let filtered = entries;

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (entry) =>
          entry.title.toLowerCase().includes(query) ||
          entry.content.toLowerCase().includes(query) ||
          entry.description?.toLowerCase().includes(query) ||
          entry.tags.some((tag) => tag.toLowerCase().includes(query))
      );
    }

    if (statusFilter !== "all") {
      filtered = filtered.filter((entry) => entry.status === statusFilter);
    }

    if (categoryFilter) {
      filtered = filtered.filter((entry) => entry.category === categoryFilter);
    }

    if (tagFilter) {
      filtered = filtered.filter((entry) => entry.tags.includes(tagFilter));
    }

    setFilteredEntries(filtered);
  }, [entries, searchQuery, statusFilter, categoryFilter, tagFilter]);

  const clearMessages = () => {
    setError(null);
    setSuccess(null);
  };

  const validateForm = (
    data: Partial<KnowledgeEntry>
  ): Record<string, string> => {
    const errors: Record<string, string> = {};

    if (!data.title?.trim()) {
      errors.title = "제목은 필수입니다.";
    }

    if (!data.content?.trim()) {
      errors.content = "내용은 필수입니다.";
    }

    if (data.content && data.content.trim().length < 10) {
      errors.content = "내용은 최소 10자 이상이어야 합니다.";
    }

    if (!data.category?.trim()) {
      errors.category = "카테고리는 필수입니다.";
    }

    return errors;
  };

  const saveEntry = async (
    entryData: Partial<KnowledgeEntry>,
    isAutoSave = false
  ) => {
    try {
      if (!isAutoSave) {
        const errors = validateForm(entryData);
        if (Object.keys(errors).length > 0) {
          setValidationErrors(errors);
          return false;
        }
      }

      setIsSaving(true);
      clearMessages();

      const now = new Date().toISOString();
      const entry: KnowledgeEntry = {
        id: editingEntry?.id || `kb_${Date.now()}`,
        title: entryData.title || "",
        content: entryData.content || "",
        category: entryData.category || "",
        tags: entryData.tags || [],
        description: entryData.description || "",
        priority: entryData.priority || "medium",
        status: entryData.status || "active",
        createdAt: editingEntry?.createdAt || now,
        updatedAt: now,
      };

      // Save to RAG system as a document
      if (entry.content.trim()) {
        const content = `# ${entry.title}\n\n${
          entry.description ? `${entry.description}\n\n` : ""
        }${entry.content}`;
        const blob = new Blob([content], { type: "text/markdown" });
        const file = new File([blob], `${entry.title}.md`, {
          type: "text/markdown",
        });

        const metadata = {
          title: entry.title,
          category: entry.category,
          tags: entry.tags,
          type: "knowledge-entry",
          priority: entry.priority,
          status: entry.status,
          entryId: entry.id,
        };

        if (editingEntry?.id) {
          // Update existing entry
          await ragEngine.uploadAndAddDocument(
            file,
            `${entry.title}.md`,
            metadata
          );
        } else {
          // Add new entry
          await ragEngine.uploadAndAddDocument(
            file,
            `${entry.title}.md`,
            metadata
          );
        }
      }

      // Update local storage
      const updatedEntries = editingEntry
        ? entries.map((e) => (e.id === editingEntry.id ? entry : e))
        : [...entries, entry];

      setEntries(updatedEntries);
      localStorage.setItem("knowledge-entries", JSON.stringify(updatedEntries));

      setLastSaved(new Date());
      setHasUnsavedChanges(false);

      if (!isAutoSave) {
        setSuccess(
          editingEntry
            ? "지식 항목이 업데이트되었습니다."
            : "새 지식 항목이 생성되었습니다."
        );

        if (editingEntry) {
          onEntryUpdated?.(entry);
        } else {
          onEntryCreated?.(entry);
        }

        setIsEditorOpen(false);
        resetForm();
      }

      return true;
    } catch (err) {
      setError(
        `저장 실패: ${err instanceof Error ? err.message : "알 수 없는 오류"}`
      );
      return false;
    } finally {
      setIsSaving(false);
    }
  };

  const autoSave = useCallback(() => {
    if (hasUnsavedChanges && editingEntry) {
      saveEntry(formData, true);
    }
  }, [formData, hasUnsavedChanges, editingEntry, saveEntry]);

  // Auto-save with debounce
  useEffect(() => {
    if (hasUnsavedChanges && editingEntry) {
      if (autoSaveTimeoutRef.current) {
        clearTimeout(autoSaveTimeoutRef.current);
      }

      autoSaveTimeoutRef.current = setTimeout(() => {
        autoSave();
      }, 2000); // Auto-save after 2 seconds of inactivity
    }

    return () => {
      if (autoSaveTimeoutRef.current) {
        clearTimeout(autoSaveTimeoutRef.current);
      }
    };
  }, [hasUnsavedChanges, editingEntry, autoSave]);

  const resetForm = () => {
    setFormData({
      title: "",
      content: "",
      category: "",
      tags: [],
      description: "",
      priority: "medium",
      status: "active",
    });
    setEditingEntry(null);
    setValidationErrors({});
    setHasUnsavedChanges(false);
  };

  const openEditor = (entry?: KnowledgeEntry) => {
    if (entry) {
      setEditingEntry(entry);
      setFormData({
        title: entry.title,
        content: entry.content,
        category: entry.category,
        tags: [...entry.tags],
        description: entry.description,
        priority: entry.priority,
        status: entry.status,
      });
    } else {
      resetForm();
    }
    setIsEditorOpen(true);
    setHasUnsavedChanges(false);
  };

  const deleteEntry = async (entry: KnowledgeEntry) => {
    if (!confirm(`"${entry.title}" 항목을 삭제하시겠습니까?`)) return;

    try {
      const updatedEntries = entries.filter((e) => e.id !== entry.id);
      setEntries(updatedEntries);
      localStorage.setItem("knowledge-entries", JSON.stringify(updatedEntries));

      setSuccess(`"${entry.title}" 항목이 삭제되었습니다.`);
      onEntryDeleted?.(entry.id);
    } catch (err) {
      setError(
        `삭제 실패: ${err instanceof Error ? err.message : "알 수 없는 오류"}`
      );
    }
  };

  const bulkDelete = async () => {
    if (!confirm(`선택된 ${selectedEntries.size}개 항목을 삭제하시겠습니까?`))
      return;

    try {
      const updatedEntries = entries.filter((e) => !selectedEntries.has(e.id));
      setEntries(updatedEntries);
      localStorage.setItem("knowledge-entries", JSON.stringify(updatedEntries));

      setSuccess(`${selectedEntries.size}개 항목이 삭제되었습니다.`);
      setSelectedEntries(new Set());
      setIsBulkMode(false);
    } catch (err) {
      setError(
        `벌크 삭제 실패: ${
          err instanceof Error ? err.message : "알 수 없는 오류"
        }`
      );
    }
  };

  const bulkUpdateStatus = async (status: KnowledgeEntry["status"]) => {
    try {
      const updatedEntries = entries.map((e) =>
        selectedEntries.has(e.id)
          ? { ...e, status, updatedAt: new Date().toISOString() }
          : e
      );

      setEntries(updatedEntries);
      localStorage.setItem("knowledge-entries", JSON.stringify(updatedEntries));

      setSuccess(
        `${selectedEntries.size}개 항목의 상태가 "${status}"로 변경되었습니다.`
      );
      setSelectedEntries(new Set());
      setIsBulkMode(false);
    } catch (err) {
      setError(
        `벌크 상태 변경 실패: ${
          err instanceof Error ? err.message : "알 수 없는 오류"
        }`
      );
    }
  };

  const updateFormData = (field: keyof KnowledgeEntry, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    setHasUnsavedChanges(true);

    // Clear validation error for this field
    if (validationErrors[field]) {
      setValidationErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const insertMarkdown = (markdown: string) => {
    if (textareaRef.current) {
      const textarea = textareaRef.current;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const currentContent = formData.content || "";

      const newContent =
        currentContent.substring(0, start) +
        markdown +
        currentContent.substring(end);
      updateFormData("content", newContent);

      // Move cursor to end of inserted text
      setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(
          start + markdown.length,
          start + markdown.length
        );
      }, 0);
    }
  };

  const formatTime = (dateString: string) => {
    return new Date(dateString).toLocaleString();
  };

  return (
    <div className="space-y-6">
      {/* Header with Controls */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>지식 베이스 편집기</CardTitle>
            <div className="flex items-center gap-2">
              <Button onClick={() => openEditor()}>새 항목 추가</Button>
              <Button
                variant="outline"
                onClick={() => setIsBulkMode(!isBulkMode)}
              >
                {isBulkMode ? "벌크 모드 종료" : "벌크 편집"}
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* Search and Filters */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
            <Input
              placeholder="검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />

            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">모든 상태</option>
              <option value="active">활성</option>
              <option value="draft">임시저장</option>
              <option value="archived">보관됨</option>
            </select>

            <select
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">모든 카테고리</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat}
                </option>
              ))}
            </select>

            <select
              value={tagFilter}
              onChange={(e) => setTagFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">모든 태그</option>
              {allTags.map((tag) => (
                <option key={tag} value={tag}>
                  {tag}
                </option>
              ))}
            </select>
          </div>

          {/* Bulk Actions */}
          {isBulkMode && selectedEntries.size > 0 && (
            <div className="flex items-center gap-2 p-3 bg-blue-50 rounded-lg mb-4">
              <span className="text-sm font-medium">
                {selectedEntries.size}개 항목 선택됨
              </span>
              <Button size="sm" onClick={() => bulkUpdateStatus("active")}>
                활성화
              </Button>
              <Button size="sm" onClick={() => bulkUpdateStatus("archived")}>
                보관
              </Button>
              <Button size="sm" variant="outline" onClick={bulkDelete}>
                삭제
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => setSelectedEntries(new Set())}
              >
                선택 해제
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Entries List */}
      <Card>
        <CardHeader>
          <CardTitle>지식 항목 ({filteredEntries.length}개)</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredEntries.length === 0 ? (
            <p className="text-gray-500 text-center py-8">
              {searchQuery ||
              statusFilter !== "all" ||
              categoryFilter ||
              tagFilter
                ? "검색 조건에 맞는 항목이 없습니다."
                : "지식 항목이 없습니다. 새 항목을 추가해보세요."}
            </p>
          ) : (
            <div className="space-y-3">
              {filteredEntries.map((entry) => (
                <div
                  key={entry.id}
                  className="flex items-start gap-3 p-4 border rounded-lg"
                >
                  {isBulkMode && (
                    <input
                      type="checkbox"
                      checked={selectedEntries.has(entry.id)}
                      onChange={(e) => {
                        const newSelected = new Set(selectedEntries);
                        if (e.target.checked) {
                          newSelected.add(entry.id);
                        } else {
                          newSelected.delete(entry.id);
                        }
                        setSelectedEntries(newSelected);
                      }}
                      className="mt-1"
                    />
                  )}

                  <div className="flex-1">
                    <div className="flex items-start justify-between">
                      <div>
                        <h4 className="font-medium text-lg">{entry.title}</h4>
                        {entry.description && (
                          <p className="text-sm text-gray-600 mb-2">
                            {entry.description}
                          </p>
                        )}
                        <div className="text-sm text-gray-500 space-y-1">
                          <p>카테고리: {entry.category}</p>
                          {entry.tags.length > 0 && (
                            <p>태그: {entry.tags.join(", ")}</p>
                          )}
                          <p>우선순위: {entry.priority}</p>
                          <p>상태: {entry.status}</p>
                          <p>마지막 수정: {formatTime(entry.updatedAt)}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openEditor(entry)}
                        >
                          편집
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => deleteEntry(entry)}
                        >
                          삭제
                        </Button>
                      </div>
                    </div>

                    <div className="mt-3 p-3 bg-gray-50 rounded text-sm">
                      <p className="line-clamp-3">{entry.content}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Editor Modal */}
      {isEditorOpen && (
        <Modal open={isEditorOpen} onOpenChange={setIsEditorOpen}>
          <ModalContent className="max-w-4xl max-h-[90vh]">
            <ModalHeader>
              <ModalTitle>
                {editingEntry ? "지식 항목 편집" : "새 지식 항목"}
                {hasUnsavedChanges && (
                  <span className="ml-2 text-sm text-orange-600">
                    ● 저장되지 않은 변경사항
                  </span>
                )}
                {lastSaved && (
                  <span className="ml-2 text-sm text-green-600">
                    마지막 저장: {lastSaved.toLocaleTimeString()}
                  </span>
                )}
              </ModalTitle>
            </ModalHeader>

            <div className="p-6 space-y-4 overflow-y-auto">
              {/* Basic Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">
                    제목 *
                  </label>
                  <Input
                    value={formData.title || ""}
                    onChange={(e) => updateFormData("title", e.target.value)}
                    placeholder="지식 항목 제목"
                    className={validationErrors.title ? "border-red-500" : ""}
                  />
                  {validationErrors.title && (
                    <p className="text-red-500 text-sm mt-1">
                      {validationErrors.title}
                    </p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    카테고리 *
                  </label>
                  <Input
                    value={formData.category || ""}
                    onChange={(e) => updateFormData("category", e.target.value)}
                    placeholder="예: FAQ, 기술문서, 가이드"
                    list="categories"
                    className={
                      validationErrors.category ? "border-red-500" : ""
                    }
                  />
                  <datalist id="categories">
                    {categories.map((cat) => (
                      <option key={cat} value={cat} />
                    ))}
                  </datalist>
                  {validationErrors.category && (
                    <p className="text-red-500 text-sm mt-1">
                      {validationErrors.category}
                    </p>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">설명</label>
                <Input
                  value={formData.description || ""}
                  onChange={(e) =>
                    updateFormData("description", e.target.value)
                  }
                  placeholder="간단한 설명"
                />
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">
                    태그 (쉼표로 구분)
                  </label>
                  <Input
                    value={formData.tags?.join(", ") || ""}
                    onChange={(e) =>
                      updateFormData(
                        "tags",
                        e.target.value
                          .split(",")
                          .map((tag) => tag.trim())
                          .filter(Boolean)
                      )
                    }
                    placeholder="예: 자주묻는질문, 기본설정"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    우선순위
                  </label>
                  <select
                    value={formData.priority || "medium"}
                    onChange={(e) => updateFormData("priority", e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="high">높음</option>
                    <option value="medium">보통</option>
                    <option value="low">낮음</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">상태</label>
                  <select
                    value={formData.status || "active"}
                    onChange={(e) => updateFormData("status", e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="active">활성</option>
                    <option value="draft">임시저장</option>
                    <option value="archived">보관됨</option>
                  </select>
                </div>
              </div>

              {/* Markdown Toolbar */}
              <div>
                <label className="block text-sm font-medium mb-1">
                  내용 (마크다운 지원) *
                </label>
                <div className="flex items-center gap-2 mb-2 p-2 bg-gray-50 rounded">
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("**굵게**")}
                  >
                    <strong>B</strong>
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("*기울임*")}
                  >
                    <em>I</em>
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("\n- ")}
                  >
                    •
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("\n1. ")}
                  >
                    1.
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("[링크 텍스트](URL)")}
                  >
                    링크
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => insertMarkdown("`코드`")}
                  >
                    코드
                  </Button>
                </div>

                <textarea
                  ref={textareaRef}
                  value={formData.content || ""}
                  onChange={(e) => updateFormData("content", e.target.value)}
                  placeholder="지식 내용을 입력하세요...&#10;&#10;예시:&#10;- 요점 형태로 작성&#10;- **중요한 내용**은 굵게&#10;- 간결하고 명확하게"
                  className={`w-full h-64 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm ${
                    validationErrors.content
                      ? "border-red-500"
                      : "border-gray-300"
                  }`}
                />
                {validationErrors.content && (
                  <p className="text-red-500 text-sm mt-1">
                    {validationErrors.content}
                  </p>
                )}
              </div>

              {/* Action Buttons */}
              <div className="flex items-center justify-between pt-4 border-t">
                <div className="flex items-center gap-2">
                  {isSaving && (
                    <span className="text-sm text-gray-600">저장 중...</span>
                  )}
                </div>

                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    onClick={() => {
                      if (
                        hasUnsavedChanges &&
                        !confirm(
                          "저장하지 않은 변경사항이 있습니다. 계속하시겠습니까?"
                        )
                      ) {
                        return;
                      }
                      setIsEditorOpen(false);
                      resetForm();
                    }}
                  >
                    취소
                  </Button>
                  <Button
                    onClick={() => saveEntry({ ...formData, status: "draft" })}
                    variant="outline"
                    disabled={isSaving}
                  >
                    임시저장
                  </Button>
                  <Button
                    onClick={() => saveEntry({ ...formData, status: "active" })}
                    disabled={isSaving}
                  >
                    {editingEntry ? "업데이트" : "저장"}
                  </Button>
                </div>
              </div>
            </div>
          </ModalContent>
        </Modal>
      )}

      {/* Status Messages */}
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-800">{error}</p>
        </div>
      )}

      {success && (
        <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
          <p className="text-green-800">{success}</p>
        </div>
      )}
    </div>
  );
}
