'use client';

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

import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { DebtSupplier } from '@/types/api/report/debt-supplier';

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

// Status color mappings (same as in DebtSupplierTab)
const dueStatusColors: Record<
  string,
  { bg: string; text: string; border: string }
> = {
  'Sudah Jatuh Tempo': { bg: '#FEE2E2', text: '#991B1B', border: '#F87171' }, // error/red
  'Belum Jatuh Tempo': { bg: '#D1FAE5', text: '#065F46', border: '#34D399' }, // success/green
  'Mendekati Jatuh Tempo': {
    bg: '#FEF3C7',
    text: '#92400E',
    border: '#FBBF24',
  }, // warning/yellow
};

const paymentStatusColors: Record<
  string,
  { bg: string; text: string; border: string }
> = {
  'Belum Lunas': { bg: '#FEF3C7', text: '#92400E', border: '#FBBF24' }, // warning/yellow
  Lunas: { bg: '#DBEAFE', text: '#1E40AF', border: '#60A5FA' }, // primary/blue
  Pembayaran: { bg: '#D1FAE5', text: '#065F46', border: '#34D399' }, // success/green
};

/**
 * Get badge style for PDF rendering
 * @param statusText - The status text
 * @param type - Type of status: 'due' or 'payment'
 * @returns Style object with background and text colors
 */
const getPDFBadgeStyle = (
  statusText: string,
  type: 'due' | 'payment' = 'payment'
) => {
  const colors =
    type === 'due'
      ? dueStatusColors[statusText]
      : paymentStatusColors[statusText];

  return colors || { bg: '#F3F4F6', text: '#374151', border: '#D1D5DB' }; // neutral fallback
};

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: {
    paddingVertical: 2,
    paddingHorizontal: 4,
    borderRadius: 12,
    fontSize: 5,
    fontWeight: 'bold',
    borderWidth: 1,
    textAlign: 'center',
    whiteSpace: 'nowrap',
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
});

interface DebtSupplierExportPDFParams {
  data: DebtSupplier[];
  params?: {
    supplier_name?: string;
    start_date?: string;
    end_date?: string;
    filter_by?: string;
  };
}

