import {useState, useImperativeHandle, forwardRef, useEffect, useRef} from 'react';
import {Button, Card, Drawer, Tabs, Typography} from "antd";
import CommitList from './CommitList';
import PublishToCongShang from "../PublishToCongShang";

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

interface ReportPreviewProps {
  selectedRepos: string[];
  commits?: CommitInfo[];
  reportContent?: string;
}

export interface ReportPreviewRef {
  handleChangeActiveTab: (key: string) => void;
}

const { Title, Paragraph } = Typography;

const ReportPreview = forwardRef<ReportPreviewRef, ReportPreviewProps>(
  ({ selectedRepos, commits = [], reportContent = '' }, ref) => {
    const [activeTabKey, setActiveTabKey] = useState<string>("commits");
    const previewDivRef = useRef<HTMLDivElement>(null);

    const handleChangeActiveTab = (key: string) => {
      setActiveTabKey(key);
    };

    useImperativeHandle(ref, () => ({
      handleChangeActiveTab,
    }));

    useEffect(() => {
      if (previewDivRef.current) {
        previewDivRef.current.scrollTop = previewDivRef.current.scrollHeight;
      }
    }, [reportContent]);

    const [isOpen, setIsOpen] = useState(false);

    if (selectedRepos.length === 0) {
      return (
        <Card className="size-full flex items-center justify-center">
          <Typography.Text type="secondary">请选择Git仓库以预览报告内容</Typography.Text>
        </Card>
      );
    }
    const tabItems = [
      {
        key: "commits",
        label: "提交记录",
        children: (
          <div className="h-[calc(100vh-100px)] overflow-auto">
            <CommitList commits={commits} />
          </div>
        ),
      },
      {
        key: "preview",
        label: "报告预览",
        children: (
          <div className="flex flex-col">
            <div className="flex justify-between items-center mb-4">
              <Title level={4}>报告内容</Title>
              <Button onClick={() => setIsOpen(true)}>发布到丛商</Button>
            </div>
            <div className="h-[calc(100vh-140px)] overflow-auto" ref={previewDivRef}>
              <Paragraph
                style={{ whiteSpace: "pre-wrap" }}
              >
                {reportContent || "暂无报告内容"}
              </Paragraph>
            </div>
          </div>
        ),
      },
    ];

    return (
      <Card className="size-full">
        <Drawer
          closable
          title="发布到丛商"
          open={isOpen}
          onClose={() => setIsOpen(false)}
        >
          <PublishToCongShang reportContent={reportContent} />
        </Drawer>
        <Tabs
          activeKey={activeTabKey}
          items={tabItems}
          onChange={(activeKey: string) => {
            setActiveTabKey(activeKey)
          }}
        />
      </Card>
    );
});

export default ReportPreview;