import React from 'react';
import { Document, Page, Text, View, StyleSheet, Image, renderToBuffer } from '@react-pdf/renderer';
import { BOLETA_FONDO_BASE64 } from './boletaBg';

// Interfaz para los datos de la boleta
export interface BoletaData {
  id_boleta: number;
  num_boleta: number;
  fecha_emision: string;
  datos_apr: {
    nombre_servicio: string;
    rut_servicio: string;
    direccion_servicio: string;
    comuna_servicio: string;
    telefono_oficina: string;
    representante_legal: string;
    telefono_representante: string;
  };
  datos_cliente: {
    nombre_cliente: string;
    rut_cliente: string;
    direccion_cliente: string;
    sector: string;
  };
  datos_lectura: {
    lectura_anterior: number;
    lectura_actual: number;
    consumo_m3: number;
    fecha_toma_lectura: string;
    numero_medidor: string;
    mes_facturacion: string;
  };
  detalle_consumo: {
    tramo_base: number;
    valor_base: number;
    tramo1: number;
    valor_tramo1: number;
    tramo2: number;
    valor_tramo2: number;
    tramo3: number;
    valor_tramo3: number;
    total_consumo: number;
  };
  cargos: {
    cargo_fijo: number;
    alcantarillado: number;
    cuota_mortuoria: number;
    multas_atraso: number;
    donaciones: number;
    subsidio: number;
    repactacion: number;
  };
  totales: {
    total_mes_actual: number;
    saldo_anterior: number;
    total_boleta: number;
    fecha_vencimiento: string;
  };
}

