import { useEffect, useMemo, useState } from 'react';
import { Page, View, Text, Font, Image, Document, StyleSheet } from '@react-pdf/renderer';

import { fDate } from '@/utils/format-time';
import { fCurrency } from '@/utils/format-number';

import { IInvoice, IInvoiceItem } from '@/shared/types/invoice';
import { downloadSignature, getGroupWithAddress } from '@/shared/api/invoice';
import { getUserByEmail, getUserById } from '@/shared/api/user';

// ----------------------------------------------------------------------

Font.register({
  family: 'Roboto',
  fonts: [{ src: '/fonts/Roboto-Regular.ttf' }, { src: '/fonts/Roboto-Bold.ttf' }],
});

const useStyles = () =>
  useMemo(
    () =>
      StyleSheet.create({
        col4: { width: '25%' },
        col8: { width: '75%' },
        col6: { width: '50%' },
        mb4: { marginBottom: 4 },
        mb8: { marginBottom: 8 },
        mb40: { marginBottom: 40 },
        h3: { fontSize: 16, fontWeight: 700 },
        h4: { fontSize: 13, fontWeight: 700 },
        body1: { fontSize: 10 },
        body2: { fontSize: 9 },
        subtitle1: { fontSize: 10, fontWeight: 700 },
        subtitle2: { fontSize: 9, fontWeight: 700 },
        alignRight: { textAlign: 'right' },
        page: {
          fontSize: 9,
          lineHeight: 1.6,
          fontFamily: 'Roboto',
          backgroundColor: '#FFFFFF',
          textTransform: 'capitalize',
          padding: '40px 24px 120px 24px',
        },
        footer: {
          left: 0,
          right: 0,
          bottom: 0,
          padding: 24,
          margin: 'auto',
          borderTopWidth: 1,
          borderStyle: 'solid',
          position: 'absolute',
          borderColor: '#DFE3E8',
        },
        gridContainer: {
          flexDirection: 'row',
          justifyContent: 'space-between',
        },
        table: {
          display: 'flex',
          width: 'auto',
        },
        tableRow: {
          padding: '8px 0',
          flexDirection: 'row',
          borderBottomWidth: 1,
          borderStyle: 'solid',
          borderColor: '#DFE3E8',
        },
        noBorder: {
          paddingTop: 8,
          paddingBottom: 0,
          borderBottomWidth: 0,
        },
        tableCell_1: {
          width: '5%',
        },
        tableCell_2: {
          width: '50%',
          paddingRight: 16,
        },
        tableCell_3: {
          width: '15%',
        },
      }),
    []
  );

// ----------------------------------------------------------------------

type Props = {
  invoice: IInvoice;
  currentStatus: string;
};

