import { useEffect } from 'react';
import { useParams } from 'react-router';
import { DocumentPage, Page404, Tabs, useLibrary } from 'so-kit-ui';
import config from '../../app-config.jsx';
import { basic_roles } from '../../library.jsx';
import General from './components/tabs/General.jsx';
import { actionConfig, fieldConfig } from './config.jsx';

import Registration from './components/tabs/Registration.jsx';
import Shareholders from './components/tabs/Shareholders.jsx';

const registration = {
  title: 'Registration',
  content: <Registration />,
  errorIds: ['vatNumber', 'remark'],
  criteria: 'sw',
};

const tabsData = [
  {
    title: 'General',
    content: <General />,
    errorIds: [
      'companyName',
      'legalForm',
      'capital',
      'employees',
      'type',
      'address.street',
      'address.city',
      'address.state',
      'address.zip',
      'website',
      'phone',
      'email',
    ],
    criteria: 'eq',
  },
  {
    title: 'Shareholders',
    content: <Shareholders />,
    errorIds: ['shareholders'],
    criteria: 'sw',
  },
];

export const CompanyForm = () => {
  const { id, startOperation } = useParams();
  const { setBreadcrumbs } = useLibrary();

  const tabs = [...tabsData];

  if (
    startOperation !== 'new' &&
    !tabs.some((tab) => tab.title === registration.title)
  ) {
    tabs.push(registration);
  }

  useEffect(() => {
    setBreadcrumbs([
      { name: 'bc.company' },
      { name: 'bc.search', href: '/search' },
      { name: 'bc.form' },
      id ? { name: id, noTranslate: true } : undefined,
    ]);
  }, [id, startOperation]);

  if (!startOperation) {
    return <Page404 />;
  }

  return (
    <div className='me-auto w-full xl:max-w-[1280px] 2xl:max-w-[1536px]'>
      <DocumentPage
        scope='company'
        paramId={id}
        paramStartOperation={startOperation}
        apiBase={config?.company?.apiBase}
        apiUri={config?.company?.apiUri}
        actionConfig={actionConfig}
        fieldConfig={fieldConfig}
        roles={basic_roles}
        ignoreConfirmLeave={['view']}
      >
        <Tabs tabsData={tabs} />
      </DocumentPage>
    </div>
  );
};
