/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React from 'react';
import {faEllipsisV} from '@fortawesome/free-solid-svg-icons';
import {CellType, ColumnsType, DataRowType} from 'components/table';
import {ChannelIconMenu} from 'components/channel-icon-menu';
import {IconMenuPosition} from 'components/icon-menu/types';
import {ChannelPublishingStateIndicator} from './channel-publishing-state-indicator';
import {theme} from 'theme';
import {useAppDispatch} from 'store';
import {setSelectedChannel} from 'store/slices/Channels.slice';
import {useNavigate} from 'react-router-dom';
import styled from 'styled-components';

const ChannelNameLink = styled.a`
  color: ${theme.colors.linkBlue};
  text-decoration: none;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
`;

// Component that needs to be rendered within a React context
const ChannelNameCellComponent = (row?: DataRowType) => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    if (row?.channelId && row?.name) {
      dispatch(setSelectedChannel(row as any));
      navigate(`/channels/${row.channelId}`);
    }
  };

  return (
    <ChannelNameLink onClick={handleClick}>
      {row?.name || 'N/A'}
    </ChannelNameLink>
  );
};

// Factory function to create columns with React context
export const createColumnsWithContext = (): ColumnsType => ({
  indicator: {
    title: '',
    hasBorder: false,
    width: 40,
    type: CellType.Component,
    renderCell: ChannelPublishingStateIndicator
  },
  name: {
    title: 'Channel Name',
    type: CellType.Component,
    renderCell: ChannelNameCellComponent,
    thStyle: {
      textAlign: 'left',
      paddingLeft: 16
    }
  },
  alias: {
    title: 'Alias',
    textCell: {propName: 'alias'}
  },
  channelId: {
    title: 'Channel Id',
    hideColumnAt: theme.screenSizes.desktop,
    textCell: {propName: 'channelId'}
  },
  streamKey: {
    title: 'Stream Key',
    hideColumnAt: theme.screenSizes.tablet,
    textCell: {propName: 'streamKey'}
  },
  created: {
    title: 'Created',
    hideColumnAt: theme.screenSizes.large,
    type: CellType.Date,
    textCell: {propName: 'created'}
  },
  dropdown: {
    title: '',
    hasBorder: false,
    width: 50,
    type: CellType.DropDown,
    dropdownCell: {
      Component: ChannelIconMenu,
      keys: ['channelId', 'name', 'alias'],
      componentProps: {
        icon: faEllipsisV,
        showTail: false,
        position: IconMenuPosition.Left
      }
    }
  }
});
