import { Box } from '@material-ui/core';
import React, { useState } from 'react';
import styled from 'styled-components';

import { DRUG_ROUTE_LABELS } from '@tamanu/constants';
import {
  findAdministrationTimeSlotFromIdealTime,
  getDateFromTimeString,
  getMedicationDoseDisplay,
  getTranslatedFrequency,
} from '@tamanu/shared/utils/medication';
import {
  DateDisplay,
  TranslatedReferenceData,
  TranslatedText,
  useDateTime,
  useTranslation,
} from '@tamanu/ui-components';
import { Colors } from '../../../constants/styles';
import { getDisplayedPharmacyNote } from '../../../utils/medications';
import { ChangeLogModal } from './ChangeLogModal';
import { PrescriptionChangeHistoryModal } from '../PrescriptionChangeHistoryModal';

const Container = styled.div`
  padding: 12px 16px;
  background-color: ${Colors.white};
  border: 1px solid ${Colors.outline};
  border-radius: 3px;
  font-size: 14px;
  color: ${Colors.darkestText};
`;

const Value = styled.div`
  font-size: 14px;
  font-weight: 500;
  color: ${Colors.darkestText};
`;

const Label = styled(Value)`
  font-weight: 400;
  color: ${Colors.midText};
  margin-bottom: 3px;
`;

const Separator = styled.hr`
  margin-block: 6px 16px;
`;

const DateTimeContainer = styled.div`
  display: flex;
  align-items: stretch;
`;

const ChangeLogLink = styled.a`
  color: ${Colors.primary};
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  height: fit-content;

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

const MedicationInfoContainer = styled.div`
  display: flex;
  justify-content: space-between;
`;

const VerticalDivider = styled.div`
  width: 1px;
  background-color: ${Colors.outline};
  margin: 0 20px;
`;

const LowerText = styled.span`
  text-transform: lowercase;
`;

export const MarInfoPane = ({ medication, marInfo }) => {
  const { dueAt, isAutoGenerated } = marInfo;
  const { formatTimeSlot, formatTime, toFacilityDateTime } = useDateTime();

  const [showChangeLogModal, setShowChangeLogModal] = useState(false);
  const [showModifyHistory, setShowModifyHistory] = useState(false);

  // The most recent pharmacy-modified fill for this prescription (null when never modified),
  // provided by the encounter medications endpoint. Its pharmacy note drives the MAR note display
  // via getDisplayedPharmacyNote; kept here for the "View change" link's change-history modal.
  const { latestModifiedDispense } = medication;

  const facilityDueAt = toFacilityDateTime(dueAt);
  const facilityTime = facilityDueAt?.split('T')[1]?.substring(0, 5);
  const { timeSlot } = facilityTime
    ? findAdministrationTimeSlotFromIdealTime(facilityTime)
    : { timeSlot: null };
  const slotStartTime = timeSlot ? getDateFromTimeString(timeSlot.startTime) : null;
  const slotEndTime = timeSlot ? getDateFromTimeString(timeSlot.endTime) : null;

  const { getTranslation, getEnumTranslation } = useTranslation();
  const {
    medication: medicationRef,
    frequency,
    route,
    notes,
  } = medication;

  const { modifiedPharmacyNote, displayedPharmacyNote } = getDisplayedPharmacyNote(medication);

  const onChangeLogClick = () => {
    setShowChangeLogModal(true);
  };

  return (
    <>
      <Container>
        <MedicationInfoContainer>
          <Box flex={0.9}>
            <Box color={Colors.midText} mb="3px">
              <TranslatedText stringId="medication.mar.medication.label" fallback="Medication" />
            </Box>
            <Box fontWeight={500} mb="3px">
              <TranslatedReferenceData
                fallback={medicationRef.name}
                value={medicationRef.id}
                category={medicationRef.type}
              />
            </Box>
            <Box mb="3px">
              {[
                getMedicationDoseDisplay(medication, getTranslation, getEnumTranslation),
                getTranslatedFrequency(frequency, getTranslation),
                getEnumTranslation(DRUG_ROUTE_LABELS, route),
              ]
                .filter(Boolean)
                .join(', ')}
            </Box>
            <Box color={Colors.midText} mb="3px">
              <span>{notes}</span>
              {displayedPharmacyNote && (
                <span>
                  {notes && ', '}
                  <TranslatedText
                    stringId="medication.mar.pharmacyNotes"
                    fallback="Pharmacy note"
                  />
                  : {displayedPharmacyNote}
                  {modifiedPharmacyNote && (
                    <>
                      {' '}
                      <ChangeLogLink as="span" onClick={() => setShowModifyHistory(true)}>
                        <TranslatedText
                          stringId="medication.mar.viewChange"
                          fallback="View change"
                        />
                      </ChangeLogLink>
                    </>
                  )}
                </span>
              )}
            </Box>
          </Box>
          <ChangeLogLink onClick={onChangeLogClick}>
            <TranslatedText stringId="general.action.viewChangeLog" fallback="View change log" />
          </ChangeLogLink>
        </MedicationInfoContainer>
        <Separator />
        <DateTimeContainer>
          <Box flex={1}>
            <Label>
              <TranslatedText stringId="general.date.label" fallback="Date" />
            </Label>
            <Value>
              <DateDisplay date={dueAt} format="long" />
            </Value>
          </Box>
          <VerticalDivider />
          <Box flex={1}>
            <Label>
              <TranslatedText stringId="general.time.label" fallback="Time" />
            </Label>
            <Value>
              {slotStartTime && slotEndTime ? (
                <>
                  <LowerText>{`${formatTimeSlot(slotStartTime)}-${formatTimeSlot(slotEndTime)}`}</LowerText>{' '}
                  <span>
                    (
                    {isAutoGenerated ? (
                      <TranslatedText
                        stringId="modal.mar.view.dueTime"
                        fallback="Due time: :dueAt"
                        replacements={{ dueAt: formatTime(dueAt) }}
                      />
                    ) : (
                      <TranslatedText
                        stringId="modal.mar.view.noDoseScheduled"
                        fallback="No dose scheduled"
                      />
                    )}
                  </span>
                  )
                </>
              ) : (
                <TranslatedText
                  stringId="medication.mar.timeUnavailable"
                  fallback="Time unavailable"
                />
              )}
            </Value>
          </Box>
        </DateTimeContainer>
      </Container>
      {showChangeLogModal && (
        <ChangeLogModal
          open
          onClose={() => setShowChangeLogModal(false)}
          medication={medication}
          marId={marInfo.id}
        />
      )}
      <PrescriptionChangeHistoryModal
        open={showModifyHistory}
        dispenseId={latestModifiedDispense?.id}
        onClose={() => setShowModifyHistory(false)}
      />
    </>
  );
};
