'use client';

import {
  Page,
  View,
  Document,
  StyleSheet,
  Font,
  pdf,
} from '@react-pdf/renderer';
import {
  HppPerKandangReport,
  HppPerKandangRow,
  HppPerKandangPerWeightRange,
} from '@/types/api/report/hpp-per-kandang';
import { formatDate, formatNumber, formatCurrency } from '@/lib/helper';
import { PdfTable, PdfColumn } from '@/components/helper/pdf/table';
import { PdfParamBadge } from '@/components/helper/pdf/badge/PdfParamBadge';
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,
  },
  section: {
    marginBottom: 15,
  },
});

interface HppPerKandangExportParams {
  data: HppPerKandangReport;
  params?: {
    area_name?: string;
    location_name?: string;
    kandang_name?: string;
    period?: string;
    weight_min?: string;
    weight_max?: string;
    show_unrecorded?: string;
    sort_by?: string;
  };
}

const formatSuppliers = (
  suppliers: { alias?: string; name: string }[] | null | undefined
): string => {
  if (!suppliers || suppliers.length === 0) return '-';
  return suppliers.map((s) => s.alias || s.name).join(' | ');
};

// Helper functions for PdfTable - Rekapitulasi
const getRekapitulasiColumns = (): PdfColumn<HppPerKandangPerWeightRange>[] => [
  {
    key: 'rentang_bw',
    header: 'Rentang BW',
    flex: 1.2,
    align: 'center',
    cell: ({ row }) => row.label || '-',
  },
  {
    key: 'sisa_butir',
    header: 'Sisa Butir',
    flex: 1,
    align: 'right',
    cell: ({ row }) => formatNumber(row.egg_production_pieces || 0),
  },
  {
    key: 'sisa_kg',
    header: 'Sisa Kg',
    flex: 1,
    align: 'right',
    cell: ({ row }) => formatNumber(row.egg_production_kg || 0),
  },
  {
    key: 'rata_rata_bobot',
    header: 'Rata-Rata Bobot (Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatNumber(row.avg_weight_kg || 0),
  },
  {
    key: 'feed_supplier',
    header: 'Feed (Supplier)',
    flex: 1.5,
    align: 'left',
    cell: ({ row }) => formatSuppliers(row.feed_suppliers),
  },
  {
    key: 'doc_supplier',
    header: 'DOC (Supplier)',
    flex: 1.2,
    align: 'left',
    cell: ({ row }) => formatSuppliers(row.doc_suppliers),
  },
  {
    key: 'rata_harga_doc',
    header: 'Rata-Rata Harga DOC',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.average_doc_price_rp || 0),
  },
  {
    key: 'hpp_telur',
    header: 'HPP Telur (Rp/Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.egg_hpp_rp_per_kg || 0),
  },
  {
    key: 'nominal_sisa',
    header: 'Nominal Sisa',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.egg_value_rp || 0),
  },
];

// Helper functions for PdfTable - Detail Per Kandang
const getDetailColumns = (
  summary?: HppPerKandangReport['summary'],
  allFeedSuppliers?: string,
  allDocSuppliers?: string
): PdfColumn<HppPerKandangRow>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
    footer: 'TOTAL',
  },
  {
    key: 'kandang',
    header: 'Kandang',
    flex: 1.5,
    align: 'left',
    cell: ({ row }) => row.kandang?.name || '-',
    footer: 'ALL',
  },
  {
    key: 'rentang_bw',
    header: 'Rentang BW',
    flex: 1,
    align: 'left',
    cell: ({ row }) =>
      `${row.weight_range.weight_min.toFixed(2)} - ${row.weight_range.weight_max.toFixed(2)}`,
    footer: '-',
  },
  {
    key: 'rata_rata_bobot',
    header: 'Rata-Rata Bobot (Kg)',
    flex: 1,
    align: 'right',
    cell: ({ row }) => formatNumber(row.avg_weight_kg || 0),
    footer: summary ? formatNumber(summary.total.average_weight_kg || 0) : '',
    footerAlign: 'right',
  },
  {
    key: 'sisa_butir',
    header: 'Sisa Butir',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => formatNumber(row.egg_production_pieces || 0),
    footer: summary
      ? formatNumber(summary.total.total_egg_production_pieces || 0)
      : '',
    footerAlign: 'right',
  },
  {
    key: 'sisa_kg',
    header: 'Sisa Kg (Telur)',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => formatNumber(row.egg_production_kg || 0),
    footer: summary
      ? formatNumber(summary.total.total_egg_production_kg || 0)
      : '',
    footerAlign: 'right',
  },
  {
    key: 'feed_supplier',
    header: 'Feed (Supplier)',
    flex: 1.2,
    align: 'left',
    cell: ({ row }) => formatSuppliers(row.feed_suppliers),
    footer: allFeedSuppliers || '-',
  },
  {
    key: 'doc_supplier',
    header: 'DOC (Supplier)',
    flex: 1,
    align: 'left',
    cell: ({ row }) => formatSuppliers(row.doc_suppliers),
    footer: allDocSuppliers || '-',
  },
  {
    key: 'rata_harga_doc',
    header: 'Rata-Rata Harga DOC',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.average_doc_price_rp || 0),
    footer: summary
      ? formatCurrency(summary.total.total_average_doc_price_rp || 0)
      : '',
    footerAlign: 'right',
  },
  {
    key: 'hpp_telur',
    header: 'HPP Telur (Rp/Kg)',
    flex: 1,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.egg_hpp_rp_per_kg || 0),
    footer: summary
      ? formatCurrency(summary.total.average_egg_hpp_rp_per_kg || 0)
      : '',
    footerAlign: 'right',
  },
  {
    key: 'nominal_sisa',
    header: 'Nominal Sisa',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => formatCurrency(row.egg_value_rp || 0),
    footer: summary
      ? formatCurrency(summary.total.total_egg_value_rp || 0)
      : '',
    footerAlign: 'right',
  },
];