// NOTE: Page size defined in component prop size={[700, 430]}
// Styles here should be strictly 100% or slightly less.
const styles = StyleSheet.create({
  page: {
    padding: 0, // CRITICAL: Prevent default margins
    backgroundColor: '#ffffff',
    fontFamily: 'Helvetica',
    fontSize: 7,
  },
  backgroundImage: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    zIndex: -1,
  },
  // Contenedor para UNA boleta (mitad izquierda o derecha)
  contentWrapper: {
    position: 'absolute',
    top: 0,
    width: 340,
    height: '100%',
  },
  // Posiciones relativas dentro del contentWrapper
  nombreServicio: { position: 'absolute', top: '6mm', left: '23mm', width: '60mm', fontSize: 8, fontWeight: 'bold', textAlign: 'left' },
  rutServicio: { position: 'absolute', top: '10mm', left: '32mm', width: '20mm', fontSize: 8, textAlign: 'left' },
  direccionServicio: { position: 'absolute', top: '16mm', left: '23mm', width: '40mm', fontSize: 7, textAlign: 'left' },
  telefonoServicio: { position: 'absolute', top: '19mm', left: '46mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  labelTelefono: { position: 'absolute', top: '19mm', left: '23mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  // ...
  fechaFacturacion: { position: 'absolute', top: '28mm', left: '85mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  fechaTomaLectura: { position: 'absolute', top: '31mm', left: '85mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  numBoleta: { position: 'absolute', top: '35mm', left: '20mm', width: '20mm', fontSize: 12, fontWeight: 'bold', textAlign: 'center' },

  nombreCliente: { position: 'absolute', top: '43mm', left: '18mm', width: '40mm', fontSize: 8, textAlign: 'left' },
  direccionCliente: { position: 'absolute', top: '46mm', left: '18mm', width: '40mm', fontSize: 7, textAlign: 'left' },
  rutCliente: { position: 'absolute', top: '49mm', left: '18mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  numMedidor: { position: 'absolute', top: '53mm', left: '21mm', width: '20mm', fontSize: 7, textAlign: 'left' },
  horarioAtencion: { position: 'absolute', top: '58mm', left: '49mm', width: '50mm', fontSize: 8, textAlign: 'left' },

  mesFacturacion: { position: 'absolute', top: '80mm', left: '25mm', width: '15mm', fontSize: 7, textAlign: 'left' },
  lecturaActual: { position: 'absolute', top: '80mm', left: '44mm', width: '8mm', fontSize: 7, textAlign: 'right' },
  lecturaAnterior: { position: 'absolute', top: '80mm', left: '56mm', width: '8mm', fontSize: 7, textAlign: 'right' },
  consumoM3: { position: 'absolute', top: '80mm', left: '69mm', width: '10mm', fontSize: 7, textAlign: 'right' },

  valorConsumo: { position: 'absolute', top: '85mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  valorCargoFijo: { position: 'absolute', top: '90mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelCargoFijo: { position: 'absolute', top: '90mm', left: '30mm', width: '10mm', fontSize: 7, textAlign: 'left' },
  valorAlcantarillado: { position: 'absolute', top: '94mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelAlcantarillado: { position: 'absolute', top: '94mm', left: '30mm', width: '10mm', fontSize: 7, textAlign: 'left' },
  valorMortuoria: { position: 'absolute', top: '98mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelMortuoria: { position: 'absolute', top: '98mm', left: '30mm', width: '10mm', fontSize: 7, textAlign: 'left' },
  valorMultaAtraso: { position: 'absolute', top: '102mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelMultaAtraso: { position: 'absolute', top: '102mm', left: '30mm', width: '10mm', fontSize: 7, textAlign: 'left' },
  valorTramoBase: { position: 'absolute', top: '106mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelTramoBase: { position: 'absolute', top: '106mm', left: '30mm', width: '15mm', fontSize: 7, fontWeight: 'bold', textAlign: 'left' },
  valorSobreconsumo: { position: 'absolute', top: '110mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelSobreconsumo: { position: 'absolute', top: '110mm', left: '30mm', width: '15mm', fontSize: 7, fontWeight: 'bold', textAlign: 'left' },
  valorSubsidio: { position: 'absolute', top: '117mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  labelSubsidio: { position: 'absolute', top: '117mm', left: '30mm', width: '15mm', fontSize: 7, textAlign: 'left' },
  valorTotalMesActual: { position: 'absolute', top: '121mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  valorSaldoAnterior: { position: 'absolute', top: '125mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  valorTotalBoleta: { position: 'absolute', top: '129mm', left: '103mm', width: '10mm', fontSize: 7, textAlign: 'right' },
  fechaVencimiento: { position: 'absolute', top: '122mm', left: '50mm', width: '10mm', fontSize: 7, fontWeight: 'bold', textAlign: 'right' },
  labelRepactacion: { position: 'absolute', top: '133mm', left: '70mm', width: '5mm', fontSize: 7, fontWeight: 'bold', textAlign: 'left' },
  valorRepactacion: { position: 'absolute', top: '133mm', left: '108mm', width: '5mm', fontSize: 7, textAlign: 'right' },
});

// Helpers
const formatMoney = (valor: number): string => {
  if (!valor || isNaN(valor)) return '$0';
  return new Intl.NumberFormat('es-CL', {
    style: 'currency',
    currency: 'CLP',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(valor);
};

const formatDate = (fecha: string): string => {
  if (!fecha) return '';
  try {
    const date = new Date(fecha);
    return date.toLocaleDateString('es-CL', { day: '2-digit', month: '2-digit', year: 'numeric' });
  } catch { return fecha; }
};

const getMesNombre = (fecha: string): string => {
  if (!fecha) return '';
  try {
    const date = new Date(fecha);
    return date.toLocaleDateString('es-CL', { month: 'long' }).toUpperCase();
  } catch { return ''; }
};

// Componente Boleta INDIVIDUAL
const BoletaContent: React.FC<{ boleta: BoletaData; leftOffset?: number }> = ({ boleta, leftOffset = 0 }) => {
  const sobreconsumo = boleta.detalle_consumo.valor_tramo1 + boleta.detalle_consumo.valor_tramo2 + boleta.detalle_consumo.valor_tramo3;

  const baseStyle = { ...styles.contentWrapper, left: leftOffset };

  return (
    <View style={baseStyle}>
      <Text style={styles.nombreServicio}>{boleta.datos_apr.nombre_servicio}</Text>
      <Text style={styles.rutServicio}>{boleta.datos_apr.rut_servicio}</Text>
      <Text style={styles.direccionServicio}>{boleta.datos_apr.direccion_servicio}</Text>
      <Text style={styles.labelTelefono}>Fono:</Text>
      <Text style={styles.telefonoServicio}>{boleta.datos_apr.telefono_oficina}</Text>
      <Text style={styles.fechaFacturacion}>{formatDate(boleta.fecha_emision)}</Text>
      <Text style={styles.fechaTomaLectura}>{formatDate(boleta.datos_lectura.fecha_toma_lectura)}</Text>
      <Text style={styles.numBoleta}>{boleta.num_boleta}</Text>
      <Text style={styles.nombreCliente}>{boleta.datos_cliente.nombre_cliente}</Text>
      <Text style={styles.direccionCliente}>{boleta.datos_cliente.direccion_cliente}</Text>
      <Text style={styles.rutCliente}>{boleta.datos_cliente.rut_cliente}</Text>
      <Text style={styles.numMedidor}>{boleta.datos_lectura.numero_medidor}</Text>
      <Text style={styles.horarioAtencion}>Lunes a Jueves de 09:00 a 13:00 hrs</Text>
      <Text style={styles.mesFacturacion}>{getMesNombre(boleta.fecha_emision)}</Text>
      <Text style={styles.lecturaActual}>{boleta.datos_lectura.lectura_actual}</Text>
      <Text style={styles.lecturaAnterior}>{boleta.datos_lectura.lectura_anterior}</Text>
      <Text style={styles.consumoM3}>{boleta.datos_lectura.consumo_m3}</Text>
      <Text style={styles.valorConsumo}>{formatMoney(boleta.detalle_consumo.total_consumo)}</Text>
      {boleta.cargos.cargo_fijo > 0 && (<><Text style={styles.labelCargoFijo}>Cargo Fijo</Text><Text style={styles.valorCargoFijo}>{formatMoney(boleta.cargos.cargo_fijo)}</Text></>)}
      {boleta.cargos.alcantarillado > 0 && (<><Text style={styles.labelAlcantarillado}>Alcantarillado</Text><Text style={styles.valorAlcantarillado}>{formatMoney(boleta.cargos.alcantarillado)}</Text></>)}
      {boleta.cargos.cuota_mortuoria > 0 && (<><Text style={styles.labelMortuoria}>Cuota Mortuoria</Text><Text style={styles.valorMortuoria}>{formatMoney(boleta.cargos.cuota_mortuoria)}</Text></>)}
      {boleta.cargos.multas_atraso > 0 && (<><Text style={styles.labelMultaAtraso}>Multa Atraso</Text><Text style={styles.valorMultaAtraso}>{formatMoney(boleta.cargos.multas_atraso)}</Text></>)}
      <Text style={styles.labelTramoBase}>Consumo Normal</Text>
      <Text style={styles.valorTramoBase}>{formatMoney(boleta.detalle_consumo.valor_base)}</Text>
      {sobreconsumo > 0 && (<><Text style={styles.labelSobreconsumo}>Sobreconsumo</Text><Text style={styles.valorSobreconsumo}>{formatMoney(sobreconsumo)}</Text></>)}
      {boleta.cargos.subsidio > 0 && (<><Text style={styles.labelSubsidio}>Subsidio</Text><Text style={styles.valorSubsidio}>-{formatMoney(boleta.cargos.subsidio)}</Text></>)}
      <Text style={styles.valorTotalMesActual}>{formatMoney(boleta.totales.total_mes_actual)}</Text>
      <Text style={styles.valorSaldoAnterior}>{formatMoney(boleta.totales.saldo_anterior)}</Text>
      <Text style={styles.valorTotalBoleta}>{formatMoney(boleta.totales.total_boleta)}</Text>
      <Text style={styles.fechaVencimiento}>{formatDate(boleta.totales.fecha_vencimiento)}</Text>
      {boleta.cargos.repactacion > 0 && (<><Text style={styles.labelRepactacion}>Repac.</Text><Text style={styles.valorRepactacion}>{formatMoney(boleta.cargos.repactacion)}</Text></>)}
    </View>
  );
};

// ... BoletaPDFDocument component
const BoletaPDFDocument: React.FC<{ boleta: BoletaData }> = ({ boleta }) => {
  // Usar imagen en Base64 para evitar problemas de rutas/protocolos en servidor
  const backgroundImagePath = BOLETA_FONDO_BASE64;

  return (
    <Document>
      {/* Use size slightly larger than content to avoid wrapping */}
      <Page size={[710, 450]} style={styles.page}>
        <Image src={backgroundImagePath} style={styles.backgroundImage} />
        {/* Boleta Izquierda (Original) */}
        <BoletaContent boleta={boleta} leftOffset={0} />
        {/* Boleta Derecha (Duplicado) */}
        <BoletaContent boleta={boleta} leftOffset={355} />
      </Page>
    </Document>
  );
};

// Función para generar el PDF como Buffer (compatible con Node.js)
export const generateBoletaPDFServer = async (boleta: BoletaData): Promise<Buffer> => {
  const doc = <BoletaPDFDocument boleta={boleta} />;
  return await renderToBuffer(doc);
};
