import React, { type ReactNode } from 'react';
import { CheckCircle, DoDisturbAlt, LinkOff } from '@mui/icons-material';

import { STATUS_ACTIVE, STATUS_ARCHIVED, STATUS_DISCONNECTED, TYPE_MRSS, TYPE_MS_STREAM } from '../../../constants';
import { STATUS_ACTIVE_TITLE, STATUS_ARCHIVED_TITLE, STATUS_DISCONNECTED_TITLE } from '../../constants';

import { FeedsDataRecordType, FeedsType, StatusType } from '@/modules/feeds/SelfServeList/types';

import { Stack, Typography } from '@/mui/components';

type Props = {
  status: StatusType;
  source?: FeedsDataRecordType['source'];
  type: FeedsType;
};

const ICONS: Record<number, ReactNode> = {
  [STATUS_ACTIVE]: <CheckCircle sx={{ color: 'success.main' }} />,
  [STATUS_ARCHIVED]: <DoDisturbAlt sx={{ color: 'error.main' }} />,
  [STATUS_DISCONNECTED]: <LinkOff sx={{ color: 'info.main' }} />,
};

const TITLES: Record<number, string> = {
  [STATUS_ACTIVE]: STATUS_ACTIVE_TITLE,
  [STATUS_ARCHIVED]: STATUS_ARCHIVED_TITLE,
  [STATUS_DISCONNECTED]: STATUS_DISCONNECTED_TITLE,
};

const normalizeStatus = (status: number, type: FeedsType, source?: FeedsDataRecordType['source']): number => {
  if (status === -1) return STATUS_ARCHIVED;
  if (status === 1 && type === TYPE_MRSS) return STATUS_ACTIVE;

  if (type === TYPE_MS_STREAM) return STATUS_ACTIVE;

  if (!source?.isConnected) return STATUS_DISCONNECTED;
  if (source?.isConnected && status === 1) return STATUS_ACTIVE;
  return status;
};

export default function StatusCell({ status, source, type }: Props) {
  const s = normalizeStatus(status, type, source);
  return (
    <Stack direction="row" spacing={2} alignItems="center">
      {ICONS[s]}
      <Typography variant="body2" color="text.primary">
        {TITLES[s]}
      </Typography>
    </Stack>
  );
}
