import React from 'react';
import { Alert, Button, Card, Col, Descriptions, Empty, Row, Table, Tag } from 'antd';
import api from '../../api';

export interface EnrollmentInfo {
  classId: number;
  className: string;
  classType: string;
  startDate: string;
  endDate: string;
  joinDate: string;
  leaveDate: string;
  status: string;
}

export const StudentsTable: React.FC<{
  columns: any[];
  data: any[];
  loading: boolean;
  pageInfo: { current: number; pageSize: number };
  onPageChange: (current: number, pageSize: number) => void;
  selectedRowKeys: number[];
  onSelect: (keys: number[]) => void;
  onClearSelection: () => void;
}> = ({
  columns,
  data,
  loading,
  pageInfo,
  onPageChange,
  selectedRowKeys,
  onSelect,
  onClearSelection,
}) => {
  const [enrollmentData, setEnrollmentData] = React.useState<Record<number, EnrollmentInfo[]>>({});

  return (
    <>
      {selectedRowKeys.length > 0 ? (
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: 12 }}
          title={
            <span>
              已选 <strong style={{ color: '#1677ff' }}>{selectedRowKeys.length}</strong>{' '}
              人（支持跨页勾选）
            </span>
          }
          action={
            <Button size="small" type="link" onClick={onClearSelection}>
              清空选择
            </Button>
          }
        />
      ) : null}
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        locale={{ emptyText: <Empty description="暂无数据" /> }}
        scroll={{ x: 1410 }}
        pagination={{
          defaultPageSize: 15,
          current: pageInfo.current,
          pageSize: pageInfo.pageSize,
          showSizeChanger: true,
          pageSizeOptions: [15, 30, 50, 100],
          showTotal: (total) => `共 ${total} 人`,
          onChange: onPageChange,
        }}
        rowClassName={(record: any) => (record.status === 'archived' ? 'archived-row' : '')}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => onSelect(keys as number[]),
        }}
        expandable={{
          rowExpandable: () => true,
          expandedRowRender: (record) => {
            const enrollments = enrollmentData[record.id];
            if (!enrollments) return null;
            if (enrollments.length < 2) {
              return (
                <div style={{ padding: 8, color: '#999', fontSize: 13 }}>
                  当前仅 {enrollments.length} 个班型，无可对比数据
                </div>
              );
            }
            return (
              <Card title="多班型对比" size="small" style={{ margin: '8px 0' }}>
                <Row gutter={[16, 16]}>
                  {enrollments.map((enr, idx) => (
                    <Col xs={24} md={12} key={enr.classId}>
                      <Card
                        size="small"
                        title={enr.classType || `班型 ${idx + 1}`}
                        style={{ background: idx === 0 ? '#f0f5ff' : '#f6ffed' }}
                      >
                        <Descriptions column={1} size="small">
                          <Descriptions.Item label="班级">{enr.className || '-'}</Descriptions.Item>
                          <Descriptions.Item label="开班日期">
                            {enr.startDate || enr.joinDate || '-'}
                          </Descriptions.Item>
                          <Descriptions.Item label="结课日期">
                            {enr.endDate || enr.leaveDate || '-'}
                          </Descriptions.Item>
                          <Descriptions.Item label="状态">
                            <Tag color={enr.status === 'active' ? 'green' : 'default'}>
                              {enr.status || '-'}
                            </Tag>
                          </Descriptions.Item>
                        </Descriptions>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </Card>
            );
          },
          onExpand: async (expanded, record) => {
            if (expanded && !enrollmentData[record.id]) {
              try {
                const res = await api.get<{ enrollments: EnrollmentInfo[] }>(
                  `/students/${record.id}/compare-classes`,
                );
                setEnrollmentData((prev) => ({ ...prev, [record.id]: res.enrollments }));
              } catch {
                setEnrollmentData((prev) => ({ ...prev, [record.id]: [] }));
              }
            }
          },
        }}
      />
      <style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
    </>
  );
};
