/**
 * Git 状态与配置区块
 *
 * 展示各环境 Git 分支/提交信息，支持 pull / 同步依赖 / 查看 .env 配置。
 * 从 OpsPanel 拆分，可独立使用（如 Dashboard 聚合页）。
 */

import React, { useState } from "react";
import {
  Card,
  Row,
  Col,
  Tag,
  Button,
  Space,
  Descriptions,
  Modal,
  Tooltip,
  Typography,
  Input,
  message,
} from "antd";
import {
  CloudDownloadOutlined,
  SyncOutlined,
  FileTextOutlined,
} from "@ant-design/icons";
import type { ServiceStatus, GitInfo } from "../../api/opsPanel";
import { fetchEnvFile } from "../../api/opsPanel";

const { Text } = Typography;
const { TextArea } = Input;

export interface GitStatusSectionProps {
  gitInfos: GitInfo[];
  /** 用于查找 env 对应的 label */
  services: ServiceStatus[];
  actionLoading: Record<string, boolean>;
  onPull: (env: string) => void;
  onSyncDeps: (env: string) => void;
}

const GitStatusSection: React.FC<GitStatusSectionProps> = ({
  gitInfos,
  services,
  actionLoading,
  onPull,
  onSyncDeps,
}) => {
  const [envModalOpen, setEnvModalOpen] = useState(false);
  const [envModalContent, setEnvModalContent] = useState("");
  const [envModalTitle, setEnvModalTitle] = useState("");

  const handleViewEnv = async (env: string, label: string) => {
    try {
      const r = await fetchEnvFile(env);
      setEnvModalTitle(`${label} .env 配置`);
      setEnvModalContent(r.content);
      setEnvModalOpen(true);
    } catch {
      message.error("读取配置文件失败");
    }
  };

  return (
    <>
      <Card size="small" title="代码与配置" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          {gitInfos.map((git) => {
            const envCfg = services.find((s) => s.env === git.env);
            const label = envCfg?.label ?? git.env;
            return (
              <Col span={12} key={git.env}>
                <Card size="small" type="inner" title={label}>
                  <Descriptions size="small" column={1} style={{ marginBottom: 12 }}>
                    <Descriptions.Item label="分支">
                      <Tag color="blue">{git.branch}</Tag>
                      {git.has_local_changes && (
                        <Tooltip title="工作区有未提交的变更">
                          <Tag color="warning">有变更</Tag>
                        </Tooltip>
                      )}
                    </Descriptions.Item>
                    <Descriptions.Item label="最新提交">
                      <Text code style={{ fontSize: 12 }}>{git.last_commit_hash}</Text>
                      <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
                        {git.last_commit_message}
                      </Text>
                    </Descriptions.Item>
                    <Descriptions.Item label="提交时间">
                      <Text type="secondary" style={{ fontSize: 12 }}>{git.last_commit_time}</Text>
                    </Descriptions.Item>
                  </Descriptions>
                  <Space>
                    <Button
                      size="small"
                      icon={<CloudDownloadOutlined />}
                      loading={actionLoading[`pull-${git.env}`]}
                      onClick={() => onPull(git.env)}
                    >
                      Git Pull
                    </Button>
                    <Button
                      size="small"
                      icon={<SyncOutlined />}
                      loading={actionLoading[`sync-${git.env}`]}
                      onClick={() => onSyncDeps(git.env)}
                    >
                      同步依赖
                    </Button>
                    <Button
                      size="small"
                      icon={<FileTextOutlined />}
                      onClick={() => handleViewEnv(git.env, label)}
                    >
                      查看配置
                    </Button>
                  </Space>
                </Card>
              </Col>
            );
          })}
        </Row>
      </Card>

      {/* 配置查看弹窗 */}
      <Modal
        title={envModalTitle}
        open={envModalOpen}
        onCancel={() => setEnvModalOpen(false)}
        footer={null}
        width={700}
      >
        <TextArea
          value={envModalContent}
          readOnly
          autoSize={{ minRows: 10, maxRows: 30 }}
          style={{ fontFamily: "monospace", fontSize: 12 }}
        />
      </Modal>
    </>
  );
};

export default GitStatusSection;
