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

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 Quote = ({
  itemList = [],
  project = {},
  billingDetails = {},

  quoteNumber = "-",
  creationTimestamp = new Date(),

  appConfig = {},

  frequentlyAskedQuestion = [],
  planning = [],

  paymentTerms = "",
}) => {
  const { summary = "" } = project;
  const { dailyRate = {}, company } = appConfig;

  const dailyRateEuro = dailyRate?.amount || 500;

  const TVA_RATE = 0.2;
  const sousTotalHT = itemList.reduce(
    (sum, phase) => sum + phase.totalNumberOfDay * dailyRateEuro,
    0
  );
  const tva = sousTotalHT * TVA_RATE;
  const montantTotalTTC = sousTotalHT + tva;

  const sections = [
    {
      title: `Devis n°${quoteNumber}`,
      content: <RenderCompanyLogo logoBase64={company?.logoBase64} />,
    },
    {
      title: null,
      content: (
        <View style={Styles.headerRow}>
          <View style={Styles.leftColumn}>
            <Text style={Styles.textParagraph}>
              Date d'émission:{" "}
              {moment(creationTimestamp)
                .tz("Europe/Paris")
                .format("DD/MM/YYYY à HH:mm")}
              {"\n"}
              Période de validité: 60 jours
            </Text>
          </View>

          {Object.keys(billingDetails).length > 0 && (
            <DisplayCustomerInformation billingDetails={billingDetails} />
          )}
        </View>
      ),
    },
    {
      title: "Résumé du Projet",
      content: <Text style={Styles.textParagraph}>{summary}</Text>,
      condition: summary.length > 0,
    },
    {
      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((phase, index) => (
            <View key={index} style={Styles.tableRow}>
              <View>
                <Text style={Styles.tableColLeft}>{phase.title}</Text>
                <Text style={Styles.tableColLeft}>{phase.description}</Text>
                <Text style={Styles.tableColLeft}>
                  Nombre de jours: {phase?.totalNumberOfDay || 0}
                </Text>
              </View>
              <Text style={Styles.tableColRight}>
                {formatPrice({
                  amount: phase.totalNumberOfDay * dailyRateEuro,
                })}
              </Text>
            </View>
          ))}
          <View style={Styles.summaryRow}>
            <Text style={Styles.summaryLabel}>Sous-total HT :</Text>
            <Text style={Styles.summaryValue}>
              {formatPrice({ amount: sousTotalHT })}
            </Text>
          </View>
          <View style={Styles.summaryRow}>
            <Text style={Styles.summaryLabel}>TVA (20%) :</Text>
            <Text style={Styles.summaryValue}>
              {formatPrice({ amount: tva })}
            </Text>
          </View>
          <View style={Styles.summaryRow}>
            <Text style={Styles.summaryLabel}>Total TTC :</Text>
            <Text style={Styles.summaryValue}>
              {formatPrice({ amount: montantTotalTTC })}
            </Text>
          </View>
        </View>
      ),
      condition: itemList.length > 0,
    },
    RenderCompanyInformation({ company }),
    {
      title: "Modalités de paiement",
      content: (
        <Text style={Styles.textParagraph}>
          {paymentTerms ||
            "Acompte de 40% à la signature du devis, 30% après livraison du design et solde à la livraison."}
        </Text>
      ),
    },
    {
      title: "Questions fréquentes",
      content: (
        <View>
          {frequentlyAskedQuestion.map((faq, index) => (
            <View key={index}>
              <Text style={Styles.textParagraph}>{faq.question}</Text>
              <Text style={{ ...Styles.textParagraph, opacity: 0.5 }}>
                {faq.answer}
              </Text>
            </View>
          ))}
        </View>
      ),
      condition: frequentlyAskedQuestion.length > 0,
    },
    {
      title: "Planning prévisionnel",
      content: (
        <View>
          <Text style={Styles.textParagraph}>
            Planning estimatif des semaines de travail, sujet à modification et
            ajustement périodique.
          </Text>

          {planning.map((event, index) => (
            <View key={index}>
              <Text style={Styles.textParagraph}>
                {`${event?.weekNumberStart} - ${event?.weekNumberEnd}: ${event.title}`}
              </Text>
              <Text style={{ ...Styles.textParagraph, opacity: 0.5 }}>
                {event.description}
              </Text>
            </View>
          ))}
        </View>
      ),
      condition: planning.length > 0,
    },
    RenderTermsOfSale(),
    SignatureForm(),
  ].filter(({ condition = true }) => condition);

  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>
  );
};

export default Quote;
