import React, { useEffect, useState } from 'react';
import { Table, Typography, Spin, Message, Card } from '@arco-design/web-react';
import '@arco-design/web-react/dist/css/arco.css';
import API_BASE_URL from './config';

const columns = [
  {
    title: 'Timestamp',
    dataIndex: 'timestamp',
    render: (val) => new Date(val).toLocaleString(),
  },
  {
    title: 'Quantity (MW)',
    dataIndex: 'quantity',
    render: (val) => val.toFixed(2),
  },
  {
    title: 'Price ($/MWh)',
    dataIndex: 'price',
    render: (val) => `$${val.toFixed(2)}`,
  },
  {
    title: 'Status',
    dataIndex: 'status',
    render: (val) => {
      let color = 'gray';
      if (val === 'Success') color = 'green';
      else if (val === 'Fail') color = 'red';
      else if (val === 'Submitted') color = 'blue';
      return <Typography.Text style={{ color }}>{val}</Typography.Text>;
    }
  },
  {
    title: 'PnL',
    dataIndex: 'pnl',
    render: (val) => {
      if (val === null) return 'N/A';
      const color = val >= 0 ? 'green' : 'red';
      return <Typography.Text style={{ color }}>{val.toFixed(2)}</Typography.Text>;
    }
  }
];

function BidsPage() {
  const [bids, setBids] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${API_BASE_URL}/bids/`)
      .then((res) => {
        if (!res.ok) throw new Error('Failed to fetch bids');
        return res.json();
      })
      .then((json) => setBids(json))
      .catch((err) => {
        console.error(err);
        Message.error('Failed to load bids.');
      })
      .finally(() => setLoading(false));
  }, []);

  return (
    <div style={{ padding: 20, backgroundColor: 'var(--color-fill-2)' }}>
      <Typography.Title heading={4}>Your Submitted Bids</Typography.Title>
      <Card style={{ marginTop: 16 }}>
        {loading ? (
          <Spin />
        ) : (
          <Table
            columns={columns}
            data={bids}
            rowKey="id"
            pagination={{
              pageSize: 10,
              sizeCanChange: true,
              showTotal: true,
            }}
          />
        )}
      </Card>
    </div>
  );
}

export default BidsPage;
