/**
 * @name 供应商管理
 */

import '../vehicle-management/style.css';
import './styles/index.css';
import React, { useCallback, useMemo, useRef, useState } from 'react';
import { Download, FileUp, Plus } from 'lucide-react';
import {
  type AnnotationDirectoryRouteNode,
  type AnnotationSourceDocument,
  type AnnotationViewerOptions
} from '@axhub/annotation';
import { PrototypeAnnotationHost } from '../../common/prototype-annotation-host';
import seedSuppliers from './data/suppliers.json';
import { FilterPanel } from './components/FilterPanel';
import { KpiCards } from './components/KpiCards';
import { SupplierTable } from './components/SupplierTable';
import { CreatePage } from './pages/CreatePage';
import { LeaveConfirmModal } from './components/LeaveConfirmModal';
import { ImportModal } from '../vehicle-management/components/ImportModal';
import { TablePagination } from '../vehicle-management/components/TablePagination';
import {
  EMPTY_CREATE_FORM,
  EMPTY_FILTERS,
  type SupplierCreateForm,
  type SupplierFilters,
  type SupplierKpiKey,
  type SupplierPageId,
  type SupplierRecord,
} from './types';
import { applyFilters, countKpi } from './utils/filters';
import { validateContactPhones } from './utils/phone';
import { cloneCreateForm, isCreateFormDirty } from './utils/createForm';
import annotationSourceDocument from './annotation-source.json';

const DEFAULT_PAGE_SIZE = 10;

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

function validateCreateForm(form: SupplierCreateForm): string | null {
  if (!form.contractingCompany) return '请选择签约公司';
  if (!form.supplierName.trim()) return '请输入供应商名称';
  if (!form.contact.trim()) return '请输入联系人';
  return validateContactPhones(form.contactMobile, form.contactPhone);
}

