import { useEffect } from 'react';
import { Link } from 'react-router';
import { SearchPage, StatusBubble, useLibrary } from 'so-kit-ui';
import config from '../../app-config.jsx';
import { basic_roles } from '../../library.jsx';

export const getColorForState = (state) => {
  switch (state) {
    case 'SUBMITTED':
      return 'info';
    case 'APPROVED':
      return 'success';
    case 'REJECTED':
      return 'error';
  }
};

const columns = [
  {
    accessor: 'data.companyName',
    header: 'Company Name',
    sortable: true,
    width: '150px',
    renderer: ({ value, row }) => (
      <Link
        to={`/companies/${row.id}/view`}
        className='font-semibold'
      >
        {`${row?.data?.['companyName']}`}
      </Link>
    ),
  },
  {
    accessor: 'data.establishedDate',
    header: 'Established Date',
    sortable: true,
    asDate: true,
    width: '150px',
  },
  {
    accessor: 'data.legalForm',
    header: 'Legal Form',
    sortable: true,
    width: '150px',
  },
  {
    accessor: 'data.employees',
    header: 'Number of Employees',
    sortable: true,
    width: '150px',
  },
  {
    accessor: 'data.vatNumber',
    header: 'VAT Number',
    sortable: true,
    width: '150px',
  },
  {
    accessor: 'metadata.current.state',
    header: 'Status',
    sortable: true,
    width: '150px',
    renderer: ({ value, row }) => (
      <div className='max-w-[100px]'>
        <StatusBubble
          outlined={false}
          value={value}
          color={getColorForState(value)}
        />
      </div>
    ),
  },
];

const filters = [
  {
    accessor: 'metadata.current.state',
    label: 'Status',
    type: 'select',
    options: [
      { value: 'APPROVED', label: 'Approved' },
      { value: 'REJECTED', label: 'Rejected' },
      { value: 'SUBMITTED', label: 'Submitted' },
    ],
    inputProps: {
      displayLabel: true,
    },
  },
  {
    accessor: 'data.establishedDate',
    label: 'Established Date',
    type: 'date',
  },
];

export const CompanySearch = () => {
  const { setBreadcrumbs } = useLibrary();

  useEffect(() => {
    setBreadcrumbs([{ name: 'bc.company' }, { name: 'bc.search' }]);
  }, []);

  return (
    <div className='me-auto w-full xl:max-w-[1280px] 2xl:max-w-[1536px] h-[calc(100vh-88px)]'>
      <SearchPage
        scope='company'
        apiBase={config?.company?.apiBase}
        apiUri={config?.company?.apiUri}
        columns={columns}
        filters={filters}
        size={50}
        roles={basic_roles}
        tableProps={{
          stackable: false,
        }}
      />
    </div>
  );
};
