import { useNavigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { appearFromBottom } from '@material-hu/utils/animations';

import FileIcon from '@material-hu/components/composed-components/files/FileIcon';
import Checkbox from '@material-hu/components/design-system/Checkbox/Checkbox';
import Pills from '@material-hu/components/design-system/Pills';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';
import TableRow from '@material-hu/components/design-system/Table/components/TableRow';

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

import { agentsRoutes } from '../../../routes';
import {
  KNOWLEDGE_BASE_STATUS_KEY,
  KNOWLEDGE_BASE_STATUS_PILL_TYPE,
} from '../../constants';
import { type KnowledgeBaseItem, KnowledgeBaseItemType } from '../../types';

import KnowledgeBaseRowMenu from './KnowledgeBaseRowMenu';

type KnowledgeBaseTableRowProps = {
  item: KnowledgeBaseItem;
  selected: boolean;
  onItemSelect: (path: string, checked: boolean) => void;
  onOpenFile: (item: KnowledgeBaseItem) => void;
  clearApplies: () => void;
};

const KnowledgeBaseTableRow = ({
  item,
  selected,
  onItemSelect,
  onOpenFile,
  clearApplies,
}: KnowledgeBaseTableRowProps) => {
  const { t } = useLokaliseTranslation(['agents']);
  const navigate = useNavigate();
  const isFolder = item.type === KnowledgeBaseItemType.FOLDER;

  const handleFolderClick = (folderItemPath: string) => {
    clearApplies();
    navigate(
      agentsRoutes.knowledgeBase.folder(encodeURIComponent(folderItemPath)),
    );
  };

  const fileToIcon = {
    type: item.type,
    extension: item.extension,
  };

  const handleOpenFile = (item: KnowledgeBaseItem) => {
    if (isFolder) handleFolderClick(item.path);
    else onOpenFile(item);
  };

  const isAllAudience =
    item.segmentationTags.length === 0 && item.segmentationUserIds.length === 0;

  return (
    <TableRow
      sx={{
        animation: `${appearFromBottom} 300ms ease-in-out`,
        ...(selected && {
          backgroundColor: ({ palette }) => palette.new.background.layout.brand,
          '&:hover': {
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.brand,
          },
        }),
      }}
    >
      <TableCell
        sx={{
          width: 48,
          borderRight: ({ palette }) =>
            `4px solid ${palette.new.border.neutral.default}`,
        }}
      >
        <Checkbox
          checked={selected}
          disabled={isFolder}
          onChange={e => onItemSelect(item.path, e.target.checked)}
          sx={{ mx: 1 }}
        />
      </TableCell>

      <TableCell sx={{ minWidth: 250 }}>
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 1,
            cursor: 'pointer',
          }}
          onClick={() => handleOpenFile(item)}
        >
          <FileIcon file={fileToIcon} />

          <Typography
            sx={{ fontWeight: 'fontWeightSemiBold' }}
            variant="globalS"
          >
            {item.name}
          </Typography>
        </Stack>
      </TableCell>

      <TableCell>{item.uploadedBy?.fullName ?? '—'}</TableCell>

      <TableCell>{item.updatedAt}</TableCell>

      <TableCell>{item.size ?? '—'}</TableCell>

      <TableCell>
        {isFolder && '—'}
        {!isFolder && (
          <Pills
            label={
              isAllAudience
                ? t('general:all')
                : t('knowledge_base.table.segmented')
            }
            type={isAllAudience ? 'neutral' : 'highlight'}
            size="small"
            hasIcon={false}
          />
        )}
      </TableCell>

      <TableCell>
        {!item.status && '—'}
        {item.status && (
          <Pills
            label={t(KNOWLEDGE_BASE_STATUS_KEY[item.status])}
            type={KNOWLEDGE_BASE_STATUS_PILL_TYPE[item.status]}
            size="small"
            hasIcon={false}
          />
        )}
      </TableCell>

      <TableCell sx={{ width: 60 }}>
        <KnowledgeBaseRowMenu item={item} />
      </TableCell>
    </TableRow>
  );
};

export default KnowledgeBaseTableRow;
