import React from "react";
import { Document, Page, Text, View, Font, Image } from "@react-pdf/renderer";
import moment from "moment-timezone";
import {
  DisplayCustomerInformation,
  formatPrice,
  RenderCompanyLogo,
  RenderTermsOfSale,
  Styles,
} from "./SharedElements";

Font.register({
  family: "Helvetica",
  fonts: [
    { src: "https://fonts.gstatic.com/s/helvetica/v15/Helvetica-Regular.ttf" },
    {
      src: "https://fonts.gstatic.com/s/helvetica/v15/Helvetica-Bold.ttf",
      fontWeight: "bold",
    },
  ],
});

const Invoice = ({
  itemList = [],
  billingDetails = {},

  number = "-",

  paymentTimestamp = null,
  creationTimestamp = new Date().toLocaleDateString("fr-FR"),

  appConfig = {},
}) => {
  const { company } = appConfig;

  const subTotalNoTax = itemList.reduce(
    (sum, item) => sum + (item?.unitPrice || 0) * (item?.quantity || 0),
    0
  );

  let taxList = {};

  itemList.forEach((item) => {
    const { taxBreakdown = [] } = item;
    taxBreakdown.forEach((tax) => {
      const { type, amount, displayName, percentageDecimal = null } = tax;
      if (type) {
        taxList[type] = {
          displayName,
          percentageDecimal,
          amount: (taxList?.[type]?.amount || 0) + amount,
        };
      }
    });
  });

  const montantTotalTTC =
    subTotalNoTax +
    Object.values(taxList).reduce((sum, tax) => sum + tax.amount, 0);

  const taxExemptionLegalString = "";

  const sections = [
    {
      title: `Facture n°${number}`,
      content: <RenderCompanyLogo logoBase64={company?.logoBase64} />,
    },
    {
      title: null,
      content: (
        <View style={Styles.headerRow}>
          <View style={Styles.leftColumn}>
            {[
              `Date d'émission: ${moment(creationTimestamp)
                .tz("Europe/Paris")
                .format("DD/MM/YYYY à HH:mm")}`,
              paymentTimestamp
                ? `Date de paiement: ${moment(paymentTimestamp)
                    .tz("Europe/Paris")
                    .format("DD/MM/YYYY à HH:mm")}`
                : null,
              "Statut: payée",
            ]
              .filter(Boolean)
              .map((line, index) => (
                <Text key={index} style={Styles.textParagraph}>
                  {line}
                </Text>
              ))}
          </View>

          <DisplayCustomerInformation billingDetails={billingDetails} />
        </View>
      ),
    },
    {
      title: "Détails des prestations",
      content: (
        <View style={Styles.table}>
          <View style={Styles.tableRow}>
            <Text style={Styles.tableColHeaderLeft}>Description</Text>
            <Text style={Styles.tableColHeaderRight}>Prix HT</Text>
          </View>
          {itemList.map((item, index) => (
            <View key={index} style={Styles.tableRow}>
              <View>
                <Text style={Styles.tableColLeft}>{item.description}</Text>
              </View>
              <Text style={Styles.tableColRight}>
                {formatPrice({ amount: item.unitPrice * item.quantity })}
              </Text>
            </View>
          ))}
          <View style={Styles.summaryRow}>
            <Text style={Styles.summaryLabel}>Sous-total HT :</Text>
            <Text style={Styles.summaryValue}>
              {formatPrice({ amount: subTotalNoTax })}
            </Text>
          </View>
          {Object.values(taxList)?.map((itemTax, index) => (
            <View key={index} style={Styles.summaryRow}>
              <Text style={Styles.summaryLabel}>
                {itemTax?.displayName}{" "}
                {itemTax?.percentageDecimal
                  ? `(${itemTax?.percentageDecimal}%)`
                  : ""}{" "}
                :
              </Text>
              <Text style={Styles.summaryValue}>
                {formatPrice({ amount: itemTax.amount })}
              </Text>
            </View>
          ))}
          <View style={Styles.summaryRow}>
            <Text style={Styles.summaryLabel}>Total TTC :</Text>
            <Text style={Styles.summaryValue}>
              {formatPrice({ amount: montantTotalTTC })}
            </Text>
          </View>
        </View>
      ),
    },
    {
      title: "Mentions légales",
      content: (
        <Text style={Styles.textParagraph}>
          {`En cas de retard de paiement, une pénalité de 3 fois le taux d'intérêt légal sera appliquée, à laquelle s'ajoutera une indemnité forfaitaire pour frais de recouvrement de 40€. ${taxExemptionLegalString}`}
        </Text>
      ),
    },
    RenderTermsOfSale(),
  ].filter(({ content }) => content);

  return (
    <Document>
      <Page style={Styles.body}>
        {sections.map((section, index) => (
          <View key={index} style={Styles.section}>
            {section.title && (
              <Text style={Styles.sectionTitle}>{section.title}</Text>
            )}
            {section.content}
          </View>
        ))}
      </Page>
    </Document>
  );
};

// Liste des taux de TVA standard pour les pays de l'UE
const euVatRates = {
  AT: 0.2, // Autriche
  BE: 0.21, // Belgique
  BG: 0.2, // Bulgarie
  HR: 0.25, // Croatie
  CY: 0.19, // Chypre
  CZ: 0.21, // République tchèque
  DK: 0.25, // Danemark
  EE: 0.2, // Estonie
  FI: 0.24, // Finlande
  FR: 0.2, // France
  DE: 0.19, // Allemagne
  GR: 0.24, // Grèce
  HU: 0.27, // Hongrie
  IE: 0.23, // Irlande
  IT: 0.22, // Italie
  LV: 0.21, // Lettonie
  LT: 0.21, // Lituanie
  LU: 0.17, // Luxembourg
  MT: 0.18, // Malte
  NL: 0.21, // Pays-Bas
  PL: 0.23, // Pologne
  PT: 0.23, // Portugal
  RO: 0.19, // Roumanie
  SK: 0.2, // Slovaquie
  SI: 0.22, // Slovénie
  ES: 0.21, // Espagne
  SE: 0.25, // Suède
};

// Fonction pour vérifier si le pays fait partie de l'UE
function isCustomerFromEurope({ countryCode }) {
  return euVatRates.hasOwnProperty(countryCode);
}

export default Invoice;
