import {
  ActionType,
  PageContainer,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import { useIntl, useRequest } from '@umijs/max';
import { Button, message, Modal, Space, theme } from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import {
  createVehicle,
  deleteVehicle,
  getVehicleDetail,
  getVehicleList,
  updateVehicle,
  updateVehicleStatus,
} from '@/services/vehicle';
import type {
  VehicleFormValues,
  VehicleItem,
  VehicleListParams,
  VehicleStatus,
  VehicleType,
} from './data';
import {
  createVehicleColumns,
  getStatusValueEnum,
  getTypeValueEnum,
} from './columns';
import VehicleFormModal from './components/VehicleFormModal';

const VehicleManagementPage: React.FC = () => {
  const intl = useIntl();
  const { token } = theme.useToken();
  const [messageApi, contextHolder] = message.useMessage();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance<VehicleFormValues>>();

  const [modalOpen, setModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<string>();
  const [currentRow, setCurrentRow] = useState<VehicleItem | undefined>();
  const [detailLoading, setDetailLoading] = useState(false);

  const statusEnum = useMemo(() => getStatusValueEnum(intl), [intl]);
  const typeEnum = useMemo(() => getTypeValueEnum(intl), [intl]);

  const { run: runGetList } = useRequest<
    VehicleListParams,
    [VehicleListParams & { current?: number; pageSize?: number }]
  >(getVehicleList as any, {
    manual: true,
  });

  const { run: runCreate, loading: createLoading } = useRequest(createVehicle, {
    manual: true,
  });

  const { run: runUpdate, loading: updateLoading } = useRequest(updateVehicle, {
    manual: true,
  });

  const { run: runDelete, loading: deleteLoading } = useRequest(deleteVehicle, {
    manual: true,
  });

  const { run: runUpdateStatus, loading: updateStatusLoading } = useRequest(
    updateVehicleStatus,
    {
      manual: true,
    },
  );

  const openCreateModal = () => {
    setEditingId(undefined);
    setCurrentRow(undefined);
    formRef.current?.resetFields();
    setModalOpen(true);
  };

  const openEditModal = async (record: VehicleItem) => {
    setEditingId(record.id);
    setCurrentRow(record);
    setModalOpen(true);

    try {
      setDetailLoading(true);
      const detail = (await getVehicleDetail(record.id)) as VehicleItem;
      setCurrentRow(detail);
      formRef.current?.setFieldsValue(detail);
    } catch {
      messageApi.error(
        intl.formatMessage({
          id: 'common.error.loadDetail',
          defaultMessage: '详情加载失败',
        }),
      );
    } finally {
      setDetailLoading(false);
    }
  };

  const handleDelete = (record: VehicleItem) => {
    Modal.confirm({
      title: intl.formatMessage({
        id: 'common.confirm.delete',
        defaultMessage: '确认删除吗？',
      }),
      content: record.plateNumber,
      okType: 'danger',
      okButtonProps: { loading: deleteLoading, disabled: deleteLoading },
      cancelButtonProps: { disabled: deleteLoading },
      okText: intl.formatMessage({ id: 'common.ok', defaultMessage: '确定' }),
      cancelText: intl.formatMessage({
        id: 'common.cancel',
        defaultMessage: '取消',
      }),
      async onOk() {
        try {
          await runDelete(record.id);
          messageApi.success(
            intl.formatMessage({
              id: 'common.success.delete',
              defaultMessage: '删除成功',
            }),
          );
          actionRef.current?.reload();
        } catch {
          messageApi.error(
            intl.formatMessage({
              id: 'common.error.delete',
              defaultMessage: '删除失败',
            }),
          );
        }
      },
    });
  };

  const handleStatusChange = async (record: VehicleItem, status: VehicleStatus) => {
    try {
      await runUpdateStatus(record.id, status);
      messageApi.success(
        intl.formatMessage({
          id: 'vehicle.status.update.success',
          defaultMessage: '状态更新成功',
        }),
      );
      actionRef.current?.reload();
    } catch {
      messageApi.error(
        intl.formatMessage({
          id: 'vehicle.status.update.error',
          defaultMessage: '状态更新失败',
        }),
      );
    }
  };

  const columns = useMemo(
    () =>
      createVehicleColumns({
        intl,
        statusEnum,
        typeEnum,
        onEdit: openEditModal,
        onDelete: handleDelete,
      }),
    [handleDelete, intl, openEditModal, statusEnum, typeEnum],
  );

  return (
    <>
      {contextHolder}
      <PageContainer
        header={{
          title: intl.formatMessage({
            id: 'pages.vehicle.title',
            defaultMessage: '车辆管理',
          }),
        }}
      >
        <ProTable<VehicleItem, VehicleListParams>
          actionRef={actionRef}
          rowKey="id"
          columns={columns}
          search={{ labelWidth: 120 }}
          toolbar={{
            title: (
              <Space>
                <span
                  style={{
                    width: 6,
                    height: 6,
                    borderRadius: '50%',
                    backgroundColor: token.colorPrimary,
                    display: 'inline-block',
                  }}
                />
                <span>
                  {intl.formatMessage({
                    id: 'pages.vehicle.table.title',
                    defaultMessage: '车辆列表',
                  })}
                </span>
              </Space>
            ),
            actions: [
              <Button key="create" type="primary" onClick={openCreateModal}>
                {intl.formatMessage({
                  id: 'pages.vehicle.add',
                  defaultMessage: '新增车辆',
                })}
              </Button>,
            ],
          }}
          request={async (params) => {
            const response = (await runGetList(params)) as VehicleListResponse | VehicleItem[];
            if (Array.isArray(response)) {
              return {
                data: response,
                success: true,
                total: response.length,
              };
            }
            return {
              data: response.data,
              success: response.success,
              total: response.total,
            };
          }}
        />

        <VehicleFormModal
          intl={intl}
          open={modalOpen}
          formRef={formRef}
          submitting={createLoading || updateLoading || detailLoading}
          initialValues={currentRow}
          onOpenChange={(open) => {
            setModalOpen(open);
            if (!open) {
              setEditingId(undefined);
              setCurrentRow(undefined);
            }
          }}
          onFinish={async (values) => {
            try {
              if (editingId) {
                await runUpdate({ ...values, id: editingId });
                messageApi.success(
                  intl.formatMessage({
                    id: 'common.success.update',
                    defaultMessage: '更新成功',
                  }),
                );
              } else {
                await runCreate(values);
                messageApi.success(
                  intl.formatMessage({
                    id: 'common.success.add',
                    defaultMessage: '添加成功',
                  }),
                );
              }
              actionRef.current?.reload();
              return true;
            } catch {
              messageApi.error(
                intl.formatMessage({
                  id: 'common.error.update',
                  defaultMessage: '更新失败',
                }),
              );
              return false;
            }
          }}
        />
      </PageContainer>
    </>
  );
};

export default VehicleManagementPage;