const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
  return (
    <Document>
      {params.data.map((supplierReport, supplierIndex) => (
        <Page
          key={supplierIndex}
          size='A4'
          orientation='landscape'
          style={pdfStyles.page}
        >
          {/* Title and Supplier Info */}
          <View style={pdfStyles.titleSection}>
            <Text style={pdfStyles.mainTitle}>
              Laporan &gt; Rekapitulasi Hutang ke Supplier
            </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>
              {params.params?.filter_by && (
                <View style={pdfStyles.parameterBadge}>
                  <Text>
                    Filter Tanggal:{' '}
                    {params.params.filter_by === 'po_date'
                      ? 'Tanggal PO'
                      : params.params.filter_by === 'received_date'
                        ? 'Tanggal Terima'
                        : params.params.filter_by === 'due_date'
                          ? 'Tanggal Jatuh Tempo'
                          : params.params.filter_by}
                  </Text>
                </View>
              )}
              <View style={pdfStyles.parameterBadge}>
                <Text>
                  Supplier: {params.params?.supplier_name || 'Semua Supplier'}
                </Text>
              </View>
              <View style={pdfStyles.parameterBadge}>
                <Text>
                  Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
                </Text>
              </View>
            </View>
            <Text style={pdfStyles.supplierTitle}>
              {supplierReport.supplier.name}
            </Text>
            <Text style={pdfStyles.supplierInfo}>
              {supplierReport.supplier.category}
            </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.5 }]}>
                <Text>No. PR</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
                <Text>No. PO</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Tgl Terima/Bayar</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Tgl PO</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 0.6 }]}>
                <Text>Aging</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Area</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Gudang</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Jatuh Tempo</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 2 }]}>
                <Text>Status Jatuh Tempo</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
                <Text>Nominal Pembelian (Rp)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
                <Text>Pembayaran (Rp)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
                <Text>Sisa Saldo Hutang (Rp)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>Status</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>No. Perjalanan</Text>
              </View>
            </View>

            {/* Initial Balance Row */}
            <View style={[pdfStyles.tableRow, pdfStyles.tableBorderBottom]}>
              <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                <Text></Text> {/* NO */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                <Text></Text> {/* No. PR */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                <Text></Text> {/* No. PO */}
              </View>
              <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                <Text></Text> {/* Tgl Terima/Bayar */}
              </View>
              <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                <Text></Text> {/* Tgl PO */}
              </View>
              <View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
                <Text></Text> {/* Aging */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                <Text></Text> {/* Area */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                <Text></Text> {/* Gudang */}
              </View>
              <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                <Text></Text> {/* Jatuh Tempo */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 2 }]}>
                <Text></Text> {/* Status Jatuh Tempo */}
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1.5 }]}>
                <Text></Text> {/* Nominal Pembelian (Rp) */}
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1.5 }]}>
                <Text></Text> {/* Pembayaran (Rp) */}
              </View>
              <View
                style={[
                  pdfStyles.tableCellRight,
                  {
                    flex: 1.5,
                    color: supplierReport.initial_balance < 0 ? 'red' : 'black',
                  },
                ]}
              >
                <Text>
                  {' '}
                  {/* Sisa Saldo Hutang (Rp) */}
                  {formatCurrency(supplierReport.initial_balance || 0)}
                </Text>
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                <Text></Text> {/* Status */}
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                <Text></Text> {/* No. Perjalanan */}
              </View>
            </View>

            {/* Table Body */}
            {supplierReport.rows.map((item, index) => (
              <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, { flex: 1.5 }]}>
                  <Text>{item.pr_number || '-'}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text>{item.po_number || '-'}</Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                  <Text>
                    {item.received_date
                      ? item.received_date != '-'
                        ? formatDate(item.received_date, 'DD MMM YY')
                        : '-'
                      : '-'}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                  <Text>
                    {item.po_date
                      ? item.po_date != '-'
                        ? formatDate(item.po_date, 'DD MMM YY')
                        : '-'
                      : '-'}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
                  <Text>{formatNumber(item.aging)} Hari</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text>{item.area?.name || '-'}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text>{item.warehouse?.name || '-'}</Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                  <Text>
                    {item.due_date
                      ? item.due_date != '-'
                        ? formatDate(item.due_date, 'DD MMM YY')
                        : '-'
                      : '-'}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 2 }]}>
                  {item.due_status && item.due_status !== '-' ? (
                    <View
                      style={[
                        pdfStyles.badge,
                        {
                          backgroundColor: getPDFBadgeStyle(
                            item.due_status,
                            'due'
                          ).bg,
                          borderColor: getPDFBadgeStyle(item.due_status, 'due')
                            .border,
                        },
                      ]}
                    >
                      <Text
                        style={{
                          color: getPDFBadgeStyle(item.due_status, 'due').text,
                        }}
                      >
                        {item.due_status}
                      </Text>
                    </View>
                  ) : (
                    <Text>-</Text>
                  )}
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.5,
                      color: item.total_price < 0 ? 'red' : 'black',
                    },
                  ]}
                >
                  <Text>{formatCurrency(item.total_price)}</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.5,
                      color: item.payment_price < 0 ? 'red' : 'black',
                    },
                  ]}
                >
                  <Text>{formatCurrency(item.payment_price)}</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    { flex: 1.5, color: item.balance < 0 ? 'red' : 'black' },
                  ]}
                >
                  <Text>{formatCurrency(item.balance)}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  {item.status && item.status !== '-' ? (
                    <View
                      style={[
                        pdfStyles.badge,
                        {
                          backgroundColor: getPDFBadgeStyle(
                            item.status,
                            'payment'
                          ).bg,
                          borderColor: getPDFBadgeStyle(item.status, 'payment')
                            .border,
                        },
                      ]}
                    >
                      <Text
                        style={{
                          color: getPDFBadgeStyle(item.status, 'payment').text,
                        }}
                      >
                        {item.status}
                      </Text>
                    </View>
                  ) : (
                    <Text>-</Text>
                  )}
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text>{item.travel_number || '-'}</Text>
                </View>
              </View>
            ))}

            {/* Summary Row */}
            {supplierReport.total && (
              <View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
                <View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
                  <Text>Total</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text></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 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
                  <Text>{formatNumber(supplierReport.total.aging)} Hari</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 2 }]}>
                  <Text></Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.5,
                      color:
                        supplierReport.total.total_price < 0 ? 'red' : 'black',
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(supplierReport.total.total_price)}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.5,
                      color:
                        supplierReport.total.payment_price < 0
                          ? 'red'
                          : 'black',
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(supplierReport.total.payment_price)}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    {
                      flex: 1.5,
                      color:
                        supplierReport.total.debt_price < 0 ? 'red' : 'black',
                    },
                  ]}
                >
                  <Text>{formatCurrency(supplierReport.total.debt_price)}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text></Text>
                </View>
                <View style={[pdfStyles.tableCellLast, { flex: 1 }]}>
                  <Text></Text>
                </View>
              </View>
            )}
          </View>
        </Page>
      ))}
    </Document>
  );
};

export const generateDebtSupplierPDF = async (
  params: DebtSupplierExportPDFParams
): 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-hutang-supplier-${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;
  }
};
