'use client';

import {
  Page,
  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 } from '@/components/helper/pdf/table';
import { PdfParamBadge } from '@/components/helper/pdf/badge/PdfParamBadge';
import { PdfStatusBadge } from '@/components/helper/pdf/badge/PdfStatusBadge';
import { PdfTypography } from '@/components/helper/pdf/typography/PdfTypography';

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

const pdfStyles = StyleSheet.create({
  page: {
    fontSize: 10,
    fontFamily: 'Helvetica',
    padding: 20,
    backgroundColor: '#FFFFFF',
  },
  titleSection: {
    marginBottom: 10,
  },
  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 getTableColumns = (
  summary?: LogisticPurchasePerSupplierReport['summary']
): PdfColumn<LogisticPurchasePerSupplierReport['rows'][number]>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
    footer: 'Total',
  },
  {
    key: 'receive_date',
    header: 'Tanggal Terima',
    flex: 1.2,
    align: 'center',
    cell: ({ row }) =>
      row.receive_date ? formatDate(row.receive_date, 'DD MMM YY') : '-',
    footer: '',
  },
  {
    key: 'po_date',
    header: 'Tanggal PO',
    flex: 1.2,
    align: 'center',
    cell: ({ row }) =>
      row.po_date ? formatDate(row.po_date, 'DD MMM YY') : '-',
    footer: '',
  },
  {
    key: 'po_number',
    header: 'No. Referensi',
    flex: 1.5,
    align: 'left',
    cell: ({ row }) => row.po_number || '-',
    footer: '',
  },
  {
    key: 'product',
    header: 'Nama Produk',
    flex: 2,
    align: 'left',
    cell: ({ row }) => row.product?.name || '-',
    footer: '',
  },
  {
    key: 'warehouse',
    header: 'Tujuan',
    flex: 1.5,
    align: 'left',
    cell: ({ row }) => row.warehouse?.name || '-',
    footer: '',
  },
  {
    key: 'qty',
    header: 'QTY',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => formatNumber(row.qty || 0),
    footer: summary ? formatNumber(summary.total_qty || 0) : '',
    footerAlign: 'right',
  },
  {
    key: 'unit_price',
    header: 'Harga Beli (Rp)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.unit_price || 0),
    footer: '',
  },
  {
    key: 'purchase_value',
    header: 'Value Harga Beli (Rp)',
    flex: 1.8,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.purchase_value || 0),
    footer: summary ? formatCurrency(summary.total_purchase_value || 0) : '',
    footerAlign: 'right',
  },
  {
    key: 'transport_unit_price',
    header: 'Transport (Rp)',
    flex: 1.3,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.transport_unit_price || 0),
    footer: '',
  },
  {
    key: 'transport_value',
    header: 'Value Transport (Rp)',
    flex: 1.8,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.transport_value || 0),
    footer: summary ? formatCurrency(summary.total_transport_value || 0) : '',
    footerAlign: 'right',
  },
  {
    key: 'total_amount',
    header: 'Jumlah (Rp)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.total_amount || 0),
    footer: summary ? formatCurrency(summary.total_amount || 0) : '',
    footerAlign: 'right',
  },
  {
    key: 'expedition',
    header: 'Ekspedisi',
    flex: 1.2,
    align: 'center',
    cell: ({ row }) =>
      row.expedition ? (
        <View style={{ alignItems: 'center' }}>
          <PdfStatusBadge
            style={{
              backgroundColor: '#DBEAFE',
              color: '#1E40AF',
              borderColor: '#60A5FA',
            }}
          >
            {row.expedition}
          </PdfStatusBadge>
        </View>
      ) : (
        '-'
      ),
    footer: '',
  },
  {
    key: 'delivery_number',
    header: 'Surat Jalan',
    flex: 1.2,
    align: 'left',
    cell: ({ row }) => row.delivery_number || '-',
    footer: '',
  },
];

const createPDFDocument = (params: PurchasesPerSupplierExportParams) => {
  return (
    <Document>
      {params.data.map((supplierReport, supplierIndex) => (
        <Page
          key={supplierIndex}
          size='A3'
          orientation='landscape'
          style={pdfStyles.page}
        >
          {/* Title and Parameters */}
          <View style={pdfStyles.titleSection}>
            <PdfTypography size='h1' variant='primary'>
              Laporan &gt; Rekapitulasi Pembelian Per Supplier
            </PdfTypography>
            <View style={pdfStyles.parameterContainer}>
              <PdfParamBadge>
                Jenis Tanggal:{' '}
                {params.params?.filter_by === 'received_date'
                  ? 'Tanggal Terima'
                  : 'Tanggal PO'}
              </PdfParamBadge>
              <PdfParamBadge>
                Periode:{' '}
                {params.params?.start_date
                  ? formatDate(params.params.start_date, 'DD MMM YYYY')
                  : '-'}{' '}
                s.d{' '}
                {params.params?.end_date
                  ? formatDate(params.params.end_date, 'DD MMM YYYY')
                  : '-'}
              </PdfParamBadge>
              <PdfParamBadge>
                Supplier: {params.params?.supplier_name || 'Semua Supplier'}
              </PdfParamBadge>
              <PdfParamBadge>
                Area: {params.params?.area_name || 'Semua Area'}
              </PdfParamBadge>
              <PdfParamBadge>
                Produk: {params.params?.product_name || 'Semua Produk'}
              </PdfParamBadge>
              <PdfParamBadge>
                Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
              </PdfParamBadge>
            </View>
            <PdfTypography size='h2' variant='primary'>
              {supplierReport.supplier.name}
            </PdfTypography>
            {supplierReport.supplier.address && (
              <PdfTypography size='label'>
                Alamat: {supplierReport.supplier.address}
              </PdfTypography>
            )}
          </View>

          {/* Table */}
          <PdfTable
            columns={getTableColumns(supplierReport.summary)}
            data={supplierReport.rows}
            showFooter={!!supplierReport.summary}
          />
        </Page>
      ))}
    </Document>
  );
};

export const generatePurchasesPerSupplierPDF = async (
  params: PurchasesPerSupplierExportParams
): Promise<void> => {
  const PDFDocument = createPDFDocument(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;
  }
};
