'use client';

import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Font,
  pdf,
} from '@react-pdf/renderer';
import { LogisticPurchasePerSupplierReport } from '@/types/api/report/logistic-stock';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';

Font.register({
  family: 'Helvetica',
  src: 'helvetica',
});

const pdfStyles = StyleSheet.create({
  page: {
    fontSize: 10,
    fontFamily: 'Helvetica',
    padding: 20,
    backgroundColor: '#FFFFFF',
  },
  titleSection: {
    marginBottom: 10,
  },
  mainTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 5,
    color: '#1f74bf',
  },
  supplierTitle: {
    fontSize: 12,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#1f74bf',
  },
  table: {
    borderWidth: 1,
    borderColor: '#000000',
    marginBottom: 15,
  },
  tableRow: {
    flexDirection: 'row',
  },
  tableHeader: {
    backgroundColor: '#F5F5F5',
  },
  tableCell: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'left',
  },
  tableCellNo: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'center',
  },
  tableCellLast: {
    flex: 1,
    padding: 4,
    fontSize: 8,
  },
  tableCellHeader: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
    textAlign: 'center',
  },
  tableCellHeaderRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    textAlign: 'right',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
  },
  tableCellHeaderLast: {
    flex: 1,
    padding: 4,
    fontSize: 8,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
    textAlign: 'center',
  },
  tableCellRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'right',
  },
  tableCellCenter: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'center',
  },
  tableCellCenterLast: {
    flex: 1,
    padding: 4,
    fontSize: 8,
    textAlign: 'center',
  },
  tableBorderBottom: {
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
  },
  supplierSection: {
    marginBottom: 10,
  },
  supplierSectionBreak: {
    marginBottom: 15,
  },
  badge: {
    backgroundColor: '#1f74bf',
    color: '#FFFFFF',
    padding: 2,
    borderRadius: 2,
    fontSize: 7,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginRight: 4,
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
});

interface PurchasesPerSupplierExportParams {
  data: LogisticPurchasePerSupplierReport[];
  params: {
    area_name?: string;
    supplier_name?: string;
    product_name?: string;
    product_category_name?: string;
    received_date?: string;
    po_date?: string;
    start_date?: string;
    end_date?: string;
    sort_by?: string;
    filter_by?: string;
  };
}

const getParameterText = (
  params: PurchasesPerSupplierExportParams['params']
) => {
  const paramsText = [];

  if (params.supplier_name) {
    paramsText.push(`Supplier: ${params.supplier_name}`);
  } else {
    paramsText.push('Semua Supplier');
  }

  if (params.start_date && params.end_date) {
    const startDate = formatDate(params.start_date, 'DD MMM YYYY');
    const endDate = formatDate(params.end_date, 'DD MMM YYYY');
    paramsText.push(`Periode: ${startDate} - ${endDate}`);
  } else if (params.start_date) {
    const startDate = formatDate(params.start_date, 'DD MMM YYYY');
    paramsText.push(`Tanggal: ${startDate}`);
  }

  const currentDate = formatDate(new Date(), 'DD MMM YYYY HH:mm');
  paramsText.push(`Dicetak: ${currentDate}`);

  return paramsText;
};

