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

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',
  },
  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: 8,
    textAlign: 'left',
  },
  tableCellHeader: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    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: 8,
    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: 8,
    textAlign: 'right',
  },
  tableCellCenter: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'center',
  },
  tableBorderBottom: {
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
  },
  supplierSection: {
    marginBottom: 10,
  },
  supplierSectionBreak: {
    marginBottom: 15,
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
});

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

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.supplierSection}>
          <Text style={pdfStyles.supplierTitle}>Rekapitulasi</Text>

          <View style={pdfStyles.table}>
            {/* Table Header */}
            <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>Rentang BW</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
                <Text>Sisa Butir</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
                <Text>Sisa Kg</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Rata-Rata Bobot (Kg)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
                <Text>Feed (Supplier)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>DOC (Supplier)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Rata-Rata Harga DOC</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>HPP Telur (RP/KG)</Text>
              </View>
              <View
                style={[
                  pdfStyles.tableCellHeaderRight,
                  { flex: 1.2, borderRightWidth: 0 },
                ]}
              >
                <Text>Nominal Sisa</Text>
              </View>
            </View>

            {/* Table Body - Rekapitulasi */}
            {rekapitulasiByWeightRange.map(
              (group: HppPerKandangPerWeightRange, index: number) => (
                <View
                  key={index}
                  style={[
                    pdfStyles.tableRow,
                    index < rekapitulasiByWeightRange.length - 1
                      ? pdfStyles.tableBorderBottom
                      : {},
                  ]}
                >
                  <View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
                    <Text>{group.label}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                    <Text>{formatNumber(group.egg_production_pieces)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                    <Text>{formatNumber(group.egg_production_kg)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatNumber(group.avg_weight_kg)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                    <Text>
                      {group.feed_suppliers
                        ?.map(
                          (s: { alias?: string; name: string }) =>
                            s.alias || s.name
                        )
                        .join(' | ') || '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                    <Text>
                      {group.doc_suppliers
                        ?.map(
                          (s: { alias?: string; name: string }) =>
                            s.alias || s.name
                        )
                        .join(' | ') || '-'}
                    </Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(group.average_doc_price_rp)}</Text>
                  </View>
                  <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                    <Text>{formatCurrency(group.egg_hpp_rp_per_kg)}</Text>
                  </View>
                  <View
                    style={[
                      pdfStyles.tableCellRight,
                      { flex: 1.2, borderRightWidth: 0 },
                    ]}
                  >
                    <Text>{formatCurrency(group.egg_value_rp)}</Text>
                  </View>
                </View>
              )
            )}
          </View>
        </View>

        {/* Detail Per Kandang Section */}
        <View style={pdfStyles.supplierSectionBreak}>
          <Text style={pdfStyles.supplierTitle}>Detail Per Kandang</Text>

          <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>Kandang</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>Rentang BW</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
                <Text>Rata-Rata Bobot (Kg)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
                <Text>Sisa Butir</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
                <Text>Sisa Kg (Telur)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
                <Text>Feed (Supplier)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
                <Text>DOC (Supplier)</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
                <Text>Rata-Rata Harga DOC</Text>
              </View>
              <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
                <Text>HPP Telur (RP/KG)</Text>
              </View>
              <View
                style={[
                  pdfStyles.tableCellHeaderRight,
                  { flex: 1.2, borderRightWidth: 0 },
                ]}
              >
                <Text>Nominal Sisa</Text>
              </View>
            </View>

            {/* Table Body - Detail Per Kandang */}
            {data.rows.map((item: HppPerKandangRow, index: number) => (
              <View
                key={index}
                style={[pdfStyles.tableRow, pdfStyles.tableBorderBottom]}
              >
                <View style={[pdfStyles.tableCellCenter, { flex: 0.5 }]}>
                  <Text>{index + 1}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                  <Text>{item.kandang?.name || '-'}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text>
                    {item.weight_range.weight_min.toFixed(2)} -{' '}
                    {item.weight_range.weight_max.toFixed(2)}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                  <Text>{formatNumber(item.avg_weight_kg)}</Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text>{formatNumber(item.egg_production_pieces)}</Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
                  <Text>{formatNumber(item.egg_production_kg)}</Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                  <Text>
                    {item.feed_suppliers
                      ?.map(
                        (s: { alias?: string; name: string }) =>
                          s.alias || s.name
                      )
                      .join(' | ')}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCell, { flex: 1 }]}>
                  <Text>
                    {item.doc_suppliers
                      ?.map(
                        (s: { alias?: string; name: string }) =>
                          s.alias || s.name
                      )
                      .join(' | ')}
                  </Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                  <Text>{formatCurrency(item.average_doc_price_rp)}</Text>
                </View>
                <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                  <Text>{formatCurrency(item.egg_hpp_rp_per_kg)}</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellRight,
                    { flex: 1.2, borderRightWidth: 0 },
                  ]}
                >
                  <Text>{formatCurrency(item.egg_value_rp)}</Text>
                </View>
              </View>
            ))}

            {/* TOTAL Row */}
            {data.summary?.total && (
              <View style={pdfStyles.tableRow}>
                <View
                  style={[
                    pdfStyles.tableCellHeader,
                    {
                      flex: 0.5,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>TOTAL</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeader,
                    {
                      flex: 1.5,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>ALL</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeader,
                    {
                      flex: 1,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>-</Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 1,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatNumber(data.summary.total.average_weight_kg)}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 0.8,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatNumber(
                      data.summary.total.total_egg_production_pieces
                    )}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 0.8,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatNumber(data.summary.total.total_egg_production_kg)}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeader,
                    {
                      flex: 1.2,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {data.rows
                      .flatMap((row: HppPerKandangRow) =>
                        row.feed_suppliers?.map(
                          (s: { alias?: string; name: string }) =>
                            s.alias || s.name
                        )
                      )
                      .filter(
                        (v: string, i: number, a: string[]) =>
                          a.indexOf(v) === i
                      )
                      .join(' | ') || '-'}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeader,
                    {
                      flex: 1,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {data.rows
                      .flatMap((row: HppPerKandangRow) =>
                        row.doc_suppliers?.map(
                          (s: { alias?: string; name: string }) =>
                            s.alias || s.name
                        )
                      )
                      .filter(
                        (v: string, i: number, a: string[]) =>
                          a.indexOf(v) === i
                      )
                      .join(' | ') || '-'}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 1.2,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(
                      data.summary.total.total_average_doc_price_rp
                    )}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 1,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(
                      data.summary.total.average_egg_hpp_rp_per_kg
                    )}
                  </Text>
                </View>
                <View
                  style={[
                    pdfStyles.tableCellHeaderRight,
                    {
                      flex: 1.2,
                      backgroundColor: '#F5F5F5',
                      borderBottomWidth: 0,
                      borderRightWidth: 0,
                    },
                  ]}
                >
                  <Text>
                    {formatCurrency(data.summary.total.total_egg_value_rp)}
                  </Text>
                </View>
              </View>
            )}
          </View>
        </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;
  }
};