export default function SupplierManagementApp() {
  const [records] = useState<SupplierRecord[]>(seedSuppliers as SupplierRecord[]);
  const [view, setView] = useState<SupplierPageId>('list');
  const [pendingFilters, setPendingFilters] = useState<SupplierFilters>(EMPTY_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<SupplierFilters>(EMPTY_FILTERS);
  const [kpiTab, setKpiTab] = useState<SupplierKpiKey>('all');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
  const [createForm, setCreateForm] = useState<SupplierCreateForm>(EMPTY_CREATE_FORM);
  const [createFormBaseline, setCreateFormBaseline] = useState<SupplierCreateForm>(EMPTY_CREATE_FORM);
  const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [toast, setToast] = useState('');
  const navigationRef = useRef<NavigationRef>({});

  const showToast = useCallback((msg: string) => {
    setToast(msg);
    window.setTimeout(() => setToast(''), 3000);
  }, []);

  navigationRef.current = {
    openCreate: () => {
      setCreateForm(EMPTY_CREATE_FORM);
      setCreateFormBaseline(cloneCreateForm(EMPTY_CREATE_FORM));
      setView('create');
    },
    backToList: () => setView('list'),
  };

  const kpiCounts = useMemo(() => ({
    all: countKpi(records, 'all'),
    cooperated: countKpi(records, 'cooperated'),
    negotiating: countKpi(records, 'negotiating'),
    terminated: countKpi(records, 'terminated'),
    expired: countKpi(records, 'expired'),
    licenseAbnormal: countKpi(records, 'licenseAbnormal'),
  }), [records]);

  const filtered = useMemo(
    () => applyFilters(records, appliedFilters, kpiTab),
    [records, appliedFilters, kpiTab],
  );

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const paged = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, page, pageSize]);

  const handleSearch = () => {
    setAppliedFilters(pendingFilters);
    setPage(1);
  };

  const handleReset = () => {
    setPendingFilters(EMPTY_FILTERS);
    setAppliedFilters(EMPTY_FILTERS);
    setPage(1);
    setKpiTab('all');
  };

  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setPage(1);
  };

  const handleOpenCreate = () => {
    setCreateForm(EMPTY_CREATE_FORM);
    setCreateFormBaseline(cloneCreateForm(EMPTY_CREATE_FORM));
    setView('create');
  };

  const leaveCreatePage = () => {
    setLeaveConfirmOpen(false);
    setCreateForm(EMPTY_CREATE_FORM);
    setCreateFormBaseline(cloneCreateForm(EMPTY_CREATE_FORM));
    setView('list');
  };

  const handleBackFromCreate = () => {
    if (isCreateFormDirty(createForm, createFormBaseline)) {
      setLeaveConfirmOpen(true);
      return;
    }
    leaveCreatePage();
  };

  const handleSaveCreate = () => {
    const error = validateCreateForm(createForm);
    if (error) {
      showToast(error);
      return;
    }
    setCreateFormBaseline(cloneCreateForm(createForm));
    showToast('已保存草稿（原型演示）');
  };

  const handleSubmitCreate = () => {
    const error = validateCreateForm(createForm);
    if (error) {
      showToast(error);
      return;
    }
    showToast('供应商已提交（原型演示）');
    leaveCreatePage();
  };

  const handleImport = (file: File) => {
    showToast(`已接收文件 ${file.name}，导入校验为原型演示`);
    setImportOpen(false);
  };

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

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

  return (
    <>
      <div className="vm-page sm-page">
        {view === 'create' ? (
          <CreatePage
            form={createForm}
            onChange={(patch) => setCreateForm((prev) => ({ ...prev, ...patch }))}
            onSave={handleSaveCreate}
            onSubmit={handleSubmitCreate}
            onBack={handleBackFromCreate}
          />
        ) : (
          <>

            <FilterPanel
              records={records}
              filters={pendingFilters}
              onChange={(patch) => setPendingFilters((prev) => ({ ...prev, ...patch }))}
              onReset={handleReset}
              onSearch={handleSearch}
            />

            <KpiCards
              counts={kpiCounts}
              active={kpiTab}
              onChange={(key) => { setKpiTab(key); setPage(1); }}
            />

            <section className="vm-table-section">
              <div className="vm-table-toolbar" data-annotation-id="sm-list-toolbar">
                <div className="vm-table-actions">
                  <button type="button" className="vm-btn vm-btn-primary ldb-toolbar-btn" onClick={handleOpenCreate} data-vm-icon="plus">新增供应商
                  </button>
                  <button type="button" className="vm-btn vm-btn-secondary ldb-toolbar-btn" data-vm-icon="import" onClick={() => setImportOpen(true)}>
                    批量导入
                  </button>
                </div>
                <button
                  type="button"
                  className="vm-btn vm-btn-ghost ldb-toolbar-btn"
                  data-vm-icon="download"
                  onClick={() => showToast(`导出功能（原型演示）：当前列表共 ${filtered.length} 条`)}
                >
                  导出
                </button>
              </div>

              <div className="vm-table-card">
                <SupplierTable
                  records={paged}
                  onView={(record) => showToast(`查看：${record.supplierName}（原型演示）`)}
                  onEdit={(record) => showToast(`编辑：${record.supplierName}（原型演示）`)}
                  onDelete={(record) => showToast(`删除：${record.supplierName}（原型演示）`)}
                />
                <div className="vm-table-footer sm-table-footer">
                  <TablePagination
                    page={Math.min(page, totalPages)}
                    pageSize={pageSize}
                    total={filtered.length}
                    onPageChange={setPage}
                    onPageSizeChange={handlePageSizeChange}
                  />
                </div>
              </div>
            </section>
          </>
        )}

        {toast && <div className="vm-toast" role="status" aria-live="polite">{toast}</div>}
      </div>

      <ImportModal open={importOpen} onClose={() => setImportOpen(false)} onImport={handleImport} />
      <LeaveConfirmModal
        open={leaveConfirmOpen}
        onClose={() => setLeaveConfirmOpen(false)}
        onConfirm={leaveCreatePage}
      />

      <PrototypeAnnotationHost
        source={annotationSourceDocument as AnnotationSourceDocument}
        options={annotationOptions}
      />
    </>
  );
}
if (typeof window !== 'undefined') {
  const applySupplierManagementAnnotationFixes = () => {
    if (window.location.pathname !== '/prototypes/supplier-management') return;

    const footer = document.querySelector('.sm-create-footer');
    if (footer && !footer.getAttribute('data-annotation-buttons-applied')) {
      const originalButtons = Array.from(footer.querySelectorAll('button'));
      const createFooterButton = (textContent: string, type: 'button' | 'submit', index: number) => {
        const button = (originalButtons[index] ?? originalButtons[0])?.cloneNode(false) as
          | HTMLButtonElement
          | undefined;
        const nextButton = button ?? document.createElement('button');
        nextButton.type = type;
        nextButton.textContent = textContent;
        return nextButton;
      };

      footer.setAttribute('data-annotation-buttons-applied', 'true');
      footer.replaceChildren(
        createFooterButton('返回', 'button', 0),
        createFooterButton('保存', 'button', 0),
        createFooterButton('提交', 'submit', 1),
      );
    }

    const subjectSelect = document.querySelector(
      'section:nth-of-type(1) label:nth-of-type(1) select.vm-input',
    ) as HTMLSelectElement | null;
    if (subjectSelect) {
      const firstOption = subjectSelect.options[0];
      if (firstOption?.textContent?.trim() === '请选择羚牛签约主体') {
        firstOption.value = '';
        firstOption.disabled = true;
        firstOption.hidden = true;
        if (!subjectSelect.value || subjectSelect.value === '请选择羚牛签约主体') {
          subjectSelect.value = '';
        }
        subjectSelect.style.color = subjectSelect.value ? '' : '#8a8f99';
        if (!subjectSelect.getAttribute('data-placeholder-color-applied')) {
          subjectSelect.setAttribute('data-placeholder-color-applied', 'true');
          subjectSelect.addEventListener('change', () => {
            subjectSelect.style.color = subjectSelect.value ? '' : '#8a8f99';
          });
        }
      }
    }

  };

  window.addEventListener('DOMContentLoaded', applySupplierManagementAnnotationFixes);
  new MutationObserver(applySupplierManagementAnnotationFixes).observe(document.documentElement, {
    childList: true,
    subtree: true,
  });
}
