/**
 * Quotation PDF Service
 * Generates a PDF buffer from a quotation using @react-pdf/renderer (v4)
 */

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

// ═══════════════════════════════════════════════════════════════════════
// Input type
// ═══════════════════════════════════════════════════════════════════════

export interface PdfQuotationInput {
  quotationNumber: string;
  title: string;
  createdAt: Date;
  dueDate?: Date | null;
  total: number;
  currency: string;
  taxRate?: number | null;
  discountRate?: number | null;
  portalToken?: string | null;
  customer?: {
    name?: string | null;
    email?: string | null;
    phone?: string | null;
  } | null;
  items?: Array<{
    description: string;
    quantity: number;
    unitPrice: number;
    total: number;
  }>;
}

// ═══════════════════════════════════════════════════════════════════════
// Styles
// ═══════════════════════════════════════════════════════════════════════

const styles = StyleSheet.create({
  page:         { padding: 40, fontSize: 11, fontFamily: 'Helvetica', color: '#111827' },
  header:       { marginBottom: 20 },
  title:        { fontSize: 20, fontFamily: 'Helvetica-Bold', marginBottom: 4 },
  subtitle:     { fontSize: 12, color: '#6b7280' },
  section:      { marginBottom: 14 },
  sectionTitle: { fontSize: 11, fontFamily: 'Helvetica-Bold', marginBottom: 6, color: '#374151' },
  row:          { flexDirection: 'row', marginBottom: 3 },
  label:        { width: 110, color: '#6b7280', fontSize: 10 },
  value:        { flex: 1, fontSize: 10 },
  tableHeader:  { flexDirection: 'row', backgroundColor: '#f9fafb', padding: 6, borderBottomWidth: 1, borderBottomColor: '#e5e7eb' },
  tableRow:     { flexDirection: 'row', padding: 5, borderBottomWidth: 1, borderBottomColor: '#f3f4f6' },
  colDesc:      { flex: 3, fontSize: 10 },
  colNum:       { flex: 1, textAlign: 'right', fontSize: 10 },
  colNumBold:   { flex: 1, textAlign: 'right', fontSize: 10, fontFamily: 'Helvetica-Bold' },
  totalsBox:    { marginTop: 8, alignItems: 'flex-end' },
  totalRow:     { flexDirection: 'row', marginBottom: 3 },
  totalLabel:   { width: 110, color: '#6b7280', fontSize: 10 },
  totalValue:   { width: 80, textAlign: 'right', fontSize: 10 },
  grandLabel:   { width: 110, fontSize: 12, fontFamily: 'Helvetica-Bold', color: '#16a34a' },
  grandValue:   { width: 80, textAlign: 'right', fontSize: 12, fontFamily: 'Helvetica-Bold', color: '#16a34a' },
  divider:      { borderBottomWidth: 1, borderBottomColor: '#e5e7eb', marginVertical: 10 },
  footer:       { marginTop: 20, borderTopWidth: 1, borderTopColor: '#e5e7eb', paddingTop: 10, color: '#6b7280', fontSize: 9 },
});

// ═══════════════════════════════════════════════════════════════════════
// PDF Document component
// ═══════════════════════════════════════════════════════════════════════

function QuotationPdf({ q }: { q: PdfQuotationInput }) {
  const fmt = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: (q.currency || 'QAR').toUpperCase(),
    minimumFractionDigits: 2,
  });

  const baseUrl = process.env.NEXTAUTH_URL ?? 'http://localhost:9000';
  const portalUrl = q.portalToken ? `${baseUrl}/quotation/${q.portalToken}` : null;

  const discountAmount = q.discountRate ? q.total * q.discountRate / 100 : 0;
  const taxAmount = q.taxRate ? (q.total - discountAmount) * q.taxRate / 100 : 0;

  return (
    <Document>
      <Page size="A4" style={styles.page}>

        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.title}>{q.title}</Text>
          <Text style={styles.subtitle}>Quotation #{q.quotationNumber}</Text>
        </View>

        <View style={styles.divider} />

        {/* Dates */}
        <View style={styles.section}>
          <View style={styles.row}>
            <Text style={styles.label}>Date Issued:</Text>
            <Text style={styles.value}>{q.createdAt.toLocaleDateString('en-GB')}</Text>
          </View>
          {q.dueDate && (
            <View style={styles.row}>
              <Text style={styles.label}>Payment Due:</Text>
              <Text style={styles.value}>{q.dueDate.toLocaleDateString('en-GB')}</Text>
            </View>
          )}
        </View>

        {/* Customer */}
        {q.customer && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>CUSTOMER</Text>
            {q.customer.name  && <View style={styles.row}><Text style={styles.label}>Name:</Text><Text style={styles.value}>{q.customer.name}</Text></View>}
            {q.customer.email && <View style={styles.row}><Text style={styles.label}>Email:</Text><Text style={styles.value}>{q.customer.email}</Text></View>}
            {q.customer.phone && <View style={styles.row}><Text style={styles.label}>Phone:</Text><Text style={styles.value}>{q.customer.phone}</Text></View>}
          </View>
        )}

        <View style={styles.divider} />

        {/* Line items */}
        {q.items && q.items.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>ITEMS</Text>
            <View style={styles.tableHeader}>
              <Text style={[styles.colDesc, { fontFamily: 'Helvetica-Bold' }] as Style[]}>Description</Text>
              <Text style={[styles.colNum,  { fontFamily: 'Helvetica-Bold' }] as Style[]}>Qty</Text>
              <Text style={[styles.colNum,  { fontFamily: 'Helvetica-Bold' }] as Style[]}>Unit Price</Text>
              <Text style={[styles.colNum,  { fontFamily: 'Helvetica-Bold' }] as Style[]}>Total</Text>
            </View>
            {q.items.map((item, i) => (
              <View key={i} style={styles.tableRow}>
                <Text style={styles.colDesc}>{item.description}</Text>
                <Text style={styles.colNum}>{item.quantity}</Text>
                <Text style={styles.colNum}>{fmt.format(item.unitPrice)}</Text>
                <Text style={styles.colNumBold}>{fmt.format(item.total)}</Text>
              </View>
            ))}
          </View>
        )}

        {/* Totals */}
        <View style={styles.totalsBox}>
          {discountAmount > 0 && (
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>Discount ({q.discountRate}%):</Text>
              <Text style={styles.totalValue}>-{fmt.format(discountAmount)}</Text>
            </View>
          )}
          {taxAmount > 0 && (
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>Tax ({q.taxRate}%):</Text>
              <Text style={styles.totalValue}>{fmt.format(taxAmount)}</Text>
            </View>
          )}
          <View style={styles.totalRow}>
            <Text style={styles.grandLabel}>Total:</Text>
            <Text style={styles.grandValue}>{fmt.format(q.total)}</Text>
          </View>
        </View>

        <View style={styles.divider} />

        {/* Footer */}
        <View style={styles.footer}>
          {portalUrl && <Text>View & Pay: {portalUrl}</Text>}
          <Text style={{ marginTop: 6 }}>{'© '}{new Date().getFullYear()} Mawidi. All rights reserved.</Text>
        </View>

      </Page>
    </Document>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Public API
// ═══════════════════════════════════════════════════════════════════════

/**
 * Generate a PDF buffer for a quotation.
 * Returns a Buffer that can be attached to an email or streamed to the client.
 */
export async function generateQuotationPdf(quotation: PdfQuotationInput): Promise<Buffer> {
  const buffer = await renderToBuffer(<QuotationPdf q={quotation} />);
  return Buffer.from(buffer);
}
