import React from 'react';
import { useDispatch } from 'react-redux';
import { useParams, useNavigate } from 'react-router';
import { DateDisplay } from '@tamanu/ui-components';
import { useEncounter } from '../contexts/Encounter';
import { useAuth } from '../contexts/Auth';
import { LocationCell, LocationGroupCell } from './LocationCell';
import { TriageWaitTimeCell } from './TriageWaitTimeCell';
import { reloadPatient } from '../store';
import { TranslatedReferenceData, TranslatedSex, TranslatedText } from './Translation';
import { DataFetchingTableWithPermissionCheck } from './Table/DataFetchingTable';
import { useSettings } from '../contexts/Settings';
import { LimitedLinesCell } from './FormattedTableCell';

const ADMITTED_PRIORITY_COLOR = '#888888';

// Give the wait time column more room; with the table's auto layout the other
// columns shrink to fit rather than the table overflowing horizontally
const WAIT_TIME_COLUMN_STYLE = `
  .MuiTableCell-head:first-child {
    width: 150px;
  }
`;

const useColumns = () => {
  const { getSetting } = useSettings();
  const triageCategories = getSetting('triageCategories');

  return [
    {
      key: 'arrivalTime',
      title: (
        <TranslatedText
          stringId="patientList.triage.table.column.waitTime"
          fallback="Wait time"
          data-testid="translatedtext-xy39"
        />
      ),
      // Cell color cannot be set on the component due to the way table cells are configured so the
      // cell color must be calculated and set in the table config separately
      cellColor: ({ score, encounterType }) => {
        switch (encounterType) {
          case 'triage':
            return triageCategories.find(c => c.level === parseInt(score))?.color;
          default:
            return ADMITTED_PRIORITY_COLOR;
        }
      },
      accessor: TriageWaitTimeCell,
      isExportable: false,
    },
    {
      key: 'chiefComplaint',
      title: (
        <TranslatedText
          stringId="patientList.triage.table.column.chiefComplaint"
          fallback="Chief complaint"
          data-testid="translatedtext-ziou"
        />
      ),
      accessor: row => (
        <TranslatedReferenceData
          value={row.chiefComplaintId}
          fallback={row.chiefComplaint}
          category="triageReason"
          data-testid="translatedreferencedata-4x0j"
        />
      ),
    },
    {
      key: 'displayId',
      title: (
        <TranslatedText
          stringId="patientList.triage.search.patientId.label"
          fallback="Patient ID"
          data-testid="translatedtext-1wg9"
        />
      ),
    },
    {
      key: 'patientName',
      title: (
        <TranslatedText
          stringId="general.patientName.label"
          fallback="Patient name"
          data-testid="translatedtext-h868"
        />
      ),
      accessor: row => `${row.firstName} ${row.lastName}`,
    },
    {
      key: 'dateOfBirth',
      title: (
        <TranslatedText
          stringId="general.localisedField.dateOfBirth.label.short"
          fallback="DOB"
          data-testid="translatedtext-daoi"
        />
      ),
      accessor: row => <DateDisplay date={row.dateOfBirth} data-testid="datedisplay-gy0v" />,
    },
    {
      key: 'sex',
      title: (
        <TranslatedText
          stringId="general.localisedField.sex.label"
          fallback="Sex"
          data-testid="translatedtext-qa0c"
        />
      ),
      accessor: ({ sex }) => {
        if (!sex) return null;
        return <TranslatedSex sex={sex} short data-testid="translatedsex-triage" />;
      },
    },
    {
      key: 'clinician',
      title: (
        <TranslatedText
          stringId="general.localisedField.clinician.label.short"
          fallback="Clinician"
          data-testid="translatedtext-clinician-column"
        />
      ),
      CellComponent: props => (
        <LimitedLinesCell
          {...props}
          isOneLine
          maxWidth="100px"
          data-testid="limitedlinescell-clinician"
        />
      ),
    },
    {
      key: 'locationGroupName',
      title: (
        <TranslatedText
          stringId="general.table.column.area"
          fallback="Area"
          data-testid="translatedtext-u3wm"
        />
      ),
      accessor: LocationGroupCell,
    },
    {
      key: 'locationName',
      title: (
        <TranslatedText
          stringId="general.location.label"
          fallback="Location"
          data-testid="translatedtext-2uc7"
        />
      ),
      accessor: LocationCell,
    },
  ];
};

export const TriageTable = React.memo(({ searchParameters = {} }) => {
  const { facilityId } = useAuth();
  const { loadEncounter } = useEncounter();
  const { category } = useParams();
  const dispatch = useDispatch();
  const columns = useColumns();
  const navigate = useNavigate();

  const viewEncounter = async triage => {
    await dispatch(reloadPatient(triage.patientId));
    await loadEncounter(triage.encounterId);
    navigate(`/patients/${category}/${triage.patientId}/encounter/${triage.encounterId}`);
  };

  return (
    <DataFetchingTableWithPermissionCheck
      verb="list"
      noun="Triage"
      endpoint="triage"
      fetchOptions={{ facilityId, ...searchParameters }}
      columns={columns}
      headStyle={WAIT_TIME_COLUMN_STYLE}
      noDataMessage={
        <TranslatedText
          stringId="patientList.table.noData"
          fallback="No patients found"
          data-testid="translatedtext-vbj4"
        />
      }
      onRowClick={viewEncounter}
      data-testid="datafetchingtablewithpermissioncheck-7800"
    />
  );
});
