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

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',
  },
  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: 7,
    textAlign: 'left',
  },
  tableCellNo: {
    flex: 0.5,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    textAlign: 'center',
  },
  tableCellLast: {
    flex: 1,
    padding: 4,
    fontSize: 7,
  },
  tableCellHeader: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    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: 7,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    textAlign: 'right',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
  },
  tableCellRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    textAlign: 'right',
  },
  tableCellCenter: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    textAlign: 'center',
  },
  tableBorderBottom: {
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
  },
  summaryRow: {
    backgroundColor: '#F0F0F0',
    fontWeight: 'bold',
  },
  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;
};

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 */}
          <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, { flex: 1.2 }]}>
                <Text>Tanggal DO</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>Tanggal Realisasi</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 0.8 }]}>
                <Text>Aging</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
                <Text>Referensi</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>No Polisi</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
                <Text>Qty</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
                <Text>Berat</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
                <Text>Rata-Rata</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Harga/Unit</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Harga Akhir</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Total</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Pembayaran</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Saldo</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
                <Text>Keterangan</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Pengambilan</Text>
              </View>
              <View
                style={[
                  pdfStyles.tableCellHeader,
                  { flex: 1.5, borderRightWidth: 0 },
                ]}
              >
                <Text>Sales</Text>
              </View>
            </View>

            {/* Table Body */}
            <>
              {/* Initial Balance Row */}
              <View style={[pdfStyles.tableRow, pdfStyles.tableBorderBottom]}>
                <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.2,
                      color:
                        typeof customerReport.initial_balance === 'number' &&
                        customerReport.initial_balance < 0
                          ? 'red'
                          : 'black',
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(customerReport.initial_balance || 0)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCell,
                    { flex: 1.5, borderRightWidth: 0 },
                  ]}
                >
                  <Text></Text>
                </View>
              </View>

              {/* Data Rows */}
              {customerReport.rows.map((item, index) => (
                <View
                  key={index}
                  style={[
                    pdfStyles.tableRow,
                    index < customerReport.rows.length - 1
                      ? pdfStyles.tableBorderBottom
                      : {},
                  ]}
                >
                  <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                    <Text>{index + 1}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
                    <Text>
                      {item.trans_date
                        ? formatDate(item.trans_date, 'DD MMM YY')
                        : '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
                    <Text>
                      {item.delivery_date
                        ? formatDate(item.delivery_date, 'DD MMM YY')
                        : '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
                    <Text>
                      {item.aging_day != null
                        ? `${formatNumber(item.aging_day)} hari`
                        : '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                    <Text>{item.reference || '-'}</Text>
                  </View>
                  <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                    <Text>
                      {Array.isArray(item.vehicle_numbers)
                        ? item.vehicle_numbers.length > 0
                          ? item.vehicle_numbers.join(', ')
                          : '-'
                        : '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                    <Text>{formatNumber(item.qty)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                    <Text>{formatNumber(item.weight)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                    <Text>{formatNumber(item.average_weight)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(item.unit_price)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(item.final_price)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(item.total_price)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(item.payment_amount)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text style={pdfStyles.textError}>
                      {formatCurrency(item.accounts_receivable)}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCellCenter, { flex: 1.5 }]}>
                    {item.status ? (
                      <View
                        style={[
                          pdfStyles.badge,
                          item.status === 'LUNAS'
                            ? pdfStyles.badgeLunas
                            : pdfStyles.badgeBelumLunas,
                        ]}
                      >
                        <Text>
                          {item.status === 'LUNAS' ? 'Lunas' : 'Belum Lunas'}
                        </Text>
                      </View>
                    ) : (
                      <Text>-</Text>
                    )}
                  </View>
                  <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                    <Text>
                      {Array.isArray(item.pickup_info)
                        ? item.pickup_info.length > 0
                          ? item.pickup_info.join(', ')
                          : '-'
                        : '-'}
                    </Text>
                  </View>
                  <View
                    style={[
                      pdfStyles.tableCell,
                      { flex: 1.5, borderRightWidth: 0 },
                    ]}
                  >
                    <Text>{item.sales_person || '-'}</Text>
                  </View>
                </View>
              ))}
            </>

            {/* Summary Row */}
            {customerReport.summary && (
              <View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
                <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                  <Text>Total</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 0.8 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text>{formatNumber(customerReport.summary.total_qty)}</Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                  <Text>
                    {formatNumber(customerReport.summary.total_weight)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text>
                    {formatCurrency(customerReport.summary.total_final_amount)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text>
                    {formatCurrency(customerReport.summary.total_grand_amount)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text>
                    {formatCurrency(customerReport.summary.total_payment)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text style={pdfStyles.textError}>
                    {formatCurrency(
                      customerReport.summary.total_accounts_receivable
                    )}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCell,
                    { flex: 1.5, borderRightWidth: 0 },
                  ]}
                >
                  <Text></Text>
                </View>
              </View>
            )}
          </View>
        </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;
  }
};
