import React, { useState, useEffect } from 'react';
import { Table, Select, Space, Button as AntButton } from 'antd';
import { Button } from '../ui/button';
import { slotApi, LockCabinetSlotVO, SlotPageParam } from '../../api/lockCabinet/slots';
import { DICT_TYPE, getIntDictOptions, getDictLabel } from '../../utils/dict';
import { dateFormatter } from '../../utils/formatTime';
import type { ColumnsType } from 'antd/es/table';
import { useTranslation } from 'react-i18next';

interface SlotsListProps {
  cabinetId: string;
}

export default function SlotsList({ cabinetId }: SlotsListProps) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<LockCabinetSlotVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<SlotPageParam>({
    pageNo: 1,
    pageSize: 10,
    cabinetId: cabinetId ? Number(cabinetId) : undefined,
    slotType: undefined,
    status: undefined,
  });

  // 获取仓位列表
  const getList = async (params?: SlotPageParam) => {
    const currentParams = params || queryParams;
    const cleanParams: SlotPageParam = {
      ...currentParams,
      cabinetId: cabinetId ? Number(cabinetId) : undefined,
    };
    // 过滤掉 undefined 的参数
    Object.keys(cleanParams).forEach(key => {
      if (cleanParams[key] === undefined || cleanParams[key] === null || cleanParams[key] === '') {
        delete cleanParams[key];
      }
    });
    setLoading(true);
    try {
      const response = await slotApi.getIsLockCabinetSlotsPage(cleanParams);
      setList(response.list || []);
      setTotal(response.total || 0);
    } catch (error: any) {
      console.error('获取仓位列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (cabinetId) {
      getList();
    }
  }, [cabinetId]);

  // 搜索
  const handleQuery = () => {
    const newParams = { ...queryParams, pageNo: 1 };
    setQueryParams(newParams);
    getList(newParams);
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: SlotPageParam = {
      pageNo: 1,
      pageSize: 10,
      cabinetId: cabinetId ? Number(cabinetId) : undefined,
      slotType: undefined,
      status: undefined,
    };
    setQueryParams(resetParams);
    getList(resetParams);
  };


  // 表格列定义
  const columns: ColumnsType<LockCabinetSlotVO> = [
    {
      title: '仓位类型',
      dataIndex: 'slotType',
      key: 'slotType',
      render: (text) => getDictLabel(DICT_TYPE.SLOT_TYPE, text) || '-',
    },
    {
      title: '行',
      dataIndex: 'row',
      key: 'row',
    },
    {
      title: '列',
      dataIndex: 'col',
      key: 'col',
    },
    {
      title: '是否被占用',
      dataIndex: 'isOccupied',
      key: 'isOccupied',
      render: (text) => getDictLabel(DICT_TYPE.ISOCCUPIED_STATUS, text) || '-',
    },
    {
      title: '占用仓位的硬件ID',
      dataIndex: 'hardwareId',
      key: 'hardwareId',
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text) => {
        if (text === null || text === undefined) return '-';
        return getDictLabel(DICT_TYPE.SLOT_STATUS, text) || '-';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      render: (text) => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text) => text ? dateFormatter(text) : '-',
    },
  ];


  const slotTypeOptions = getIntDictOptions(DICT_TYPE.SLOT_TYPE);
  const statusOptions = getIntDictOptions(DICT_TYPE.SLOT_STATUS);

  return (
    <div className="space-y-4">
      {/* 搜索栏 */}
      <div className="bg-white p-4 rounded-lg shadow-sm">
        <Space size="middle" wrap>
          <div className="flex items-center gap-2 flex-shrink-0">
            <span className="text-sm font-medium">仓位类型:</span>
            <Select
              className="min-w-[150px] max-w-[200px]"
              placeholder="请选择仓位类型"
              allowClear
              value={queryParams.slotType}
              onChange={(value) => setQueryParams(prev => ({ ...prev, slotType: value }))}
            >
              {slotTypeOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </div>
          {/* <div className="flex items-center gap-2">
            <span className="text-sm font-medium">状态:</span>
            <Select
              className="min-w-[150px] max-w-[200px]"
              placeholder="请选择状态"
              allowClear
              value={queryParams.status}
              onChange={(value) => setQueryParams(prev => ({ ...prev, status: value }))}
            >
              {statusOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </div> */}
          <AntButton type="primary" onClick={handleQuery}>搜索</AntButton>
          <AntButton onClick={resetQuery}>重置</AntButton>
        </Space>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-lg shadow-sm">
        <Table
          rowKey={(record) => (record as any).slotId || (record as any).id || `row-${Math.random()}`}
          loading={loading}
          dataSource={list}
          columns={columns}
          pagination={false}
          scroll={{ x: 'max-content' }}
        />
      </div>

      {/* 分页 */}
      {!loading && list.length > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => {
                  const newParams = { ...queryParams, pageNo: queryParams.pageNo - 1 };
                  setQueryParams(newParams);
                  getList(newParams);
                }}
                disabled={queryParams.pageNo <= 1}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize) || 1}
              </span>
              <Button
                onClick={() => {
                  const newParams = { ...queryParams, pageNo: queryParams.pageNo + 1 };
                  setQueryParams(newParams);
                  getList(newParams);
                }}
                disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize)}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

