/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React, {useEffect, useState} from 'react';
import {channelListErrorMessages} from 'constants/index';

import {useAppDispatch, useAppSelector} from 'store';
import {selectChannelList, selectChannelsLoading, selectChannelsError, listChannels} from 'store/action/channels';

import {LoadingWheel as Loader} from 'components/loaders';
import {Body, Main} from 'components/layout';
import {TableHeaderKey, ITableWithPaginationHeader} from 'components/table';
import {TableWithPagination} from 'components';

import {Error} from 'components/error-renderer/style';
import {createColumnsWithContext} from './columns-data';
import {CreateChannelModal} from './create-channel';

export const ChannelList = (): React.JSX.Element => {
  const dispatch = useAppDispatch();
  const [hasLoaded, setHasLoaded] = useState(false);

  // Redux state
  const channels = useAppSelector(selectChannelList);
  const isFetching = useAppSelector(selectChannelsLoading);
  const error = useAppSelector(selectChannelsError);

  // Local state
  const [isCreateChannelModalOpened, setCreateChannelModalOpened] = useState(false);

  // Create columns with React context for channel name navigation
  const columns = React.useMemo(() => createColumnsWithContext(), []);

  // Load channels on component mount
  useEffect(() => {
    dispatch(listChannels());
  }, [dispatch]);

  // Screen header configuration
  const screenHeader: ITableWithPaginationHeader = {
    [TableHeaderKey.Search]: {},
    [TableHeaderKey.AddRow]: {
      openAddRowModal: () => setCreateChannelModalOpened(true)
    }
  };

  // Handle loading state
  if (isFetching && !hasLoaded) {
    setHasLoaded(true);
    return (
      <Main>
        <Loader />
      </Main>
    );
  }

  // Handle error state
  if (error) {
    return (
      <Body className="table-container">
        <Error>
          {(channelListErrorMessages as Record<string, string>)[error] || error}
          <button onClick={() => dispatch(listChannels())} style={{marginLeft: '10px', padding: '5px 10px'}}>
            Retry
          </button>
        </Error>
      </Body>
    );
  }

  return (
    <Body className="table-container">
      <TableWithPagination title="Channels" screenHeader={screenHeader} columns={columns} data={channels as any[]} paginationItemText="channels" />
      {isCreateChannelModalOpened && (
        <CreateChannelModal
          getChannelList={async () => {
            await dispatch(listChannels());
          }}
          setCreateChannelModalOpened={setCreateChannelModalOpened}
        />
      )}
    </Body>
  );
};
