"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { FileIcon, defaultStyles } from "react-file-icon";
import {
  ArrowRight,
  ChevronRight,
  Plus,
  Search,
  Settings,
  Trash2,
} from "lucide-react";
import DashboardLayout from "@/components/layout/dashboard-layout";
import { api, ApiError } from "@/lib/api";
import { useToast } from "@/components/ui/use-toast";

interface KnowledgeBase {
  id: number;
  name: string;
  description: string;
  documents: Document[];
  created_at: string;
}

interface Document {
  id: number;
  file_name: string;
  file_path: string;
  file_size: number;
  content_type: string;
  knowledge_base_id: number;
  created_at: string;
  updated_at: string;
  processing_tasks: any[];
}

export default function DocumentKnowledgeBasePage() {
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [collapsedDocumentSections, setCollapsedDocumentSections] = useState<
    Record<number, boolean>
  >({});
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    void fetchKnowledgeBases();
  }, []);

  const fetchKnowledgeBases = async () => {
    try {
      const data = await api.get("/api/knowledge-base");
      setKnowledgeBases(data);
    } catch (error) {
      console.error("Failed to fetch knowledge bases:", error);
      if (error instanceof ApiError) {
        toast({
          title: "错误",
          description: error.message,
          variant: "destructive",
        });
      }
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("确定要删除这个知识库吗？")) {
      return;
    }

    try {
      await api.delete(`/api/knowledge-base/${id}`);
      setKnowledgeBases((prev) => prev.filter((kb) => kb.id !== id));
      toast({
        title: "成功",
        description: "知识库删除成功",
      });
    } catch (error) {
      console.error("Failed to delete knowledge base:", error);
      if (error instanceof ApiError) {
        toast({
          title: "错误",
          description: error.message,
          variant: "destructive",
        });
      }
    }
  };

  const toggleDocumentsSection = (knowledgeBaseId: number) => {
    setCollapsedDocumentSections((prev) => ({
      ...prev,
      [knowledgeBaseId]: !prev[knowledgeBaseId],
    }));
  };

  return (
    <DashboardLayout>
      <div className="space-y-8">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-3xl font-bold tracking-tight">文档知识库</h2>
            <p className="text-muted-foreground">管理你的知识库与文档</p>
          </div>
          <Link
            href="/dashboard/knowledge/new"
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
          >
            <Plus className="mr-2 h-4 w-4" />
            新建知识库
          </Link>
        </div>

        <div className="grid gap-6">
          {knowledgeBases.map((kb) => {
            const isDocumentsCollapsed =
              collapsedDocumentSections[kb.id] ?? true;

            return (
              <div
                key={kb.id}
                className="space-y-4 rounded-lg border bg-card p-6"
              >
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="text-lg font-semibold">{kb.name}</h3>
                    <p className="text-sm text-muted-foreground">
                      {kb.description || "暂无描述"}
                    </p>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {kb.documents.length} 个文档 ·{" "}
                      {new Date(kb.created_at).toLocaleDateString("zh-CN")}
                    </p>
                  </div>

                  <div className="flex space-x-2">
                    <Link
                      href={`/dashboard/knowledge/${kb.id}`}
                      className="inline-flex h-8 w-8 items-center justify-center rounded-md bg-secondary"
                    >
                      <Settings className="h-4 w-4" />
                    </Link>
                    <Link
                      href={`/dashboard/test-retrieval/${kb.id}`}
                      className="inline-flex h-8 w-8 items-center justify-center rounded-md bg-secondary"
                    >
                      <Search className="h-4 w-4" />
                    </Link>
                    <button
                      onClick={() => void handleDelete(kb.id)}
                      className="inline-flex h-8 w-8 items-center justify-center rounded-md bg-destructive/10 hover:bg-destructive/20"
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </button>
                  </div>
                </div>

                {kb.documents.length > 0 && (
                  <div className="border-t pt-4">
                    <button
                      type="button"
                      onClick={() => toggleDocumentsSection(kb.id)}
                      className="mb-2 flex w-full items-center justify-between rounded-md px-1 py-1 text-left hover:bg-accent/50"
                    >
                      <h4 className="text-sm font-medium">文档</h4>
                      <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        <span>{isDocumentsCollapsed ? "展开" : "收起"}</span>
                        <ChevronRight
                          className={`h-4 w-4 transition-transform ${
                            isDocumentsCollapsed ? "" : "rotate-90"
                          }`}
                        />
                      </div>
                    </button>

                    {!isDocumentsCollapsed && (
                      <div className="flex max-h-[400px] flex-wrap gap-2 overflow-y-auto">
                        {kb.documents.slice(0, 9).map((doc) => (
                          <div
                            key={doc.id}
                            className="flex h-[150px] w-[150px] cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border bg-card p-2 transition-colors hover:bg-accent/50"
                          >
                            <div className="mb-2 h-8 w-8">
                              {doc.content_type.toLowerCase().includes("pdf") ? (
                                <FileIcon extension="pdf" {...defaultStyles.pdf} />
                              ) : doc.content_type.toLowerCase().includes("doc") ? (
                                <FileIcon extension="doc" {...defaultStyles.docx} />
                              ) : doc.content_type.toLowerCase().includes("txt") ? (
                                <FileIcon extension="txt" {...defaultStyles.txt} />
                              ) : doc.content_type.toLowerCase().includes("md") ? (
                                <FileIcon extension="md" {...defaultStyles.md} />
                              ) : (
                                <FileIcon
                                  extension={doc.file_name.split(".").pop() || ""}
                                  color="#E2E8F0"
                                  labelColor="#94A3B8"
                                />
                              )}
                            </div>
                            <div className="max-w-[100px] text-center text-sm font-medium">
                              <div className="line-clamp-2 overflow-hidden text-ellipsis">
                                {doc.file_name}
                              </div>
                            </div>
                            <span className="mt-1 text-xs text-muted-foreground">
                              {new Date(doc.created_at).toLocaleDateString("zh-CN")}
                            </span>
                          </div>
                        ))}
                        {kb.documents.length > 9 && (
                          <Link
                            href={`/dashboard/knowledge/${kb.id}`}
                            className="flex h-[150px] w-[150px] cursor-pointer flex-col items-center justify-center rounded-lg border bg-card p-2 transition-colors hover:bg-accent/50"
                          >
                            <div className="mb-2 flex h-8 w-8 items-center justify-center">
                              <ArrowRight className="h-6 w-6" />
                            </div>
                            <span className="text-center text-sm font-medium">
                              查看全部文档
                            </span>
                            <span className="mt-1 text-xs text-muted-foreground">
                              共 {kb.documents.length} 个
                            </span>
                          </Link>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}

          {!loading && knowledgeBases.length === 0 && (
            <div className="py-12 text-center">
              <p className="text-muted-foreground">暂无知识库，请先创建一个。</p>
            </div>
          )}

          {loading && (
            <div className="flex items-center justify-center py-12">
              <div className="space-y-4">
                <div className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-primary/30 border-t-primary" />
                <p className="animate-pulse text-muted-foreground">
                  正在加载知识库...
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
    </DashboardLayout>
  );
}
