import React, { useEffect, useState } from 'react';
import { Button, Input, Select, Table, Pagination, Tag, Typography, Tooltip } from 'antd';
import { FileTextOutlined } from '@ant-design/icons';
import { getMaterialList } from '../api';
import PreResultDisplay from '../components/PreResultDisplay';
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const { Text } = Typography;

const AdminMaterialList: React.FC = () => {
  const [tableData, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [searchMaterialId, setSearchMaterialId] = useState('');
  const [searchUploadId, setSearchUploadId] = useState('');
  const [searchResourceType, setSearchResourceType] = useState('');

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (text: number) => <span style={{ color: '#64748b' }}>{text}</span>,
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '广告主账户ID',
      dataIndex: 'advertiserId',
      key: 'advertiserId',
    },
    {
      title: '素材ID',
      dataIndex: 'materialId',
      key: 'materialId',
      width: 180,
    },
    {
      title: '上传ID',
      dataIndex: 'uploadId',
      key: 'uploadId',
      render: (v: string) => {
        if (!v) return '-';
        const short = v.length > 12 ? `${v.slice(0, 6)}...${v.slice(-4)}` : v;
        return (
            <Tooltip title={v} placement="topLeft">
              <Typography.Text style={{ fontSize: 12 }}>{short}</Typography.Text>
            </Tooltip>
        );
      },
    },
    {
      title: '预测试模板ID',
      dataIndex: 'preTestTemplateId',
      key: 'preTestTemplateId',
    },
    {
      title: '授权ID',
      dataIndex: 'oauthId',
      key: 'oauthId',
    },
    {
      title: '目标标ID',
      dataIndex: 'targetId',
      key: 'targetId',
    },
    {
      title: '目标表',
      dataIndex: 'targetTable',
      key: 'targetTable',
    },
    {
      title: '任务ID',
      dataIndex: 'taskId',
      key: 'taskId',
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '备注',
      dataIndex: 'note',
      key: 'note',
      width: 200,
      render: (text: string) => (
        <Input.TextArea
          value={text || ''}
          readOnly
          autoSize={{ minRows: 1, maxRows: 4 }}
          style={{ color: '#94a3b8', resize: 'none', border: 'none', background: 'transparent', padding: 0 }}
          placeholder="-"
        />
      ),
    },
    {
      title: '预测试结果',
      dataIndex: 'preResult',
      key: 'preResult',
      width: 120,
      render: (text: string) => <PreResultDisplay preResult={text} />,
    },
    {
      title: '资源类型',
      dataIndex: 'resourceType',
      key: 'resourceType',
      width: 100,
      render: (text: string) => (
        <Tag color={text === 'video' ? 'blue' : 'green'}>
          {text === 'video' ? '视频' : '图片'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text: string) => (
        <Tag color={text === 'SUCCESS' ? 'green' : text === 'PENDING' ? 'orange' : 'red'}>
          {text === 'SUCCESS' ? '成功' : text === 'PENDING' ? '处理中' : '失败'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (text: string) => <span style={{ color: '#64748b' }}>{ formatDateTime(text)}</span>,
    },
    
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (text: string) => <span style={{ color: '#64748b' }}>{ formatDateTime(text)}</span>,
    },
  ];

  const loadMaterialList = async () => {
    setLoading(true);
    try {
      const res = await getMaterialList({
        material_id: searchMaterialId || undefined,
        upload_id: searchUploadId || undefined,
        resource_type: searchResourceType || undefined,
        page: currentPage,
        page_size: pageSize,
      });
      const data = res.data || [];
      const tableData = data.map((item: any, index: number) => ({
        ...item,
        index: (currentPage - 1) * pageSize + index + 1,
      }));
      setTableData(tableData);
      setTotal(res.pagination?.total || 0);
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadMaterialList();
  }, [currentPage, pageSize]);

  const handleSearch = () => {
    setCurrentPage(1);
    loadMaterialList();
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <FileTextOutlined style={{ color: '#6366f1', fontSize: 16 }} />
        <Text strong style={{ fontSize: 16 }}>素材ID列表</Text>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <Input
            placeholder="素材ID"
            value={searchMaterialId}
            onChange={(e) => setSearchMaterialId(e.target.value)}
            style={{ width: 160 }}
            allowClear
            onPressEnter={handleSearch}
          />
          <Input
            placeholder="上传ID"
            value={searchUploadId}
            onChange={(e) => setSearchUploadId(e.target.value)}
            style={{ width: 160 }}
            allowClear
            onPressEnter={handleSearch}
          />
          <Input
            placeholder="文件名"
            value={searchResourceType}
            onChange={(e) => setSearchResourceType(e.target.value)}
            style={{ width: 140 }}
            allowClear
            onPressEnter={handleSearch}
          />
          <Select
            placeholder="资源类型"
            value={searchResourceType}
            onChange={(value) => setSearchResourceType(value)}
            style={{ width: 120 }}
            allowClear
            options={[
              { value: 'image', label: '图片' },
              { value: 'video', label: '视频' },
            ]}
          />
          <Button
            type="primary"
            onClick={handleSearch}
          >
            搜索
          </Button>
        </div>
      </div>
      <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
        <Table
          dataSource={tableData}
          columns={columns}
          loading={loading}
          pagination={false}
          rowKey="id"
          bordered={false}
          scroll={{ x: 'max-content' }}
        />
        <div style={{ padding: '16px', textAlign: 'right' }}>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            showTotal={(total) => `共 ${total} 条记录`}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }}
            size="small"
          />
        </div>
      </div>
    </div>
  );
};

export default AdminMaterialList;