const createPDFDocument = (
  supplierReports: LogisticPurchasePerSupplierReport[],
  params: PurchasesPerSupplierExportParams['params']
) => (
  <Document>
    <Page size='A3' orientation='landscape' style={pdfStyles.page}>
      {/* Title and Parameters */}
      <View style={pdfStyles.titleSection}>
        <Text style={pdfStyles.mainTitle}>
          Laporan &gt; Rekapitulasi Pembelian Per Supplier
        </Text>
        <View style={pdfStyles.parameterContainer}>
          <View style={pdfStyles.parameterBadge}>
            <Text>
              Jenis Tanggal:{' '}
              {params.filter_by === 'received_date'
                ? 'Tanggal Terima'
                : 'Tanggal PO'}
            </Text>
          </View>
          {getParameterText(params).map((param, index) => (
            <View key={index} style={pdfStyles.parameterBadge}>
              <Text>{param}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* Supplier Sections */}
      {supplierReports.map(
        (
          supplierReport: LogisticPurchasePerSupplierReport,
          supplierIndex: number
        ) => {
          return (
            <View
              key={supplierReport.supplier.id}
              style={[
                pdfStyles.supplierSection,
                supplierIndex < supplierReports.length - 1
                  ? pdfStyles.supplierSectionBreak
                  : {},
              ]}
            >
              <Text style={pdfStyles.supplierTitle}>
                {supplierReport.supplier.name}
              </Text>

              <View style={pdfStyles.table}>
                {/* Table Header */}
                <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
                  <View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
                    <Text>No</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeader}>
                    <Text>Tanggal Terima</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeader}>
                    <Text>Tanggal PO</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeader}>
                    <Text>Referensi</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeader}>
                    <Text>Produk</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeader}>
                    <Text>Tujuan</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
                    <Text>Qty</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                    <Text>Harga Beli</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
                    <Text>Nilai Pembelian</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                    <Text>Biaya Transport</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
                    <Text>Total</Text>
                  </View>
                  <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                    <Text>Armada</Text>
                  </View>
                  <View style={pdfStyles.tableCellHeaderLast}>
                    <Text>Surat Jalan</Text>
                  </View>
                </View>

                {/* Table Body */}
                {supplierReport.rows.map(
                  (
                    item: LogisticPurchasePerSupplierReport['rows'][number],
                    index: number
                  ) => (
                    <View
                      key={index}
                      style={[
                        pdfStyles.tableRow,
                        index < supplierReport.rows.length - 1
                          ? pdfStyles.tableBorderBottom
                          : {},
                      ]}
                    >
                      <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                        <Text>{index + 1}</Text>
                      </View>
                      <View style={pdfStyles.tableCell}>
                        <Text>
                          {formatDate(item.receive_date, 'DD-MMM-YYYY')}
                        </Text>
                      </View>
                      <View style={pdfStyles.tableCell}>
                        <Text>{formatDate(item.po_date, 'DD-MMM-YYYY')}</Text>
                      </View>
                      <View style={pdfStyles.tableCell}>
                        <Text>{item.po_number || '-'}</Text>
                      </View>
                      <View style={pdfStyles.tableCell}>
                        <Text>{item.product?.name || '-'}</Text>
                      </View>
                      <View style={pdfStyles.tableCell}>
                        <Text>{item.warehouse?.name || '-'}</Text>
                      </View>
                      <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                        <Text>{formatNumber(item.qty || 0)}</Text>
                      </View>
                      <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                        <Text>{formatCurrency(item.unit_price || 0)}</Text>
                      </View>
                      <View style={[pdfStyles.tableCellRight, { flex: 1.5 }]}>
                        <Text>{formatCurrency(item.purchase_value || 0)}</Text>
                      </View>
                      <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                        <Text>
                          {formatCurrency(item.transport_unit_price || 0)}
                        </Text>
                      </View>
                      <View style={[pdfStyles.tableCellRight, { flex: 1.5 }]}>
                        <Text>{formatCurrency(item.total_amount || 0)}</Text>
                      </View>
                      <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                        <View style={pdfStyles.badge}>
                          <Text>{item.expedition || '-'}</Text>
                        </View>
                      </View>
                      <View style={pdfStyles.tableCellLast}>
                        <Text>{item.delivery_number || '-'}</Text>
                      </View>
                    </View>
                  )
                )}
              </View>
            </View>
          );
        }
      )}
    </Page>
  </Document>
);

export const generatePurchasesPerSupplierPDF = async (
  data: LogisticPurchasePerSupplierReport[],
  params: PurchasesPerSupplierExportParams['params']
): Promise<void> => {
  const PDFDocument = createPDFDocument(data, params);

  try {
    const blob = await pdf(PDFDocument).toBlob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `laporan-pembelian-per-supplier-dicetak-pada-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  } catch (error) {
    throw error;
  }
};
