'use client';

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

import { formatDate, formatNumber } from '@/lib/helper';
import { BaseProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { ProductionResult } from '@/types/api/report/production-result';
import { PdfTypography } from '@/components/helper/pdf/typography/PdfTypography';
import { PdfParamBadge } from '@/components/helper/pdf/badge/PdfParamBadge';
import { PdfPageNumber } from '@/components/helper/pdf/layout/PdfPageNumber';
import { PdfTable, PdfColumn } from '@/components/helper/pdf/table';

type MappedProductionResultsItem = {
  projectFlockKandang: BaseProjectFlockKandang;
  productionResult: ProductionResult[] | null;
};

interface ProductionResultReportPDFProps {
  mappedProductionResults?: MappedProductionResultsItem[];
}

const styles = StyleSheet.create({
  page: {
    fontSize: 10,
    fontFamily: 'Helvetica',
    padding: 20,
    backgroundColor: '#FFFFFF',
  },
  titleSection: {
    marginBottom: 10,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
  tableSection: {
    marginBottom: 12,
  },
  tableTitle: {
    fontSize: 10,
    fontWeight: 'bold',
    marginBottom: 6,
    color: '#333',
  },
  emptyText: {
    fontSize: 8,
    color: '#666',
    fontStyle: 'italic',
  },
});

function valueText(v: unknown) {
  if (v === null || v === undefined) return '-';
  if (typeof v === 'number') return formatNumber(v);
  return String(v);
}

// ========================================
// TABLE 1: WOA & BW
// ========================================
const getBwTableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'woa',
    header: 'Week of Age',
    flex: 0.8,
    align: 'center',
    cell: ({ row }) => valueText(row.woa),
  },
  {
    key: 'bw',
    header: 'Body Weight',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.bw),
  },
  {
    key: 'std_bw',
    header: 'Std Body Weight',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.std_bw),
  },
  {
    key: 'uniformity',
    header: 'Uniformity',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.uniformity),
  },
  {
    key: 'std_uniformity',
    header: 'Std Uniformity',
    flex: 1.3,
    align: 'right',
    cell: ({ row }) => valueText(row.std_uniformity),
  },
];

// ========================================
// TABLE 2: DEPLESI
// ========================================
const getDepTableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'dep_kum',
    header: 'Depletion Cummulative',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.dep_kum),
  },
  {
    key: 'dep_std',
    header: 'Depletion Std',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.dep_std),
  },
];

// ========================================
// TABLE 3: BUTIRAN
// ========================================
const getButiranTableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'butiran_utuh',
    header: 'Utuh',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.butiran_utuh),
  },
  {
    key: 'butiran_putih',
    header: 'Putih',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.butiran_putih),
  },
  {
    key: 'butiran_retak',
    header: 'Retak',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.butiran_retak),
  },
  {
    key: 'butiran_pecah',
    header: 'Pecah',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.butiran_pecah),
  },
  {
    key: 'butiran_jumlah',
    header: 'Jumlah',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.butiran_jumlah),
  },
  {
    key: 'total_butir',
    header: 'Total Butir',
    flex: 1.3,
    align: 'right',
    cell: ({ row }) => valueText(row.total_butir),
  },
];

// ========================================
// TABLE 4: BERAT (KG)
// ========================================
const getKgTableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'kg_utuh',
    header: 'Utuh (Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.kg_utuh),
  },
  {
    key: 'kg_putih',
    header: 'Putih (Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.kg_putih),
  },
  {
    key: 'kg_retak',
    header: 'Retak (Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.kg_retak),
  },
  {
    key: 'kg_pecah',
    header: 'Pecah (Kg)',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.kg_pecah),
  },
  {
    key: 'kg_jumlah',
    header: 'Jumlah (Kg)',
    flex: 1.3,
    align: 'right',
    cell: ({ row }) => valueText(row.kg_jumlah),
  },
  {
    key: 'total_kg',
    header: 'Total (Kg)',
    flex: 1.3,
    align: 'right',
    cell: ({ row }) => valueText(row.total_kg),
  },
];

// ========================================
// TABLE 5: PERSENTASE
// ========================================
const getPersenTableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'persen_utuh',
    header: 'Utuh (%)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.persen_utuh),
  },
  {
    key: 'persen_putih',
    header: 'Putih (%)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.persen_putih),
  },
  {
    key: 'persen_retak',
    header: '% Retak (%)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.persen_retak),
  },
  {
    key: 'persen_pecah',
    header: '% Pecah (%)',
    flex: 1.5,
    align: 'right',
    cell: ({ row }) => valueText(row.persen_pecah),
  },
];

// ========================================
// TABLE 6: PRODUKSI (HD, FI, EM, EW)
// ========================================
const getProduksi1TableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'hd',
    header: 'Hen Day',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => valueText(row.hd),
  },
  {
    key: 'hd_std',
    header: 'Hen Day Std',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.hd_std),
  },
  {
    key: 'fi',
    header: 'Feed Intake',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => valueText(row.fi),
  },
  {
    key: 'fi_std',
    header: 'Feed Intake Std',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.fi_std),
  },
  {
    key: 'em',
    header: 'Egg Mass',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => valueText(row.em),
  },
  {
    key: 'em_std',
    header: 'Egg Mass Std',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.em_std),
  },
  {
    key: 'ew',
    header: 'Egg Weight',
    flex: 0.8,
    align: 'right',
    cell: ({ row }) => valueText(row.ew),
  },
  {
    key: 'ew_std',
    header: 'Egg Weight Std',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.ew_std),
  },
];

