import React from 'react';
import { Descriptions, Tag, Space, Divider, Table, Button, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import API_BASE_URL from '../config';
import {
  achievementTypes,
  fieldLabels,
  nameLabels,
  dateLabels
} from '../constants/achievements';

const AchievementFormRenderer = ({ data }) => {
  if (!data) return null;

  const SPLIT_CONTRIBUTOR_THRESHOLD = 8;
  const contributors = Array.isArray(data.contributors) ? data.contributors : [];
  const shouldSplitContributors = contributors.length > SPLIT_CONTRIBUTOR_THRESHOLD;
  const splitIndex = Math.ceil(contributors.length / 2);
  const leftContributors = contributors.slice(0, splitIndex);
  const rightContributors = contributors.slice(splitIndex);

  const getContributorColumns = (isSplit = false) => [
    {
      title: '排名',
      dataIndex: 'ranking',
      key: 'ranking',
      width: isSplit ? 56 : 72,
      render: (ranking) => ranking || '-'
    },
    { title: '姓名', dataIndex: 'name', key: 'name', ...(isSplit ? {} : { width: 180 }), render: (name) => <div className="export-form-wrap-text">{name || '-'}</div> },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      ...(isSplit ? {} : { width: 260 }),
      render: (role, record) => (
        <Space wrap size={[4, 4]}>
          {role || (record.isMain ? '主要完成人' : '完成人')}
          {record.isMain && <Tag color="blue">主要</Tag>}
        </Space>
      )
    }
  ];

  const getTypeName = (typeKey) => {
    const type = achievementTypes.find((t) => t.key === typeKey);
    return type ? type.label : typeKey;
  };

  const formatTwoLineLabel = (label) => {
    const text = String(label || '').trim();
    if (!text) return '';

    if (text.length <= 2) {
      return (
        <span className="export-form-label-two-line">
          <span>{text}</span>
          <span>&nbsp;</span>
        </span>
      );
    }

    const breakIndex = Math.ceil(text.length / 2);
    return (
      <span className="export-form-label-two-line">
        <span>{text.slice(0, breakIndex)}</span>
        <span>{text.slice(breakIndex)}</span>
      </span>
    );
  };

  const handleDownloadAttachment = async (file) => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/attachments/${file.id}/download`, {
        headers: { Authorization: `Bearer ${token}` },
        responseType: 'blob'
      });

      let filename = file.file_name || 'attachment';
      const contentDisposition = response.headers['content-disposition'];
      if (contentDisposition) {
        const utf8Name = contentDisposition.match(/filename\\*=UTF-8''(.+)/);
        const normalName = contentDisposition.match(/filename="(.+)"/);
        if (utf8Name && utf8Name[1]) {
          filename = decodeURIComponent(utf8Name[1]);
        } else if (normalName && normalName[1]) {
          filename = normalName[1];
        }
      }

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      message.error('下载失败，请稍后重试');
    }
  };

  const renderContributorTable = (source, keyPrefix, isSplit = false) => (
    <Table
      dataSource={source}
      columns={getContributorColumns(isSplit)}
      pagination={false}
      size="small"
      bordered
      tableLayout="fixed"
      className={`export-form-table ${isSplit ? 'export-form-table-split' : 'export-form-table-single'}`}
      style={{ width: '100%' }}
      rowKey={(record, index) => `${keyPrefix}-${record?.id || record?.phone || record?.name || 'row'}-${index}`}
    />
  );

  return (
    <div id="achievement-detail-content" className="export-form-root">
      <Descriptions title="基础信息" bordered column={2} className="export-form-descriptions">
        <Descriptions.Item label={formatTwoLineLabel(nameLabels[data.type] || '成果名称')} span={2}>
          <div className="export-form-wrap-text">{data.name}</div>
        </Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('归属部门')} span={2}>
          <Space size={[0, 4]} wrap>
            {(data.assigned_departments || []).map((dept) => (
              <Tag color="blue" key={dept}>{dept}</Tag>
            ))}
          </Space>
        </Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel(dateLabels[data.type] || '成果时间')}>
          {data.achievement_date ? new Date(data.achievement_date).toLocaleDateString() : '无'}
        </Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('类型')}>{getTypeName(data.type)}</Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('状态')}>
          <Tag color={data.status === 'approved' ? 'green' : data.status === 'rejected' ? 'red' : 'gold'}>
            {data.status === 'approved' ? '已通过' : data.status === 'rejected' ? '已驳回' : '待审核'}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('提交时间')}>{new Date(data.created_at).toLocaleString()}</Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('审核意见')}>{data.audit_comment || '无'}</Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('备注')} span={2}>{data.remarks || '无'}</Descriptions.Item>
        <Descriptions.Item label={formatTwoLineLabel('附件列表')} span={2}>
          {data.attachments && data.attachments.length > 0 ? (
            <Space direction="vertical" style={{ width: '100%' }}>
              {data.attachments.map((file) => (
                <Button
                  key={file.id}
                  type="link"
                  icon={<DownloadOutlined />}
                  className="export-form-attachment-btn"
                  style={{ width: '100%' }}
                  onClick={() => handleDownloadAttachment(file)}
                >
                  {file.file_name}
                </Button>
              ))}
            </Space>
          ) : '无'}
        </Descriptions.Item>
      </Descriptions>

      <Divider orientation="center" style={{ fontWeight: 'bold', fontSize: '16px', margin: '24px 0', color: '#1890ff' }}>完成人列表</Divider>

      {shouldSplitContributors ? (
        <div className="export-form-contributor-grid">
          <div className="export-form-contributor-col">
            {renderContributorTable(leftContributors, 'left', true)}
          </div>
          <div className="export-form-contributor-col">
            {renderContributorTable(rightContributors, 'right', true)}
          </div>
        </div>
      ) : (
        renderContributorTable(contributors, 'single', false)
      )}

      <Divider orientation="center" style={{ fontWeight: 'bold', fontSize: '16px', margin: '24px 0', color: '#1890ff' }}>详细表单内容</Divider>

      <Descriptions bordered column={2} className="export-form-descriptions">
        {Object.entries(data.details || {}).map(([key, value]) => {
          if (key === 'id' || key === 'achievement_id' || key === 'approver_id') return null;
          const label = fieldLabels[data.type]?.[key] || key;
          return (
            <Descriptions.Item key={key} label={label}>
              <div className="export-form-wrap-text">{value?.toString() || '无'}</div>
            </Descriptions.Item>
          );
        })}
      </Descriptions>

      <style>{`
        #achievement-detail-content.export-form-root {
          width: 100%;
          overflow: visible;
        }
        #achievement-detail-content .export-form-wrap-text {
          white-space: normal;
          word-break: break-all;
          overflow-wrap: anywhere;
          line-height: 1.5;
        }
        #achievement-detail-content .export-form-label-two-line {
          display: inline-flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          min-height: 2.2em;
          line-height: 1.1;
          white-space: nowrap;
        }
        #achievement-detail-content .export-form-label-two-line > span {
          display: block;
        }
        #achievement-detail-content .export-form-descriptions.ant-descriptions-bordered .ant-descriptions-view {
          border: 2px solid #595959;
        }
        #achievement-detail-content .export-form-descriptions.ant-descriptions-bordered .ant-descriptions-row > th,
        #achievement-detail-content .export-form-descriptions.ant-descriptions-bordered .ant-descriptions-row > td {
          border-inline-end: 1.5px solid #595959;
          border-bottom: 1.5px solid #595959;
          vertical-align: top;
          white-space: normal;
          word-break: break-all;
          overflow-wrap: anywhere;
        }
        #achievement-detail-content .export-form-table .ant-table-container {
          border: 2px solid #595959;
        }
        #achievement-detail-content .export-form-table .ant-table-container table {
          width: 100% !important;
        }
        #achievement-detail-content .export-form-table .ant-table-thead > tr > th,
        #achievement-detail-content .export-form-table .ant-table-tbody > tr > td {
          border-inline-end: 1.5px solid #595959;
          border-bottom: 1.5px solid #595959;
          vertical-align: top;
          white-space: normal;
          word-break: break-all;
          overflow-wrap: anywhere;
        }
        #achievement-detail-content .export-form-table .ant-tag {
          white-space: normal;
        }
        #achievement-detail-content .export-form-table-split .ant-space {
          display: flex;
          flex-wrap: wrap;
          row-gap: 4px;
        }
        #achievement-detail-content .export-form-contributor-grid {
          display: flex;
          gap: 16px;
          align-items: flex-start;
        }
        #achievement-detail-content .export-form-contributor-col {
          flex: 1 1 0;
          min-width: 0;
        }
        @media (max-width: 680px) {
          #achievement-detail-content .export-form-contributor-grid {
            flex-wrap: wrap;
          }
          #achievement-detail-content .export-form-contributor-col {
            flex-basis: 100%;
          }
        }
        #achievement-detail-content .export-form-attachment-btn.ant-btn-link {
          height: auto;
          text-align: left;
          padding: 0;
          white-space: normal;
          word-break: break-all;
          overflow-wrap: anywhere;
          line-height: 1.5;
        }
      `}</style>
    </div>
  );
};

export default AchievementFormRenderer;

