import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Skeleton from '@material-hu/components/design-system/Skeleton';
import HuPills from '@material-hu/components/design-system/Pills';
import HuTable from '@material-hu/components/design-system/Table';
import HuTableBody from '@material-hu/components/design-system/Table/components/TableBody';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import HuTableHead from '@material-hu/components/design-system/Table/components/TableHead';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import { useLokaliseTranslation } from 'src/utils/i18n';

import type {
  RetentionConversationListItem,
  ActionSummary,
} from '../../types/retention';
import { getSmTicketPillType } from 'src/pages/dashboard/ServiceManagement/utils';
import { CategoryBadge } from '../CategoryBadge';

type ConversationTableProps = {
  conversations: RetentionConversationListItem[];
  isLoading: boolean;
  isFetchingNextPage: boolean;
  onRowClick: (id: number) => void;
};

const COLUMN_KEYS = [
  'record',
  'employee',
  'category',
  'associated_request',
  'request_status',
] as const;

function AssociatedRequestCell({
  actions,
  t,
}: {
  actions: ActionSummary[];
  t: (key: string) => string;
}) {
  const first = actions[0];
  if (!first) {
    return (
      <Typography
        variant="globalS"
        sx={{ color: ({ palette }) => palette.new.text.neutral.disabled }}
      >
        —
      </Typography>
    );
  }

  return (
    <Stack sx={{ gap: 0.25 }}>
      <Typography
        variant="globalS"
        sx={{ color: ({ palette }) => palette.new.text.neutral.default }}
      >
        {t(`tali.action_type.${first.actionType}`)}
      </Typography>
      {first.taskNumber != null && (
        <Typography
          variant="globalXS"
          sx={{ color: ({ palette }) => palette.new.text.neutral.lighter }}
        >
          #{first.taskNumber}
        </Typography>
      )}
    </Stack>
  );
}

function TicketStatusCell({ actions }: { actions: ActionSummary[] }) {
  const first = actions.find(a => a.smTicketState != null);
  if (!first) {
    return (
      <Typography
        variant="globalS"
        sx={{ color: ({ palette }) => palette.new.text.neutral.disabled }}
      >
        —
      </Typography>
    );
  }

  return (
    <HuPills
      type={getSmTicketPillType(first.smTicketState!, first.smTicketTerminal)}
      label={first.smTicketState!}
      hasIcon={false}
      size="small"
    />
  );
}

function SkeletonRows({ cols }: { cols: number }) {
  return (
    <>
      {Array.from({ length: 5 }).map((_, idx) => (
        <HuTableRow key={idx}>
          {Array.from({ length: cols }).map((__, cidx) => (
            <HuTableCell key={cidx}>
              <Skeleton
                width={cidx === 1 ? 140 : 80}
                height={20}
              />
            </HuTableCell>
          ))}
        </HuTableRow>
      ))}
    </>
  );
}

export function ConversationTable({
  conversations,
  isLoading,
  isFetchingNextPage,
  onRowClick,
}: ConversationTableProps) {
  const { t } = useLokaliseTranslation('backoffice_only');

  return (
    <HuTableContainer>
      <HuTable>
        <HuTableHead>
          <HuTableRow headerRow>
            {COLUMN_KEYS.map(key => (
              <HuTableCell
                key={key}
                headerCell
              >
                {t(`tali.conversation_list.columns.${key}`)}
              </HuTableCell>
            ))}
          </HuTableRow>
        </HuTableHead>

        <HuTableBody>
          {isLoading && <SkeletonRows cols={COLUMN_KEYS.length} />}

          {!isLoading && conversations.length === 0 && (
            <HuTableRow>
              <HuTableCell colSpan={COLUMN_KEYS.length}>
                <Typography
                  variant="globalS"
                  sx={{
                    textAlign: 'center',
                    py: 5,
                    color: ({ palette }) => palette.new.text.neutral.lighter,
                  }}
                >
                  {t('tali.conversation_list.empty_state')}
                </Typography>
              </HuTableCell>
            </HuTableRow>
          )}

          {!isLoading &&
            conversations.map(item => (
              <HuTableRow
                key={item.id}
                onClick={() => onRowClick(item.id)}
                sx={{
                  cursor: 'pointer',
                  '&:hover': {
                    backgroundColor: ({ palette }) =>
                      palette.new.background.layout.default,
                  },
                }}
              >
                <HuTableCell>
                  <Typography
                    variant="globalS"
                    sx={{
                      color: ({ palette }) => palette.new.text.neutral.default,
                    }}
                  >
                    #{item.id}
                  </Typography>
                </HuTableCell>

                <HuTableCell>
                  <Stack sx={{ gap: 0.25 }}>
                    <Typography
                      variant="globalS"
                      fontWeight="fontWeightSemiBold"
                      sx={{
                        color: ({ palette }) =>
                          palette.new.text.neutral.default,
                      }}
                    >
                      {[item.employeeFirstName, item.employeeLastName]
                        .filter(Boolean)
                        .join(' ') ||
                        item.employeeName ||
                        '—'}
                    </Typography>
                    {item.employeeInternalId && (
                      <Typography
                        variant="globalXS"
                        sx={{
                          color: ({ palette }) =>
                            palette.new.text.neutral.lighter,
                        }}
                      >
                        {item.employeeInternalId}
                      </Typography>
                    )}
                  </Stack>
                </HuTableCell>

                <HuTableCell>
                  <CategoryBadge category={item.category} />
                </HuTableCell>

                <HuTableCell>
                  <AssociatedRequestCell
                    actions={item.actionsSummary}
                    t={t}
                  />
                </HuTableCell>

                <HuTableCell>
                  <TicketStatusCell actions={item.actionsSummary} />
                </HuTableCell>
              </HuTableRow>
            ))}

          {isFetchingNextPage && <SkeletonRows cols={COLUMN_KEYS.length} />}
        </HuTableBody>
      </HuTable>
    </HuTableContainer>
  );
}
