/* === Data Probe Page === */
function PageOperationProbe() {
  const [tables, setTables] = React.useState([]);
  const [selectedTable, setSelectedTable] = React.useState(null);
  const [tableSchema, setTableSchema] = React.useState(null);
  const [data, setData] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [total, setTotal] = React.useState(0);
  const [loading, setLoading] = React.useState(false);
  const [startDate, setStartDate] = React.useState('');
  const [endDate, setEndDate] = React.useState('');

  const API_BASE = window.API_BASE;

  const PAGE_SIZES = [10, 20, 50, 100];

  React.useEffect(() => {
    fetchTables();
  }, []);

  React.useEffect(() => {
    if (selectedTable) {
      fetchTableConfig(selectedTable);
    }
  }, [selectedTable]);

  React.useEffect(() => {
    if (selectedTable) {
      fetchTableData(selectedTable, page, pageSize);
    }
  }, [selectedTable, page, pageSize]);

  const fetchTables = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/probe/tables`);
      const json = await res.json();
      if (Array.isArray(json)) {
        setTables(json);
      } else if (json.data) {
        setTables(json.data);
      }
    } catch (err) {
      console.error('Failed to fetch tables:', err);
    }
  };

  const fetchTableConfig = async (tableCode) => {
    try {
      const res = await fetch(`${API_BASE}/api/probe/table/${tableCode}`);
      const json = await res.json();
      if (json.code === 200) {
        setTableSchema(json.data.table_schema);
      }
    } catch (err) {
      console.error('Failed to fetch table config:', err);
    }
  };

  const fetchTableData = async (tableCode, pageNum, pageSizeNum) => {
    setLoading(true);
    try {
      let url = `${API_BASE}/api/probe/table/${tableCode}/data?page=${pageNum}&page_size=${pageSizeNum}`;
      if (startDate) {
        url += `&start_date=${startDate}`;
      }
      if (endDate) {
        url += `&end_date=${endDate}`;
      }
      const res = await fetch(url);
      const json = await res.json();
      if (json.code === 200) {
        setData(json.data);
        setTotal(json.total);
      }
    } catch (err) {
      console.error('Failed to fetch table data:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (e) => {
    const code = e.target.value;
    setSelectedTable(code);
    setPage(1);
  };

  const handleQuery = () => {
    setPage(1);
    if (selectedTable) {
      fetchTableData(selectedTable, 1, pageSize);
    }
  };

  const handlePageSizeChange = (e) => {
    const size = parseInt(e.target.value);
    setPageSize(size);
    setPage(1);
    if (selectedTable) {
      fetchTableData(selectedTable, 1, size);
    }
  };

  const goToPage = (pageNum) => {
    if (pageNum >= 1 && pageNum <= Math.ceil(total / pageSize)) {
      setPage(pageNum);
      if (selectedTable) {
        fetchTableData(selectedTable, pageNum, pageSize);
      }
    }
  };

  const formatValue = (value, type) => {
    if (value === null || value === undefined) return '-';
    if (type === 'date' || type === 'datetime') {
      return value;
    }
    if (type === 'decimal') {
      return parseFloat(value).toFixed(4);
    }
    return value;
  };

  const columns = tableSchema?.columns || [];
  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="page-probe">
      <div className="card operation-header-card">
        <div className="batch-toolbar">
          <div className="batch-search">
            <div className="batch-search-item">
              <label>数据表</label>
              <select 
                value={selectedTable || ''} 
                onChange={handleTableChange} 
                className="input"
              >
                <option value="">请选择表</option>
                {tables.map(table => (
                  <option key={table.table_code} value={table.table_code}>
                    {table.table_name} ({table.table_code})
                  </option>
                ))}
              </select>
            </div>
            <div className="batch-search-item">
              <label>开始日期</label>
              <input
                type="date"
                className="input"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                placeholder="开始日期"
              />
            </div>
            <div className="batch-search-item">
              <label>结束日期</label>
              <input
                type="date"
                className="input"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                placeholder="结束日期"
              />
            </div>
            <button className="btn btn-primary" onClick={handleQuery}>查询</button>
          </div>
        </div>
      </div>

      {selectedTable && tableSchema && (
        <div className="probe-content">
          <div className="batch-table-wrapper">
            <table className="batch-table">
              <thead>
                <tr>
                  {columns.map(col => (
                    <th key={col.name}>{col.label}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={columns.length} className="batch-loading">
                      加载中...
                    </td>
                  </tr>
                ) : data.length > 0 ? (
                  data.map((row, index) => (
                    <tr key={index}>
                      {columns.map(col => (
                        <td key={col.name} className={`col-${col.type}`}>
                          {formatValue(row[col.name], col.type)}
                        </td>
                      ))}
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={columns.length} className="batch-empty">
                      暂无数据
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {total > 0 && (
            <div className="pagination-container">
              <div className="pagination-info">
                共 {total} 条记录，当前第 {page} / {totalPages} 页
              </div>
              <div className="pagination-controls">
                <button
                  className="pagination-btn"
                  onClick={() => goToPage(page - 1)}
                  disabled={page <= 1}
                >
                  上一页
                </button>
                <span className="pagination-current">
                  第 {page} 页
                </span>
                <button
                  className="pagination-btn"
                  onClick={() => goToPage(page + 1)}
                  disabled={page >= totalPages}
                >
                  下一页
                </button>
                <div className="pagination-page-size">
                  <span>每页</span>
                  <select
                    value={pageSize}
                    onChange={handlePageSizeChange}
                  >
                    {PAGE_SIZES.map(size => (
                      <option key={size} value={size}>{size}</option>
                    ))}
                  </select>
                  <span>条</span>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {!selectedTable && (
        <div className="batch-empty" style={{ marginTop: '80px' }}>
          <div className="batch-empty-icon">📊</div>
          <h3>请选择数据表</h3>
          <p>从上方下拉菜单中选择要查看的数据表</p>
        </div>
      )}
    </div>
  );
}