import React, { useCallback, useEffect, useState } from 'react';
import { Button, Card, DatePicker, Input, Select, Space, Table, Tag, Tooltip, Typography, message } from 'antd';
import { EyeOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getAdminHotOpeningTasks } from '../api';
import type { HotOpeningTaskListItemOut } from '../types';
import { formatDate } from '../utils/formatDate';

const PAGE_SIZE = 20;

const STATUS_OPTIONS = [
  { value: 'pending', label: '已创建' },
  { value: 'waiting_user', label: '等待用户操作' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'failed', label: '失败' },
  { value: 'cancelled', label: '已取消' },
];

const STATUS_MAP: Record<string, { color: string; text: string }> = {
  pending: { color: 'default', text: '已创建' },
  waiting_user: { color: 'processing', text: '等待用户操作' },
  processing: { color: 'warning', text: '处理中' },
  completed: { color: 'success', text: '已完成' },
  failed: { color: 'error', text: '失败' },
  cancelled: { color: 'default', text: '已取消' },
};

const STEP_MAP: Record<string, string> = {
  material_input: '素材输入',
  image_prompt_optimize: '图片 AI 提词',
  image_generate: '图片生成',
  video_prompt_optimize: '视频 AI 提词',
  video_generate: '视频生成',
};

const safeDate = (value?: string | null): string => (value ? formatDate(value) : '-');
const shortId = (value?: string | null): string => (!value ? '-' : value.length > 16 ? `${value.slice(0, 10)}...` : value);

const StatusTag: React.FC<{ status?: string | null }> = ({ status }) => {
  if (!status) return <Tag>-</Tag>;
  const meta = STATUS_MAP[status] || { color: 'blue', text: status };
  return <Tag color={meta.color}>{meta.text}</Tag>;
};

