'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';
import {
  PdfTable,
  PdfColumn,
  PdfTbodyCell,
} from '@/components/helper/pdf/table';

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',
  },
  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,
  },
  supplierSection: {
    marginBottom: 10,
  },
  supplierSectionBreak: {
    marginBottom: 15,
  },
});

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

// Helper functions for PdfTable
const getTableColumns = (): PdfColumn[] => [
  { key: 'no', header: 'No', flex: 0.5, align: 'center' },
  { key: 'receive_date', header: 'Tanggal Terima', flex: 1, align: 'center' },
  { key: 'po_date', header: 'Tanggal PO', flex: 1, align: 'center' },
  { key: 'po_number', header: 'Referensi', flex: 1, align: 'left' },
  { key: 'product', header: 'Produk', flex: 1, align: 'left' },
  { key: 'warehouse', header: 'Tujuan', flex: 1, align: 'left' },
  { key: 'qty', header: 'Qty', flex: 0.8, align: 'right' },
  { key: 'unit_price', header: 'Harga Beli', flex: 1.2, align: 'right' },
  {
    key: 'purchase_value',
    header: 'Nilai Pembelian',
    flex: 1.5,
    align: 'right',
  },
  {
    key: 'transport_price',
    header: 'Biaya Transport',
    flex: 1.2,
    align: 'right',
  },
  { key: 'total_amount', header: 'Total', flex: 1.5, align: 'right' },
  { key: 'expedition', header: 'Armada', flex: 1.2, align: 'center' },
  { key: 'delivery_number', header: 'Surat Jalan', flex: 1, align: 'left' },
];

const getTableData = (
  rows: LogisticPurchasePerSupplierReport['rows']
): PdfTbodyCell[][] => {
  return rows.map((item, index) => [
    { key: 'no', value: index + 1, align: 'center' },
    {
      key: 'receive_date',
      value: formatDate(item.receive_date, 'DD-MMM-YYYY'),
      align: 'center',
    },
    {
      key: 'po_date',
      value: formatDate(item.po_date, 'DD-MMM-YYYY'),
      align: 'center',
    },
    { key: 'po_number', value: item.po_number || '-' },
    { key: 'product', value: item.product?.name || '-' },
    { key: 'warehouse', value: item.warehouse?.name || '-' },
    { key: 'qty', value: formatNumber(item.qty || 0), align: 'right' },
    {
      key: 'unit_price',
      value: formatCurrency(item.unit_price || 0),
      align: 'right',
    },
    {
      key: 'purchase_value',
      value: formatCurrency(item.purchase_value || 0),
      align: 'right',
    },
    {
      key: 'transport_price',
      value: formatCurrency(item.transport_unit_price || 0),
      align: 'right',
    },
    {
      key: 'total_amount',
      value: formatCurrency(item.total_amount || 0),
      align: 'right',
    },
    {
      key: 'expedition',
      value: (
        <View style={pdfStyles.badge}>
          <Text>{item.expedition || '-'}</Text>
        </View>
      ),
      align: 'center',
    },
    { key: 'delivery_number', value: item.delivery_number || '-' },
  ]);
};

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>

              <PdfTable
                columns={getTableColumns()}
                data={getTableData(supplierReport.rows)}
              />
            </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;
  }
};
