/**
 * @name 租赁合同管理
 */
import React, { useCallback, useMemo, useRef, useState } from 'react';
import * as antd from 'antd';
import { ConfigProvider } from 'antd';
import {
  AnnotationViewer,
  type AnnotationDirectoryRouteNode,
  type AnnotationSourceDocument,
  type AnnotationViewerOptions,
} from '@axhub/annotation';
import 'antd/dist/reset.css';
import '../vehicle-management/style.css';
import './styles/index.css';
import '../contract-template-management/contract-template-catalog.js';
import LeaseContractApp from './LeaseContractManagement.jsx';
import annotationSourceDocument from './annotation-source.json';

type LeaseContractPageId = 'list' | 'create';

type LeaseContractNavigationRef = {
  openCreate?: () => void;
  backToList?: () => void;
};

declare global {
  interface Window {
    React: typeof React;
    antd: typeof antd;
  }
}

window.React = React;
window.antd = antd;

/** 与 vehicle-management / ONE-OS 主题一致 */
const vmTheme = {
  token: {
    colorPrimary: '#32a06e',
    colorLink: '#32a06e',
    colorLinkHover: '#3fb87c',
    borderRadius: 8,
    fontFamily:
      'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Display", "PingFang SC", "Microsoft YaHei", sans-serif',
    fontSize: 14,
    colorText: '#18181b',
    colorTextSecondary: '#52525b',
    colorBorder: '#e5e7eb',
    colorBgContainer: '#ffffff',
  },
  components: {
    Table: {
      headerBg: '#f6f7f7',
      headerColor: '#71717a',
      rowHoverBg: '#f6f7f7',
      borderColor: '#e5e7eb',
      cellPaddingBlock: 8,
      cellPaddingInline: 12,
    },
    Card: {
      borderRadiusLG: 12,
    },
    InputNumber: {
      handleVisible: true,
    },
  },
};

export default function LeaseContractManagementPage() {
  const [annotationPageId, setAnnotationPageId] = useState<LeaseContractPageId>('list');
  const navigationRef = useRef<LeaseContractNavigationRef>({});

  const handleDirectoryRoute = useCallback((node: AnnotationDirectoryRouteNode) => {
    const payload = node.payload as { pageId?: string } | undefined;
    const pageId: LeaseContractPageId = payload?.pageId === 'create' ? 'create' : 'list';
    if (pageId === 'create') {
      navigationRef.current.openCreate?.();
    } else {
      navigationRef.current.backToList?.();
    }
    setAnnotationPageId(pageId);
  }, []);

  const annotationOptions = useMemo<AnnotationViewerOptions>(
    () => ({
      showToolbar: true,
      showThemeToggle: true,
      showColorFilter: true,
      emptyWhenNoData: false,
      toolbarEdge: 'right',
      currentPageId: annotationPageId,
      onDirectoryRoute: handleDirectoryRoute,
    }),
    [annotationPageId, handleDirectoryRoute],
  );

  return (
    <ConfigProvider theme={vmTheme}>
      <LeaseContractApp
        navigationRef={navigationRef}
        onPageViewChange={setAnnotationPageId}
      />
      <AnnotationViewer
        source={annotationSourceDocument as AnnotationSourceDocument}
        options={annotationOptions}
      />
    </ConfigProvider>
  );
}
