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

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 {columns} from './columns-config';
import {CreateChannelModal} from './create-channel';

const POLLING_INTERVAL = 5000; // 5 seconds
const ChannelListLoading = () => <Main>
  <Loader />
</Main>

export const ChannelList = (): React.JSX.Element => {
  const dispatch = useAppDispatch();
  const interval = useRef<NodeJS.Timeout | null>(null);

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

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

  // Memoized columns to prevent unnecessary re-renders
  const channelsColumns = React.useMemo(() => ({...columns}), []);


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

  // Set up polling for channel updates
  useEffect(() => {
    if (interval.current) {
      clearInterval(interval.current);
    }

    // Only start polling if we have channels and not currently fetching
    if (channels.length > 0 && !isFetching) {
      interval.current = setInterval(() => {
        dispatch(listChannels());
      }, POLLING_INTERVAL);
    }

    return () => {
      if (interval.current) {
        clearInterval(interval.current);
      }
    };
  }, [dispatch, channels.length, isFetching]);

  // Memoized screen header to prevent unnecessary re-renders
  const screenHeader: ITableWithPaginationHeader = React.useMemo(() => ({
    [TableHeaderKey.Search]: {},
    [TableHeaderKey.AddRow]: {
      openAddRowModal: () => {
        setCreateChannelModalOpened(true);
      }
    }
  }), []);

  // Callback for handling search and sort changes (no-op since TableWithPagination handles internally)
  const changeScreenProps = useCallback((_data: Partial<ITableSortSearch>) => {
    // TableWithPagination handles search and sort internally
    // This is kept for compatibility with the component interface
  }, []);

  // Memoized callback for refreshing channel list
  const refreshChannelList = useCallback(async () => {
    await dispatch(listChannels());
  }, [dispatch]);

  // Early return for 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 (
    <div>
      <Body className="table-container">
        {isFetching ? <ChannelListLoading /> : channels.length === 0 ? (
            <Main>
              <div style={{ textAlign: 'center', padding: '2rem' }}>
                <h3>No channels found</h3>
                <p>Get started by creating your first channel.</p>
                <button 
                  onClick={() => setCreateChannelModalOpened(true)}
                  style={{ padding: '10px 20px', marginTop: '1rem' }}
                >
                  Create Channel
                </button>
              </div>
            </Main>
          ) : (
            <TableWithPagination
              title="Channels"
              screenHeader={screenHeader}
              columns={channelsColumns}
              data={channels as any[]}
              paginationItemText="channels"
              changeSortProps={changeScreenProps}
              changeSearch={changeScreenProps}
            />
          )}
      </Body>
      {isCreateChannelModalOpened && (
        <CreateChannelModal 
          getChannelList={refreshChannelList} 
          setCreateChannelModalOpened={setCreateChannelModalOpened} 
        />
      )}
    </div>
  );
};