const AdminHotOpeningReplications: React.FC = () => {
  const navigate = useNavigate();
  const [items, setItems] = useState<HotOpeningTaskListItemOut[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  const [status, setStatus] = useState<string>('');
  const [inputKeyword, setInputKeyword] = useState('');
  const [inputUserId, setInputUserId] = useState('');
  const [inputUserName, setInputUserName] = useState('');
  const [createdRange, setCreatedRange] = useState<any>(null);

  const [queryKeyword, setQueryKeyword] = useState('');
  const [queryUserId, setQueryUserId] = useState('');
  const [queryUserName, setQueryUserName] = useState('');
  const [queryCreatedRange, setQueryCreatedRange] = useState<any>(null);
  const [reloadKey, setReloadKey] = useState(0);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getAdminHotOpeningTasks({
        status: status || undefined,
        keyword: queryKeyword || undefined,
        userId: queryUserId || undefined,
        userName: queryUserName || undefined,
        createdStart: queryCreatedRange?.[0]?.toISOString?.(),
        createdEnd: queryCreatedRange?.[1]?.toISOString?.(),
        page,
        pageSize: PAGE_SIZE,
      });
      setItems(res.items || []);
      setTotal(res.total || 0);
    } catch (e: any) {
      message.error(e?.message || '加载爆款开头复刻任务失败');
    } finally {
      setLoading(false);
    }
  }, [page, queryCreatedRange, queryKeyword, queryUserId, queryUserName, status]);

  useEffect(() => {
    load();
  }, [load, reloadKey]);

  const doSearch = () => {
    setQueryKeyword(inputKeyword.trim());
    setQueryUserId(inputUserId.trim());
    setQueryUserName(inputUserName.trim());
    setQueryCreatedRange(createdRange);
    setPage(1);
  };

  const resetSearch = () => {
    setStatus('');
    setInputKeyword('');
    setInputUserId('');
    setInputUserName('');
    setCreatedRange(null);
    setQueryKeyword('');
    setQueryUserId('');
    setQueryUserName('');
    setQueryCreatedRange(null);
    setPage(1);
    setReloadKey(v => v + 1);
  };

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          <Space align="center" style={{ justifyContent: 'space-between', width: '100%' }}>
            <div>
              <Typography.Title level={3} style={{ marginBottom: 4 }}>爆款开头复刻</Typography.Title>
              <Typography.Text type="secondary">只读排查页面：查看任务列表、素材、步骤详情和生成结果。</Typography.Text>
            </div>
            <Button icon={<ReloadOutlined />} onClick={() => setReloadKey(v => v + 1)}>刷新</Button>
          </Space>

          <Space wrap>
            <Select
              allowClear
              placeholder="任务状态"
              style={{ width: 160 }}
              value={status || undefined}
              onChange={value => { setStatus(value || ''); setPage(1); }}
              options={STATUS_OPTIONS}
            />
            <Input
              allowClear
              prefix={<SearchOutlined />}
              placeholder="关键词：标题/项目名/核心点"
              style={{ width: 260 }}
              value={inputKeyword}
              onChange={e => setInputKeyword(e.target.value)}
              onPressEnter={doSearch}
            />
            <Input
              allowClear
              placeholder="用户ID（管理员）"
              style={{ width: 190 }}
              value={inputUserId}
              onChange={e => setInputUserId(e.target.value)}
              onPressEnter={doSearch}
            />
            <Input
              allowClear
              placeholder="用户名（管理员）"
              style={{ width: 230 }}
              value={inputUserName}
              onChange={e => setInputUserName(e.target.value)}
              onPressEnter={doSearch}
            />
            <DatePicker.RangePicker
              showTime
              value={createdRange}
              onChange={setCreatedRange}
              placeholder={['创建开始', '创建结束']}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={doSearch}>搜索</Button>
            <Button onClick={resetSearch}>重置</Button>
          </Space>

          <Table
            rowKey="id"
            loading={loading}
            dataSource={items}
            pagination={{
              current: page,
              pageSize: PAGE_SIZE,
              total,
              showSizeChanger: false,
              showTotal: value => `共 ${value} 条`,
              onChange: setPage,
            }}
            scroll={{ x: 1380 }}
            columns={[
              {
                title: '项目ID',
                dataIndex: 'id',
                width: 150,
                render: (value: string) => <Tooltip title={value}>{shortId(value)}</Tooltip>,
              },
              {
                title: '用户',
                width: 180,
                render: (_, record) => (
                  <Space direction="vertical" size={0}>
                    <Typography.Text>{record.userName || '-'}</Typography.Text>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>{shortId(record.userId)}</Typography.Text>
                  </Space>
                ),
              },
              {
                title: '项目信息',
                width: 260,
                render: (_, record) => (
                  <Space direction="vertical" size={2}>
                    <Typography.Text strong>{record.title || record.targetProjectName || '-'}</Typography.Text>
                    <Typography.Text type="secondary" ellipsis style={{ maxWidth: 240 }}>素材：{record.sourceProjectName || '-'}</Typography.Text>
                    <Typography.Text type="secondary" ellipsis style={{ maxWidth: 240 }}>核心：{record.coreContentPoint || '-'}</Typography.Text>
                  </Space>
                ),
              },
              { title: '状态', dataIndex: 'status', width: 130, render: (v: string) => <StatusTag status={v} /> },
              { title: '当前步骤', dataIndex: 'currentStepCode', width: 140, render: (v: string) => STEP_MAP[v] || v || '-' },
              { title: '图片结果', dataIndex: 'finalImageUrl', width: 90, render: (v: string) => v ? <Tag color="success">有</Tag> : <Tag>无</Tag> },
              { title: '视频结果', dataIndex: 'finalVideoUrl', width: 90, render: (v: string) => v ? <Tag color="success">有</Tag> : <Tag>无</Tag> },
              { title: '错误信息', dataIndex: 'errorMessage', width: 220, ellipsis: true, render: (v: string) => v || '-' },
              { title: '创建时间', dataIndex: 'createdAt', width: 170, render: safeDate },
              { title: '更新时间', dataIndex: 'updatedAt', width: 170, render: safeDate },
              {
                title: '操作',
                fixed: 'right',
                width: 110,
                render: (_, record) => (
                  <Button type="link" icon={<EyeOutlined />} onClick={() => navigate(`/hot-opening-replications/${record.id}`)}>详情</Button>
                ),
              },
            ]}
          />
        </Space>
      </Card>
    </div>
  );
};

export default AdminHotOpeningReplications;
