import { _updateStationPrice } from '@/services/station';
import { ProColumns } from '@ant-design/pro-components';
import { Button, Form, InputNumber, message, Modal } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
import DetailModal from './detailModal';

export const StationTableColumns = ({
  mainTableReload,
}: {
  mainTableReload: () => Promise<void> | undefined;
}): ProColumns<Page_Station.Station>[] => {
  const [priceAdjustmentModalOpen, setPriceAdjustmentModalOpen] = useState(false);
  const [form] = Form.useForm();
  const PriceAdjustmentModal = ({ record }: { record: Page_Station.Station }) => {
    return (
      <Modal
        centered
        title="價格調整"
        open={priceAdjustmentModalOpen}
        onCancel={() => setPriceAdjustmentModalOpen(false)}
        onOk={async () => {
          const values = await form.validateFields();
          console.log(values);
          console.log(record);
          await _updateStationPrice({
            stationId: record.id,
            price: values.price,
          });
          message.success('價格調整成功');
          setPriceAdjustmentModalOpen(false);
          mainTableReload?.();
        }}
      >
        <Form form={form}>
          <Form.Item label="請輸入新價格" name="price">
            <InputNumber />
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  return [
    {
      title: '充電站ID',
      dataIndex: 'id',
      width: 200,
      fixed: 'left',
      copyable: true,
    },
    {
      title: '充電站名稱',
      dataIndex: ['snapshot', 'StationName'],
      width: 180,
    },
    {
      title: '地址',
      dataIndex: ['snapshot', 'Address'],
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '充電樁數量',
      dataIndex: ['Equipments'],
      width: 120,
      render: (_, record) => {
        // 只统计至少有一个充电枪有park的充电桩
        const validEquipments = record.Equipments?.filter((equipment: { ConnectorInfos: any[] }) =>
          equipment.ConnectorInfos?.some((connector: { park: null }) => connector.park !== null),
        );
        return validEquipments?.length || 0;
      },
    },
    {
      title: '充電槍數量',
      dataIndex: ['Equipments'],
      width: 120,
      render: (_, record) => {
        // 只统计有park的充电枪
        return (
          record.Equipments?.reduce((total: number, equipment: Page_Station.Equipment) => {
            const validConnectors =
              equipment.ConnectorInfos?.filter(
                (connector: Page_Station.Connector) => connector.park !== null,
              ) || [];
            return total + validConnectors.length;
          }, 0) || 0
        );
      },
    },

    {
      title: '收費標準',
      dataIndex: 'price',
      width: 120,
      render: (text) => `HK$${text}/kWh`,
    },

    {
      title: '經緯度',
      copyable: true,
      width: 200,
      render: (_, record) =>
        `${record.snapshot?.StationLat || '-'}, ${record.snapshot?.StationLng || '-'}`,
    },
    {
      title: '更新時間',
      dataIndex: 'updatedAt',
      width: 180,
      render: (text) => (text ? dayjs(text as any).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    {
      title: '創建時間',
      dataIndex: 'createdAt',
      width: 180,
      render: (text) => (text ? dayjs(text as any).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },

    {
      title: '操作',
      width: 120,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: 8 }}>
          <DetailModal initData={record} mainTableReload={mainTableReload} key="detailModal" />
          <Button
            type="primary"
            onClick={() => setPriceAdjustmentModalOpen(true)}
            key="priceAdjustment"
          >
            價格調整
          </Button>
          <PriceAdjustmentModal record={record} />
        </div>
      ),
    },
  ];
};
