import React from 'react';

import { Document, StyleSheet, Text, View } from '@react-pdf/renderer';

import { DRUG_ROUTE_LABELS } from '@tamanu/constants';

import { CertificateContent, CertificateHeader, Col, Signature, styles } from './Layout';
import { LetterheadSection } from './LetterheadSection';
import { Table } from './Table';
import { DataItem } from './printComponents/DataItem';
import { DataSection } from './printComponents/DataSection';
import { Footer } from './printComponents/Footer';
import { PatientDetailsWithBarcode } from './printComponents/PatientDetailsWithBarcode';
import { Page } from '../pdf/Page';
import { useLanguageContext, withLanguageContext } from '../pdf/languageContext';
import { useDateTime, withDateTimeContext } from '../pdf/withDateTimeContext';
import { getMedicationDoseDisplay, getTranslatedFrequency } from '../medication';

const columns = (getTranslation, getEnumTranslation) => [
  {
    key: 'medication',
    title: getTranslation('pdf.table.column.medication', 'Medication'),
    accessor: ({ medication, notes, indication }) => (
      <View>
        <Text style={{ marginBottom: 4 }}>{medication?.name}</Text>
        {notes && (
          <Text style={{ fontFamily: 'Helvetica-Oblique', marginBottom: 4 }}>{notes}</Text>
        )}
        {indication && (
          <Text>
            <Text style={{ fontFamily: 'Helvetica-Bold' }}>
              {getTranslation('medication.indication.label', 'Indication')}:
            </Text>
            <Text>{` ${indication}`}</Text>
          </Text>
        )}
      </View>
    ),
    customStyles: { minWidth: 180 },
  },
  {
    key: 'dose',
    title: getTranslation('pdf.table.column.dose', 'Dose'),
    accessor: (medication) => {
      return (
        <Text>
          {getMedicationDoseDisplay(medication, getTranslation, getEnumTranslation)}
          {medication?.isPrn && ` ${getTranslation('medication.table.prn', 'PRN')}`}
        </Text>
      );
    },
  },
  {
    key: 'frequency',
    title: getTranslation('pdf.table.column.frequency', 'Frequency'),
    accessor: ({ frequency }) => getTranslatedFrequency(frequency, getTranslation),
    customStyles: { minWidth: 30 },
  },
  {
    key: 'route',
    title: getTranslation('pdf.table.column.route', 'Route'),
    accessor: ({ route }) => getEnumTranslation(DRUG_ROUTE_LABELS, route),
  },
  {
    key: 'quantity',
    title: getTranslation('pdf.table.column.quantity', 'Quantity'),
    accessor: ({ quantity }) => quantity,
  },
  {
    key: 'repeats',
    title: getTranslation('pdf.table.column.repeats', 'Repeats'),
    accessor: ({ repeats }) => repeats,
  },
];

const prescriptionSectionStyles = StyleSheet.create({
  tableContainer: {
    marginTop: 12,
  },
});

const signingSectionStyles = StyleSheet.create({
  container: {
    marginTop: 22,
  },
});

const generalStyles = StyleSheet.create({
  container: {
    marginVertical: 8,
  },
});

const SectionContainer = (props) => <View style={generalStyles.container} {...props} />;

const PrescriptionsSection = ({
  prescriptions,
  prescriber,
  facility,
  getSetting,
}) => {
  const { getTranslation, getEnumTranslation } = useLanguageContext();
  const { formatShort, getCurrentDate } = useDateTime();
  return (
    <View>
      <DataSection hideBottomRule title="Prescription details">
        <Col>
          <DataItem label="Date" value={formatShort(getCurrentDate())} />
          <DataItem label="Prescriber" value={prescriber?.displayName} />
        </Col>
        <Col>
          <DataItem label="Prescriber ID" value={prescriber?.displayId ?? 'n/a'} />
          <DataItem label="Facility" value={facility?.name} />
        </Col>
      </DataSection>
      <View style={prescriptionSectionStyles.tableContainer}>
        <Table
          columns={columns(getTranslation, getEnumTranslation)}
          data={prescriptions}
          getSetting={getSetting}
          columnStyle={{ padding: '8px 7px' }}
        />
      </View>
    </View>
  );
};

const PrescriptionSigningSection = () => (
  <View style={signingSectionStyles.container}>
    <Signature fontSize={9} lineThickness={0.5} text="Signed" />
    <Signature fontSize={9} lineThickness={0.5} text="Date" />
  </View>
);

const PrescriptionPrintoutComponent = ({
  patientData,
  prescriptions,
  prescriber,
  certificateData,
  facility,
  getSetting,
}) => {
  return (
    <Document>
      <Page size="A4" style={[styles.page, { paddingBottom: '50' }]}>
        <CertificateHeader>
          <LetterheadSection
            letterheadConfig={certificateData}
            logoSrc={certificateData.logo}
            certificateTitle="Prescription"
          />
          <SectionContainer>
            <PatientDetailsWithBarcode patient={patientData} getSetting={getSetting} />
          </SectionContainer>
        </CertificateHeader>
        <CertificateContent style={{ margin: 0 }}>
          <SectionContainer>
            <PrescriptionsSection
              prescriptions={prescriptions}
              prescriber={prescriber}
              facility={facility}
              getSetting={getSetting}
            />
          </SectionContainer>
          <SectionContainer>
            <PrescriptionSigningSection />
          </SectionContainer>
        </CertificateContent>
        <Footer style={{ left: 30, right: 30 }} />
      </Page>
    </Document>
  );
};

export const PrescriptionPrintout = withLanguageContext(
  withDateTimeContext(PrescriptionPrintoutComponent),
);
