import {invoke} from "@tauri-apps/api/core";
import type React from "react";
import {useRef, useState} from "react";
import {message} from "antd";
import GitRepo from "../../components/GitRepo";
import Setting from "../../components/Setting";
import ReportPreview, {ReportPreviewRef} from "../../components/ReportPreview";
import type {ReportType} from "../../types/types";
import {getTimeRange} from "../../utils/timeUtils";
import {processWithDeepSeek} from '../../utils/deepseekApi';

interface GitRepoData {
  repoPath: string;
  name: string;
}

interface CommitInfo {
  id: string;
  message: string;
  author: string;
  date: string;
}

const Home: React.FC = () => {
  const [repos, setRepos] = useState<GitRepoData[]>([]);
  const [selectedRepos, setSelectedRepos] = useState<string[]>([]);
  const [commits, setCommits] = useState<CommitInfo[]>([]);
  const [reportContent, setReportContent] = useState<string>("");
  const [messageApi, contextHolder] = message.useMessage();


  const reportPreviewRef = useRef<ReportPreviewRef>(null);

  const handleAddRepo = async (repo: GitRepoData) => {
    try {
      // TODO: 调用Tauri后端API验证仓库路径
      setRepos([...repos, repo]);
      message.success("仓库添加成功");
    } catch (error) {
      message.error("添加仓库失败");
    }
  };

  const handleGenerateReport = async (
    reportType: ReportType,
    useAI: boolean,
  ) => {
    if (selectedRepos.length === 0) {
      message.warning("请先选择仓库");
      return;
    }

    messageApi.open({
      type: 'loading',
      content: '获取git提交记录中...',
      duration: 0,
    });

    try {
      const commits = await Promise.all(
        selectedRepos.map(async (repoPath) => {
          const repoName =
            repos.find((r) => r.repoPath === repoPath)?.name || "";

          const userEmail = localStorage.getItem("userEmail");
          return await invoke<CommitInfo[]>("get_commits", {
            repoPath,
            repoName,
            authorFilter: userEmail || null,
            timeRange: reportType ? getTimeRange(reportType) : null,
          });
        }),
      );

      messageApi.destroy();
      console.log(commits);

      const flatCommits = commits.flat();
      setCommits(flatCommits);

      const reportText = `已生成 ${selectedRepos.length} 个仓库的报告内容\n\n${flatCommits
        .map(
          (commit) =>
            `- ${commit.message} (${commit.author} 于 ${new Date(Number.parseInt(commit.date) * 1000).toLocaleDateString()})`,
        )
        .join("\n")}`;

      reportPreviewRef.current?.handleChangeActiveTab("preview");

      if (useAI) {
        messageApi.open({
          type: 'loading',
          content: '正在思考...',
          duration: 0,
        });
        try {
          const apiKey = localStorage.getItem("userKey") || "";
          let fullResponse = '';

          await processWithDeepSeek(reportText, apiKey, (chunk) => {
            if (!fullResponse) {
              messageApi.destroy();
              messageApi.open({
                type: 'loading',
                content: '正在生成...',
                duration: 0,
              });
            }
            fullResponse += chunk;
            setReportContent(fullResponse);
          });
        } catch (error) {
          console.error("DeepSeek处理失败:", error);
        } finally {
          messageApi.destroy();
        }
      }else {
        setReportContent(reportText);
      }

      message.success("报告生成完毕");
    } catch (error) {
      message.error("报告生成失败");
      setCommits([]);
      setReportContent("");
    }
  };

  const handleReposSelect = (selected: string[]) => {
    setSelectedRepos(selected);
    if (selected.length === 0) {
      setCommits([]);
      setReportContent("");
    }
  };

  return (
    <div className="flex size-full overflow-hidden">
      {contextHolder}
      <div className="h-full w-80 flex flex-col">
        <div>
          <Setting />
        </div>
        <GitRepo
          className="flex-1"
          onAddRepo={handleAddRepo}
          repos={repos}
          onGenerateReport={handleGenerateReport}
          onReposSelect={handleReposSelect}
        />
      </div>
      <div className="flex-1 h-full overflow-hidden">
        <ReportPreview
          ref={reportPreviewRef}
          selectedRepos={selectedRepos}
          commits={commits}
          reportContent={reportContent}
        />
      </div>
    </div>
  );
};

export default Home;