// ========================================
// TABLE 7: PRODUKSI (FCR, HH)
// ========================================
const getProduksi2TableColumns = (): PdfColumn<ProductionResult>[] => [
  {
    key: 'no',
    header: 'No',
    flex: 0.5,
    align: 'center',
    cell: ({ index }) => index + 1,
  },
  {
    key: 'fcr',
    header: 'FCR',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.fcr),
  },
  {
    key: 'fcr_std',
    header: 'FCR Std',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.fcr_std),
  },
  {
    key: 'hh',
    header: 'Hen House',
    flex: 1,
    align: 'right',
    cell: ({ row }) => valueText(row.hh),
  },
  {
    key: 'hh_std',
    header: 'Hen House Std',
    flex: 1.2,
    align: 'right',
    cell: ({ row }) => valueText(row.hh_std),
  },
];

/**
 * ✅ Main PDF Component
 */
const ProductionResultReportPDF = ({
  mappedProductionResults = [],
}: ProductionResultReportPDFProps) => {
  return (
    <Document>
      {mappedProductionResults.length === 0 ? (
        <Page style={styles.page} size='A4'>
          {/* Title and Parameters */}
          <View style={styles.titleSection}>
            <PdfTypography size='h1' variant='primary'>
              Laporan &gt; Production Result
            </PdfTypography>
            <View style={styles.parameterContainer}>
              <PdfParamBadge>
                Tanggal: {formatDate(Date.now(), 'DD MMMM YYYY')}
              </PdfParamBadge>
              <PdfParamBadge>
                Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
              </PdfParamBadge>
            </View>
          </View>

          <View style={{ marginTop: 16 }}>
            <Text style={styles.emptyText}>Tidak ada data.</Text>
          </View>

          <PdfPageNumber />
        </Page>
      ) : (
        mappedProductionResults.map((item, idx) => {
          const pfk = item.projectFlockKandang;

          const kandangName =
            pfk?.kandang?.name ?? `Kandang #${pfk?.kandang_id ?? idx + 1}`;

          const projectName = pfk?.project_flock?.name ?? '';

          const locationName = pfk?.project_flock?.location?.name ?? '';

          const areaName = pfk?.project_flock?.area?.name ?? '';

          const hasData =
            item.productionResult && item.productionResult.length > 0;

          return (
            <Page key={`pfk-${pfk?.id ?? idx}`} style={styles.page} size='A4'>
              {/* Title and Parameters */}
              <View style={styles.titleSection}>
                <PdfTypography size='h1' variant='primary'>
                  Laporan &gt; Production Result
                </PdfTypography>
                <View style={styles.parameterContainer}>
                  <PdfParamBadge>
                    Tanggal: {formatDate(Date.now(), 'DD MMMM YYYY')}
                  </PdfParamBadge>
                  <PdfParamBadge>
                    Dicetak: {formatDate(new Date(), 'DD MMM YYYY HH:mm')}
                  </PdfParamBadge>
                </View>
                <PdfTypography size='h2' variant='primary'>
                  {projectName
                    ? `${projectName} • ${kandangName}`
                    : kandangName}
                </PdfTypography>
                <PdfTypography size='label'>
                  {[areaName, locationName].filter(Boolean).join(' • ')}
                </PdfTypography>
              </View>

              {hasData ? (
                <>
                  {/* Table 1: WOA & BW */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>1. WOA & Body Weight</Text>
                    <PdfTable
                      columns={getBwTableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 2: Deplesi */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>2. Deplesi</Text>
                    <PdfTable
                      columns={getDepTableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 3: Butiran */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>3. Butiran</Text>
                    <PdfTable
                      columns={getButiranTableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 4: Berat (Kg) */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>4. Berat (Kg)</Text>
                    <PdfTable
                      columns={getKgTableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 5: Persentase */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>5. Persentase</Text>
                    <PdfTable
                      columns={getPersenTableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 6: Produksi (HD, FI, EM, EW) */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>
                      6. Produksi (HD, FI, EM, EW)
                    </Text>
                    <PdfTable
                      columns={getProduksi1TableColumns()}
                      data={item.productionResult!}
                    />
                  </View>

                  {/* Table 7: Produksi (FCR, HH) */}
                  <View style={styles.tableSection}>
                    <Text style={styles.tableTitle}>7. Produksi (FCR, HH)</Text>
                    <PdfTable
                      columns={getProduksi2TableColumns()}
                      data={item.productionResult!}
                    />
                  </View>
                </>
              ) : (
                <Text style={styles.emptyText}>
                  Tidak ada production result untuk kandang ini.
                </Text>
              )}

              <PdfPageNumber />
            </Page>
          );
        })
      )}
    </Document>
  );
};

export default ProductionResultReportPDF;