const createPDFDocument = (
  params: HppPerKandangExportParams,
  allFeedSuppliers: string,
  allDocSuppliers: string
) => {
  const rekapitulasiByWeightRange = params.data.summary?.per_weight_range || [];

  const weightRangeText =
    params.params?.weight_min || params.params?.weight_max
      ? params.params.weight_min && params.params.weight_max
        ? `${params.params.weight_min} - ${params.params.weight_max} kg`
        : params.params.weight_min
          ? `≥ ${params.params.weight_min} kg`
          : `≤ ${params.params.weight_max} kg`
      : '-';

  return (
    <Document>
      <Page size='A3' orientation='landscape' style={pdfStyles.page}>
        {/* Title and Parameters */}
        <View style={pdfStyles.titleSection}>
          <PdfTypography size='h1' variant='primary'>
            Laporan &gt; HPP Harian Kandang
          </PdfTypography>
          <View style={pdfStyles.parameterContainer}>
            <PdfParamBadge>
              Area: {params.params?.area_name || 'Semua Area'}
            </PdfParamBadge>
            <PdfParamBadge>
              Lokasi: {params.params?.location_name || 'Semua Lokasi'}
            </PdfParamBadge>
            <PdfParamBadge>
              Kandang: {params.params?.kandang_name || 'Semua Kandang'}
            </PdfParamBadge>
            <PdfParamBadge>
              Periode:{' '}
              {params.params?.period
                ? formatDate(params.params.period, 'DD MMM YYYY')
                : '-'}
            </PdfParamBadge>
            <PdfParamBadge>Rentang Bobot: {weightRangeText}</PdfParamBadge>
            {params.params?.show_unrecorded === 'true' && (
              <PdfParamBadge>Tampilkan: Tanpa Recording</PdfParamBadge>
            )}
            <PdfParamBadge>
              Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
            </PdfParamBadge>
          </View>
        </View>

        {/* Rekapitulasi Section */}
        <View style={pdfStyles.section}>
          <PdfTypography size='h2' variant='primary'>
            Rekapitulasi
          </PdfTypography>
          <PdfTable
            columns={getRekapitulasiColumns()}
            data={rekapitulasiByWeightRange}
          />
        </View>

        {/* Detail Per Kandang Section */}
        <View style={pdfStyles.section}>
          <PdfTypography size='h2' variant='primary'>
            Detail Per Kandang
          </PdfTypography>
          <PdfTable
            columns={getDetailColumns(
              params.data.summary,
              allFeedSuppliers,
              allDocSuppliers
            )}
            data={params.data.rows}
            showFooter={!!params.data.summary}
            footerLabel='TOTAL'
          />
        </View>
      </Page>
    </Document>
  );
};

export const generateHppPerKandangPDF = async (
  params: HppPerKandangExportParams,
  allFeedSuppliers: string,
  allDocSuppliers: string
): Promise<void> => {
  const PDFDocument = createPDFDocument(
    params,
    allFeedSuppliers,
    allDocSuppliers
  );

  try {
    const blob = await pdf(PDFDocument).toBlob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    const period =
      params.params?.period || formatDate(new Date(), 'YYYY-MM-DD');
    link.download = `laporan-hpp-harian-kandang-periode-${period}.pdf`;

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  } catch (error) {
    throw error;
  }
};