export default function InvoicePDF({ invoice, currentStatus }: Props) {
  const [signatureImageUrl, setSignatureImageUrl] = useState<string | null>(null);
  const [managerInfo, setManagerInfo] = useState<any>(null);
  const [loadingManager, setLoadingManager] = useState(true);
  if (!invoice) {
  
    return <div>Aucune facture trouvée</div>;
  }
  const {
    taxes,
    dueDate,
    invoiceClient,
    createDate,
    totalAmount,
    invoiceIssuer,
    invoiceNumber,
    subTotal,
    notes,
  } = invoice;
  
  useEffect(() => {
    const fetchSignature = async () => {
      if (invoice.signatureUrl) {
        try {
          const signatureUrl = await downloadSignature(invoice.signatureUrl);
          setSignatureImageUrl(signatureUrl);
        } catch (error) {
          console.error('Erreur lors du téléchargement de la signature:', error);
        }
      }
    };

    fetchSignature();

   
    return () => {
      if (signatureImageUrl) {
        URL.revokeObjectURL(signatureImageUrl);
      }
    };
  }, [invoice.signatureUrl]);
  const styles = useStyles();
  useEffect(() => {
    const fetchManagerInfo = async () => {
      if (invoice.responsibleId === undefined) {
        setLoadingManager(false);
        return;
      }

      setLoadingManager(true);
      
      try {
        const userData = await getUserById(invoice.responsibleId);
        let managerInfoData;

        if (userData.group?.id) {
          const groupData = await getGroupWithAddress(userData.group.id);
          managerInfoData = {
            name: groupData.name,
            email: groupData.email,
            phoneNumber: groupData.phoneNumber,
            address: formatAddress(groupData)
          };
        } else {
          managerInfoData = {
            name: `${userData.firstName} ${userData.lastName}`,
            email: userData.email,
            phoneNumber: userData.phoneNumber,
            address: formatAddress(userData.address)
          };
        }

        setManagerInfo(managerInfoData);
      } catch (error) {
        console.error('Error fetching manager info:', error);
       
      } finally {
        setLoadingManager(false);
      }
    };

    fetchManagerInfo();
  }, [invoice.responsibleId]);

  const formatAddress = (addressData: any) => {
    if (!addressData) return 'Adresse non disponible';
    return `${addressData.primaryAddresse || ''}, ${addressData.optionalAddress || ''}, ${addressData.postalCode || ''} ${addressData.city || ''}, ${addressData.country || ''}`.trim();
  };

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        <View style={[styles.gridContainer, styles.mb40]}>
          <Image source="/logo/logo_stunar.png" style={{ width: 48, height: 48 }} />

          <View style={{ alignItems: 'flex-end', flexDirection: 'column' }}>
            <Text style={styles.h3}>{currentStatus}</Text>
            <Text> {invoiceNumber} </Text>
          </View>
        </View>

        <View style={[styles.gridContainer, styles.mb40]}>
     
          <View style={styles.col6}>
            <Text style={[styles.subtitle2, styles.mb4]}>Invoice from</Text>
            {loadingManager ? (
              <Text style={styles.body2}>Loading...</Text>
            ) : managerInfo ? (
              <>
                <Text style={styles.body2}>{managerInfo.name}</Text>
                <Text style={styles.body2}>{managerInfo.email}</Text>
                <Text style={styles.body2}>{managerInfo.phoneNumber}</Text>
                <Text style={styles.body2}>{managerInfo.address}</Text>
              </>
            ) : (
              <Text style={styles.body2}>No manager information available</Text>
            )}
          </View>

          <View style={styles.col6}>
            <Text style={[styles.subtitle2, styles.mb4]}>Invoice to</Text>
            <Text style={styles.body2}>{invoiceClient.company}</Text>
            <Text style={styles.body2}>{invoiceClient.apartement} {invoiceClient.street} - {invoiceClient.city}/{invoiceClient.postalCode}, {invoiceClient.country}</Text>
            <Text style={styles.body2}>{invoiceClient.phoneNumber}</Text>
          </View>
        </View>

        <View style={[styles.gridContainer, styles.mb40]}>
          <View style={styles.col6}>
            <Text style={[styles.subtitle2, styles.mb4]}>Date create</Text>
            <Text style={styles.body2}>{fDate(createDate)}</Text>
          </View>
          <View style={styles.col6}>
            <Text style={[styles.subtitle2, styles.mb4]}>Due date</Text>
            <Text style={styles.body2}>{fDate(dueDate)}</Text>
          </View>
        </View>

        <Text style={[styles.subtitle1, styles.mb8]}>Invoice Details</Text>

        <View style={styles.table}>
          <View>
            <View style={styles.tableRow}>
              <View style={styles.tableCell_1}>
                <Text style={styles.subtitle2}>#</Text>
              </View>

              <View style={styles.tableCell_2}>
                <Text style={styles.subtitle2}>Description</Text>
              </View>

              <View style={styles.tableCell_3}>
                <Text style={styles.subtitle2}>Qty</Text>
              </View>

              <View style={styles.tableCell_3}>
                <Text style={styles.subtitle2}>Unit price</Text>
              </View>

              <View style={[styles.tableCell_3, styles.alignRight]}>
                <Text style={styles.subtitle2}>Total</Text>
              </View>
            </View>
          </View>

          <View>
            {invoice.productLine.map((item, index) => (
              <View style={styles.tableRow} key={item.id}>
                <View style={styles.tableCell_1}>
                  <Text>{index + 1}</Text>
                </View>

                <View style={styles.tableCell_2}>
                  <Text style={styles.subtitle2}>{item.title}</Text>
                  <Text>{item.description}</Text>
                </View>

                <View style={styles.tableCell_3}>
                  <Text>{item.quantity}</Text>
                </View>

                <View style={styles.tableCell_3}>
                  <Text>{item.price}</Text>
                </View>

                <View style={[styles.tableCell_3, styles.alignRight]}>
                  <Text>{fCurrency(item.price * item.quantity)}</Text>
                </View>
              </View>
            ))}

            <View style={[styles.tableRow, styles.noBorder]}>
              <View style={styles.tableCell_1} />
              <View style={styles.tableCell_2} />
              <View style={styles.tableCell_3} />
              <View style={styles.tableCell_3}>
                <Text>Subtotal</Text>
              </View>
              <View style={[styles.tableCell_3, styles.alignRight]}>
                <Text>{fCurrency(subTotal)}</Text>
              </View>
            </View>

            <View style={[styles.tableRow, styles.noBorder]}>
              <View style={styles.tableCell_1} />
              <View style={styles.tableCell_2} />
              <View style={styles.tableCell_3} />
              <View style={styles.tableCell_3}>
                <Text>Taxes</Text>
              </View>
              <View style={[styles.tableCell_3, styles.alignRight]}>
                <Text>{fCurrency(taxes)}</Text>
              </View>
            </View>

            <View style={[styles.tableRow, styles.noBorder]}>
              <View style={styles.tableCell_1} />
              <View style={styles.tableCell_2} />
              <View style={styles.tableCell_3} />
              <View style={styles.tableCell_3}>
                <Text style={styles.h4}>Total</Text>
              </View>
              <View style={[styles.tableCell_3, styles.alignRight]}>
                <Text style={styles.h4}>{fCurrency(totalAmount)}</Text>
              </View>
            </View>
          </View>
        </View>

        <View style={[styles.gridContainer, styles.footer]} fixed>
          <View style={styles.col8}>
          </View>
        </View>
        <View style={[styles.gridContainer, styles.mb40, { marginTop: 40 }]}>
          <View style={styles.col8}>
            <Text style={[styles.subtitle2, styles.mb4]}>Notes</Text>
            <Text style={styles.body2}>{notes}</Text>
          </View>
          <View style={[styles.col4, { alignItems: 'flex-end' }]}>
            <Text style={[styles.subtitle2, styles.mb4]}>Signature</Text>
            {signatureImageUrl ? (
              <Image source={signatureImageUrl} style={{ width: 120, height: 'auto' }} />
            ) : (
              <Text style={styles.body2}>No signature available</Text>
            )}
          </View>
        </View>

        <View style={[styles.gridContainer, styles.footer]} fixed>
          <View style={styles.col8}>
            <Text style={styles.body2}>
              Thank you for your business
            </Text>
          </View>
          <View style={[styles.col4, styles.alignRight]}>
            <Text style={styles.body2}>Page 1 of 1</Text>
          </View>
        </View>
      </Page>
    </Document>
  );
}



// ----------------------------------------------------------------------
