import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Input, Form, Modal, message, Popconfirm, Tooltip, Select } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import TemplateContainer from '@/pages/TemplateContainer';
import { request, useModel } from '@umijs/max';
import { ColumnsType, FilterValue, SorterResult, TableCurrentDataSource, TablePaginationConfig } from 'antd/es/table/interface';
import { objectToQueryString } from '@/services/services/common';
import { FormatDate } from '@/util/time';
import { GetMachineAuthorizationTypeOption, GetMachineAuthorizationTypeOptions } from '@/services/enum/machineAuthorizationEnum';
import { useFormReset } from '@/hooks/useFormReset';
import AddMachineIdAuthorization from './AddMachineIdAuthorization';


const MachineIdAuthorization: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [dataSource, setDataSource] = useState<MachineAuthorizationModel.MachineAuthorizationBase[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [messageApi, messageHolder] = message.useMessage();
  const { setFormRef, resetForm } = useFormReset();
  const [id, setId] = useState<string>('');
  const [tableParams, setTableParams] = useState<TableModel.TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      totalBoundaryShowSizeChanger: true,
    },
  });

  useEffect(() => {
    QueryMachineAuthorizationCollection(tableParams, form.getFieldsValue());
  }, []);

  async function QueryMachineAuthorizationCollection(tableParams: TableModel.TableParams, options?: any) {
    try {
      setLoading(true);

      let data = {
        ...options,
        page: tableParams.pagination?.current,
        pageSize: tableParams.pagination?.pageSize,
      }
      let query = objectToQueryString(data)
      let res = await request<ApiResponse.SuccessItem<MachineAuthorizationModel.QueryMachineAuthorizationData>>(`/lms/Other/QueryMachineAuthorizationCollection?${query}`, {
        method: 'GET',
      });
      if (res.code != 1) {
        throw new Error(res.message);
      }
      let resData = res.data;
      setDataSource(resData.collection);
      setTableParams({
        pagination: {
          ...tableParams.pagination,
          total: resData.total
        }
      })
      messageApi.success('Data fetched successfully');
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  const columns: ColumnsType<MachineAuthorizationModel.MachineAuthorizationBase> = [
    {
      title: '机器码/唯一授权码',
      dataIndex: 'machineID',
      key: 'machineId',
      width: '200px',
      render: (text) => (
        <Tooltip title={text}>
          <span>{text?.length > 20 ? `${text.substring(0, 20)}...` : text}</span>
        </Tooltip>
      ),
    },
    {
      title: '授权类型',
      dataIndex: 'type',
      key: 'type',
      render: (text, record) => GetMachineAuthorizationTypeOption(record.type),
    },
    {
      title: '授权时间',
      dataIndex: 'authorizedDate',
      key: 'authorizedDate',
      render: (text) => FormatDate(text),
    },
    {
      title: '授权到期时间',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (text) => FormatDate(text),
    },
    {
      title: '授权码',
      dataIndex: 'authorizationCode',
      key: 'authorizationCode',
      render: (text) => (
        <Tooltip title={text}>
          <span>{text?.length > 30 ? `${text.substring(0, 30)}...` : text}</span>
        </Tooltip>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'createdUser',
      key: 'createdUser',
      render: (text) => {
        const userName = text?.userName || '';
        return (
          <Tooltip title={userName}>
            <span>{userName.length > 10 ? `${userName.substring(0, 10)}...` : userName}</span>
          </Tooltip>
        );
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdDate',
      key: 'createdDate',
      render: (text, record) => FormatDate(record.createdDate),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>
            Edit
          </Button>
          <Popconfirm
            title="Are you sure you want to revoke this authorization?"
            onConfirm={() => handleRevoke(record.id)}
            okText="Yes"
            cancelText="No"
          >
            <Button type="link" danger>
              Revoke
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleEdit = (record: MachineAuthorizationModel.MachineAuthorizationBase) => {
    setModalVisible(true);
  };

  const handleRevoke = async (id: string) => {
    try {
      const newData = dataSource.map(item =>
        item.id === id ? { ...item, status: 'revoked' as const } : item
      );
      setDataSource(newData);
      messageApi.success('Authorization revoked successfully');
    } catch (error) {
      messageApi.error('Failed to revoke authorization');
    }
  };

  const handleAdd = () => {
    form.resetFields();
    setModalVisible(true);
  };


  async function TableChangeHandle(pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<MachineAuthorizationModel.MachineAuthorizationBase> | SorterResult<MachineAuthorizationModel.MachineAuthorizationBase>[], extra: TableCurrentDataSource<MachineAuthorizationModel.MachineAuthorizationBase>): Promise<void> {
    await QueryMachineAuthorizationCollection({ pagination }, form.getFieldsValue());
    setTableParams({
      pagination: {
        ...tableParams.pagination,
        current: pagination.current,
        pageSize: pagination.pageSize
      }
    })
  }

  async function modalCancel(): Promise<void> {
    setModalVisible(false);
    resetForm();
    setId('');
    // 这边调用加载数据的方法
    await QueryMachineAuthorizationCollection(tableParams, form.getFieldsValue());
  }

  return (
    <TemplateContainer navTheme={initialState?.settings?.navTheme ?? "realDark"}>
      <Form
        form={form}
        layout="inline"
        onFinish={(values) => QueryMachineAuthorizationCollection(tableParams, values)}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="machineID" label="机器码">
          <Input placeholder="Machine ID" style={{ width: 200 }} />
        </Form.Item>

        <Form.Item name="authorizationCode" label="授权码">
          <Input placeholder="Authorization Code" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name="type" label="授权类型">
          <Select
            placeholder="Authorization Type"
            style={{ width: 180 }}
            allowClear
            options={GetMachineAuthorizationTypeOptions()}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button onClick={() => form.resetFields()}>
              重置
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加机器码授权
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        columns={columns}
        dataSource={dataSource}
        rowKey="id"
        loading={loading}
        pagination={tableParams.pagination}
        onChange={TableChangeHandle}
      />

      <Modal width={600} title="新增机器码" maskClosable={false} open={modalVisible} footer={null} onCancel={modalCancel}>
        <AddMachineIdAuthorization setFormRef={setFormRef} id={id} />
      </Modal>
      {messageHolder}
    </TemplateContainer>
  );
};

export default MachineIdAuthorization;