import PaymentsTable from './PaymentsTable';
import Results from './Results';
import Validation from './Validation';
import Background from '@/Components/Layout/Background';
import { useErrors, useStore } from '@/stores/hooks';
import { min } from '@/styles/mq';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Badge, Tabs } from 'ui/elements';

const outputTabs = [PaymentsTable, Results, Validation];
const items = outputTabs.map(({ Component, id, title }) => {
  let Label = () => title;

  if (id === 'validation') {
    Label = observer(() => {
      const { hasErrors } = useErrors();

      return (
        <Badge offset={[5, 0]} dot={hasErrors}>
          {title}
        </Badge>
      );
    });
  }

  return {
    children: <Component />,
    key: id,
    label: <Label />,
  };
});

const Wrapper = styled(Background)`
  padding: 4px 10px;
  min-height: 200px;

  ${min('laptop')} {
    padding: 4px 18px;
    min-height: 790px;
  }
`;

export const Output = observer(({ tabs }) => {
  const { $results } = useStore();
  const [activeKey, setActiveKey] = useState(undefined);
  const { hasErrors } = useErrors();

  useEffect(() => {
    if ($results.payments.length > 0) {
      setActiveKey('payments-table');
    }

    if (!tabs && hasErrors) {
      setActiveKey('validation');
    }
  }, [$results.payments.length, hasErrors, tabs]);

  return (
    <Wrapper>
      <Tabs
        items={tabs ? items.filter((x) => x.key !== 'validation') : items}
        activeKey={activeKey}
        onChange={(key) => {
          setActiveKey(key);
        }}
      />
    </Wrapper>
  );
});
