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

import { DRUG_ROUTE_LABELS } from '@tamanu/constants';
import { getDrugUnitLabel, getMedicationDoseDisplay, getTranslatedFrequency } from '../medication';
import { Page } from '../pdf/Page';
import { useLanguageContext, withLanguageContext } from '../pdf/languageContext';
import { useDateTime, withDateTimeContext } from '../pdf/withDateTimeContext';
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';

const columns = (getTranslation, getEnumTranslation) => [
  {
    key: 'medication',
    title: getTranslation('pdf.table.column.medication', 'Medication'),
    accessor: ({ medication, notes, indication }) => (
      <View>
        <Text>{medication?.name}</Text>
        {notes && <Text style={{ fontFamily: 'Helvetica-Oblique' }}>{`\n${notes}`}</Text>}
        {indication && (
          <>
            <Text style={{ fontFamily: 'Helvetica-Bold' }}>
              {`\n${getTranslation('medication.indication.label', 'Indication')}:`}
            </Text>
            <Text>{` ${indication}`}</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, dispensingUnit }) => {
      if (!quantity) return '';
      if (!dispensingUnit) return `${quantity}`;
      return `${quantity} ${getDrugUnitLabel(dispensingUnit, quantity, getEnumTranslation)}`;
    },
  },
  {
    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),
);
