'use client';

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

import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
import {
  PdfTable,
  PdfColumn,
  PdfTbodyCell,
  PdfTfootCell,
} 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',
  },
  supplierInfo: {
    fontSize: 9,
    marginBottom: 5,
    color: '#333333',
  },
  badge: {
    backgroundColor: '#1f74bf',
    color: '#FFFFFF',
    padding: 2,
    borderRadius: 2,
    fontSize: 7,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginRight: 4,
  },
  badgeLunas: {
    backgroundColor: '#1f74bf',
    color: '#FFFFFF',
  },
  badgeBelumLunas: {
    backgroundColor: '#F97316',
    color: '#FFFFFF',
  },
  textError: {
    color: '#DC2626',
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
});

interface CustomerPaymentExportPDFParams {
  data: CustomerPaymentReport[];
  params?: {
    customer_name?: string;
    // TODO: Uncomment when BE is ready
    // sales?: string;
    start_date?: string;
    end_date?: string;
    // TODO: Uncomment when BE is ready
    // filter_by?: string;
  };
}

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

  if (params?.customer_name) {
    paramsText.push(`Customer: ${params.customer_name}`);
  } else {
    paramsText.push('Semua Customer');
  }

  // TODO: Uncomment when BE is ready
  // if (params?.sales) {
  //   paramsText.push(`Sales: ${params.sales}`);
  // }

  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: 'trans_date', header: 'Tanggal DO', flex: 1.2, align: 'center' },
  {
    key: 'delivery_date',
    header: 'Tanggal Realisasi',
    flex: 1.2,
    align: 'center',
  },
  { key: 'aging', header: 'Aging', flex: 0.8, align: 'center' },
  { key: 'reference', header: 'Referensi', flex: 1.5, align: 'left' },
  { key: 'vehicle_numbers', header: 'No Polisi', flex: 1.2, align: 'left' },
  { key: 'qty', header: 'Qty', flex: 0.8, align: 'right' },
  { key: 'weight', header: 'Berat', flex: 1, align: 'right' },
  { key: 'average_weight', header: 'Rata-Rata', flex: 0.8, align: 'right' },
  { key: 'unit_price', header: 'Harga/Unit', flex: 1.2, align: 'right' },
  { key: 'final_price', header: 'Harga Akhir', flex: 1.2, align: 'right' },
  { key: 'total_price', header: 'Total', flex: 1.2, align: 'right' },
  { key: 'payment_amount', header: 'Pembayaran', flex: 1.2, align: 'right' },
  { key: 'accounts_receivable', header: 'Saldo', flex: 1.2, align: 'right' },
  { key: 'status', header: 'Keterangan', flex: 1.5, align: 'center' },
  { key: 'pickup_info', header: 'Pengambilan', flex: 1, align: 'left' },
  { key: 'sales_person', header: 'Sales', flex: 1.5, align: 'left' },
];

const getTableData = (
  rows: CustomerPaymentReport['rows']
): PdfTbodyCell[][] => {
  return rows.map((item, index) => [
    { key: 'no', value: index + 1 },
    {
      key: 'trans_date',
      value: item.trans_date ? formatDate(item.trans_date, 'DD MMM YY') : '-',
    },
    {
      key: 'delivery_date',
      value: item.delivery_date
        ? formatDate(item.delivery_date, 'DD MMM YY')
        : '-',
    },
    {
      key: 'aging',
      value:
        item.aging_day != null ? `${formatNumber(item.aging_day)} hari` : '-',
    },
    { key: 'reference', value: item.reference || '-' },
    {
      key: 'vehicle_numbers',
      value:
        Array.isArray(item.vehicle_numbers) && item.vehicle_numbers.length > 0
          ? item.vehicle_numbers.join(', ')
          : '-',
    },
    { key: 'qty', value: formatNumber(item.qty), align: 'right' },
    { key: 'weight', value: formatNumber(item.weight), align: 'right' },
    {
      key: 'average_weight',
      value: formatNumber(item.average_weight),
      align: 'right',
    },
    {
      key: 'unit_price',
      value: formatCurrency(item.unit_price),
      align: 'right',
    },
    {
      key: 'final_price',
      value: formatCurrency(item.final_price),
      align: 'right',
    },
    {
      key: 'total_price',
      value: formatCurrency(item.total_price),
      align: 'right',
    },
    {
      key: 'payment_amount',
      value: formatCurrency(item.payment_amount),
      align: 'right',
    },
    {
      key: 'accounts_receivable',
      value: formatCurrency(item.accounts_receivable),
      align: 'right',
      color: item.accounts_receivable < 0 ? '#DC2626' : undefined,
    },
    {
      key: 'status',
      value: item.status ? (
        <View
          style={[
            pdfStyles.badge,
            item.status === 'LUNAS'
              ? pdfStyles.badgeLunas
              : pdfStyles.badgeBelumLunas,
          ]}
        >
          <Text>{item.status === 'LUNAS' ? 'Lunas' : 'Belum Lunas'}</Text>
        </View>
      ) : (
        '-'
      ),
    },
    {
      key: 'pickup_info',
      value:
        Array.isArray(item.pickup_info) && item.pickup_info.length > 0
          ? item.pickup_info.join(', ')
          : '-',
    },
    { key: 'sales_person', value: item.sales_person || '-' },
  ]);
};

