'use client';

import {
  Page,
  Text,
  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,
  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',
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  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 getParameterText = (params: HppPerKandangExportParams['params']) => {
  const paramsText = [];

  if (params.area_name && params.area_name !== 'Semua Area') {
    paramsText.push(`Area: ${params.area_name}`);
  }

  if (params.location_name && params.location_name !== 'Semua Lokasi') {
    paramsText.push(`Lokasi: ${params.location_name}`);
  }

  if (params.kandang_name && params.kandang_name !== 'Semua Kandang') {
    paramsText.push(`Kandang: ${params.kandang_name}`);
  }

  if (params.period) {
    const formattedDate = formatDate(params.period, 'DD MMM YYYY');
    paramsText.push(`Tanggal: ${formattedDate}`);
  }

  if (params.weight_min || params.weight_max) {
    const weightRange =
      params.weight_min && params.weight_max
        ? `${params.weight_min} - ${params.weight_max} kg`
        : params.weight_min
          ? `≥ ${params.weight_min} kg`
          : `≤ ${params.weight_max} kg`;
    paramsText.push(`Rentang Bobot: ${weightRange}`);
  }

  if (params.show_unrecorded === 'true') {
    paramsText.push('Tampilkan: Tanpa Recording');
  }

  const currentDate = formatDate(new Date().toISOString(), 'DD MMM YYYY HH:mm');
  paramsText.push(`Dicetak: ${currentDate}`);

  return paramsText;
};

// Helper functions for PdfTable - Rekapitulasi
const getRekapitulasiColumns = (): PdfColumn[] => [
  { key: 'rentang_bw', header: 'Rentang BW', flex: 1.2, align: 'center' },
  { key: 'sisa_butir', header: 'Sisa Butir', flex: 1, align: 'right' },
  { key: 'sisa_kg', header: 'Sisa Kg', flex: 1, align: 'right' },
  {
    key: 'rata_rata_bobot',
    header: 'Rata-Rata Bobot (Kg)',
    flex: 1.2,
    align: 'right',
  },
  { key: 'feed_supplier', header: 'Feed (Supplier)', flex: 1.5, align: 'left' },
  { key: 'doc_supplier', header: 'DOC (Supplier)', flex: 1.2, align: 'left' },
  {
    key: 'rata_harga_doc',
    header: 'Rata-Rata Harga DOC',
    flex: 1.2,
    align: 'right',
  },
  { key: 'hpp_telur', header: 'HPP Telur (RP/KG)', flex: 1.2, align: 'right' },
  { key: 'nominal_sisa', header: 'Nominal Sisa', flex: 1.2, align: 'right' },
];

const getRekapitulasiData = (
  perWeightRange: HppPerKandangPerWeightRange[]
): PdfTbodyCell[][] => {
  return perWeightRange.map((group) => [
    { key: 'rentang_bw', value: group.label, align: 'center' },
    {
      key: 'sisa_butir',
      value: formatNumber(group.egg_production_pieces),
      align: 'right',
    },
    {
      key: 'sisa_kg',
      value: formatNumber(group.egg_production_kg),
      align: 'right',
    },
    {
      key: 'rata_rata_bobot',
      value: formatNumber(group.avg_weight_kg),
      align: 'right',
    },
    {
      key: 'feed_supplier',
      value:
        group.feed_suppliers
          ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
          .join(' | ') || '-',
    },
    {
      key: 'doc_supplier',
      value:
        group.doc_suppliers
          ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
          .join(' | ') || '-',
    },
    {
      key: 'rata_harga_doc',
      value: formatCurrency(group.average_doc_price_rp),
      align: 'right',
    },
    {
      key: 'hpp_telur',
      value: formatCurrency(group.egg_hpp_rp_per_kg),
      align: 'right',
    },
    {
      key: 'nominal_sisa',
      value: formatCurrency(group.egg_value_rp),
      align: 'right',
    },
  ]);
};

// Helper functions for PdfTable - Detail Per Kandang
const getDetailColumns = (): PdfColumn[] => [
  { key: 'no', header: 'No', flex: 0.5, align: 'center' },
  { key: 'kandang', header: 'Kandang', flex: 1.5, align: 'left' },
  { key: 'rentang_bw', header: 'Rentang BW', flex: 1, align: 'left' },
  {
    key: 'rata_rata_bobot',
    header: 'Rata-Rata Bobot (Kg)',
    flex: 1,
    align: 'right',
  },
  { key: 'sisa_butir', header: 'Sisa Butir', flex: 0.8, align: 'right' },
  { key: 'sisa_kg', header: 'Sisa Kg (Telur)', flex: 0.8, align: 'right' },
  { key: 'feed_supplier', header: 'Feed (Supplier)', flex: 1.2, align: 'left' },
  { key: 'doc_supplier', header: 'DOC (Supplier)', flex: 1, align: 'left' },
  {
    key: 'rata_harga_doc',
    header: 'Rata-Rata Harga DOC',
    flex: 1.2,
    align: 'right',
  },
  { key: 'hpp_telur', header: 'HPP Telur (RP/KG)', flex: 1, align: 'right' },
  { key: 'nominal_sisa', header: 'Nominal Sisa', flex: 1.2, align: 'right' },
];

const getDetailData = (rows: HppPerKandangRow[]): PdfTbodyCell[][] => {
  return rows.map((item, index) => [
    { key: 'no', value: index + 1, align: 'center' },
    { key: 'kandang', value: item.kandang?.name || '-' },
    {
      key: 'rentang_bw',
      value: `${item.weight_range.weight_min.toFixed(2)} - ${item.weight_range.weight_max.toFixed(2)}`,
    },
    {
      key: 'rata_rata_bobot',
      value: formatNumber(item.avg_weight_kg),
      align: 'right',
    },
    {
      key: 'sisa_butir',
      value: formatNumber(item.egg_production_pieces),
      align: 'right',
    },
    {
      key: 'sisa_kg',
      value: formatNumber(item.egg_production_kg),
      align: 'right',
    },
    {
      key: 'feed_supplier',
      value:
        item.feed_suppliers
          ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
          .join(' | ') || '-',
    },
    {
      key: 'doc_supplier',
      value:
        item.doc_suppliers
          ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
          .join(' | ') || '-',
    },
    {
      key: 'rata_harga_doc',
      value: formatCurrency(item.average_doc_price_rp),
      align: 'right',
    },
    {
      key: 'hpp_telur',
      value: formatCurrency(item.egg_hpp_rp_per_kg),
      align: 'right',
    },
    {
      key: 'nominal_sisa',
      value: formatCurrency(item.egg_value_rp),
      align: 'right',
    },
  ]);
};

const getDetailFooter = (
  summary: HppPerKandangReport['summary']
): PdfTfootCell[] => {
  if (!summary?.total) return [];

  const allFeedSuppliers =
    summary.total.feed_suppliers
      ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
      .join(' | ') || '-';

  const allDocSuppliers =
    summary.total.doc_suppliers
      ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
      .join(' | ') || '-';

  return [
    { key: 'no', value: 'TOTAL' },
    { key: 'kandang', value: 'ALL' },
    { key: 'rentang_bw', value: '-' },
    {
      key: 'rata_rata_bobot',
      value: formatNumber(summary.total.average_weight_kg),
      align: 'right',
    },
    {
      key: 'sisa_butir',
      value: formatNumber(summary.total.total_egg_production_pieces),
      align: 'right',
    },
    {
      key: 'sisa_kg',
      value: formatNumber(summary.total.total_egg_production_kg),
      align: 'right',
    },
    { key: 'feed_supplier', value: allFeedSuppliers },
    { key: 'doc_supplier', value: allDocSuppliers },
    {
      key: 'rata_harga_doc',
      value: formatCurrency(summary.total.total_average_doc_price_rp),
      align: 'right',
    },
    {
      key: 'hpp_telur',
      value: formatCurrency(summary.total.average_egg_hpp_rp_per_kg),
      align: 'right',
    },
    {
      key: 'nominal_sisa',
      value: formatCurrency(summary.total.total_egg_value_rp),
      align: 'right',
    },
  ];
};

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

  return (
    <Document>
      <Page size='A3' orientation='landscape' style={pdfStyles.page}>
        {/* Title and Parameters */}
        <View style={pdfStyles.titleSection}>
          <Text style={pdfStyles.mainTitle}>
            Laporan &gt; HPP Harian Kandang
          </Text>
          <View style={pdfStyles.parameterContainer}>
            {getParameterText(params).map((param, index) => (
              <View key={index} style={pdfStyles.parameterBadge}>
                <Text>{param}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Rekapitulasi Section */}
        <View style={pdfStyles.section}>
          <Text style={pdfStyles.supplierTitle}>Rekapitulasi</Text>
          <PdfTable
            columns={getRekapitulasiColumns()}
            data={getRekapitulasiData(rekapitulasiByWeightRange)}
          />
        </View>

        {/* Detail Per Kandang Section */}
        <View style={pdfStyles.section}>
          <Text style={pdfStyles.supplierTitle}>Detail Per Kandang</Text>
          <PdfTable
            columns={getDetailColumns()}
            data={getDetailData(data.rows)}
            footer={data.summary ? getDetailFooter(data.summary) : undefined}
            footerLabel='TOTAL'
          />
        </View>
      </Page>
    </Document>
  );
};

export const generateHppPerKandangPDF = async (
  data: HppPerKandangExportParams['data'],
  params: HppPerKandangExportParams['params']
): Promise<void> => {
  const PDFDocument = createPDFDocument(data, params);

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

    const period = 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;
  }
};