const getTableFooter = (
  summary: CustomerPaymentReport['summary']
): PdfTfootCell[] => [
  { key: 'no', value: 'Total' },
  { key: 'trans_date', value: '' },
  { key: 'delivery_date', value: '' },
  { key: 'aging', value: '' },
  { key: 'reference', value: '' },
  { key: 'vehicle_numbers', value: '' },
  { key: 'qty', value: formatNumber(summary?.total_qty || 0), align: 'right' },
  {
    key: 'weight',
    value: formatNumber(summary?.total_weight || 0),
    align: 'right',
  },
  { key: 'average_weight', value: '' },
  { key: 'unit_price', value: '' },
  {
    key: 'final_price',
    value: formatCurrency(summary?.total_final_amount || 0),
    align: 'right',
  },
  {
    key: 'total_price',
    value: formatCurrency(summary?.total_grand_amount || 0),
    align: 'right',
  },
  {
    key: 'payment_amount',
    value: formatCurrency(summary?.total_payment || 0),
    align: 'right',
  },
  {
    key: 'accounts_receivable',
    value: formatCurrency(summary?.total_accounts_receivable || 0),
    align: 'right',
    color:
      (summary?.total_accounts_receivable || 0) < 0 ? '#DC2626' : undefined,
  },
  { key: 'status', value: '' },
  { key: 'pickup_info', value: '' },
  { key: 'sales_person', value: '' },
];

const createPDFDocument = (params: CustomerPaymentExportPDFParams) => {
  return (
    <Document>
      {params.data.map((customerReport, customerIndex) => (
        <Page
          key={customerIndex}
          size='A3'
          orientation='landscape'
          style={pdfStyles.page}
        >
          {/* Title and Parameters */}
          <View style={pdfStyles.titleSection}>
            <Text style={pdfStyles.mainTitle}>
              Laporan &gt; Kontrol Pembayaran Customer
            </Text>
            <View style={pdfStyles.parameterContainer}>
              <View style={pdfStyles.parameterBadge}>
                <Text>
                  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')
                    : '-'}
                </Text>
              </View>
              {/* TODO: Uncomment when BE is ready */}
              {/* <View style={pdfStyles.parameterBadge}>
                <Text>Filter Tanggal: Tanggal DO</Text>
              </View> */}
              <View style={pdfStyles.parameterBadge}>
                <Text>
                  Customer: {params.params?.customer_name || 'Semua Customer'}
                </Text>
              </View>
              <View style={pdfStyles.parameterBadge}>
                <Text>
                  Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
                </Text>
              </View>
            </View>
            <Text style={pdfStyles.supplierTitle}>
              {customerReport.customer.name}
            </Text>
            <Text style={pdfStyles.supplierInfo}>
              Alamat: {customerReport.customer.address || '-'}
            </Text>
          </View>

          {/* Table */}
          <PdfTable
            columns={getTableColumns()}
            data={getTableData(customerReport.rows)}
            footer={
              customerReport.summary
                ? getTableFooter(customerReport.summary)
                : undefined
            }
            firstRow={
              typeof customerReport.initial_balance === 'number' &&
              customerReport.initial_balance !== 0
                ? {
                    valueKey: 'accounts_receivable',
                    value: customerReport.initial_balance,
                    align: 'right',
                    color:
                      customerReport.initial_balance < 0 ? '#DC2626' : 'black',
                  }
                : undefined
            }
          />
        </Page>
      ))}
    </Document>
  );
};

export const generateCustomerPaymentPDF = async (
  params: CustomerPaymentExportPDFParams
): 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-kontrol-pembayaran-customer-${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;
  }
};
