import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import PDFDocument from 'pdfkit';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { type CrmActor } from '../../common/crm/crm-record.helper';
import { CreateQuoteDto, CreateQuoteItemDto } from './dto/create-quote.dto';
import { UpdateQuoteDto } from './dto/update-quote.dto';
import { GetQuotesQuery } from './dto/get-quotes.query';

import { NumberingService } from '../numbering/numbering.service';
import { AuditService } from '../audit/audit.service';

@Injectable()
export class QuotesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
    private readonly numbering: NumberingService,
    private readonly audit: AuditService,
  ) {}

  // Helper to compute line item amounts and quote totals
  private computeTotals(items: CreateQuoteItemDto[]) {
    let subtotal = 0;
    let discountTotal = 0;
    let taxTotal = 0;

    const computedItems = items.map((it, idx) => {
      const qty = Math.max(0.01, it.quantity ?? 1);
      const rate = Math.max(0, it.unitPrice ?? 0);
      const discPct = Math.min(100, Math.max(0, it.discountPercent ?? 0));
      const gstRate = Math.min(100, Math.max(0, it.gstRate ?? 18.0));

      const lineGross = qty * rate;
      const lineDisc = lineGross * (discPct / 100);
      const lineTaxable = lineGross - lineDisc;
      const lineTax = lineTaxable * (gstRate / 100);
      const lineTotal = lineTaxable + lineTax;

      subtotal += lineGross;
      discountTotal += lineDisc;
      taxTotal += lineTax;

      return {
        productId: it.productId || null,
        name: it.name.trim(),
        description: it.description?.trim() || null,
        quantity: qty,
        unitPrice: rate,
        discountPercent: discPct,
        gstRate,
        lineTotal,
        orderIndex: idx,
      };
    });

    const totalAmount = subtotal - discountTotal + taxTotal;

    return {
      items: computedItems,
      subtotal,
      discountTotal,
      taxTotal,
      totalAmount,
    };
  }

  // Generates unique quote sequence number via NumberingService
  private async generateQuoteNumber(tenantId: string): Promise<string> {
    return this.numbering.getNextNumber(tenantId, 'QUOTE');
  }

  // Returns list of quotes with filter tabs and summary strip
  async list(ctx: RequestTenantContext, q: GetQuotesQuery) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const page = Math.max(1, q.page || 1);
    const limit = Math.min(100, Math.max(1, q.limit || 25));
    const skip = (page - 1) * limit;

    const where: Prisma.QuoteWhereInput = {
      tenantId,
    };

    if (q.status) {
      where.status = q.status;
    }

    if (q.accountId) {
      where.accountId = q.accountId;
    }

    if (q.dealId) {
      where.dealId = q.dealId;
    }

    if (q.ownerId) {
      where.ownerId = q.ownerId;
    }

    if (q.search?.trim()) {
      const term = q.search.trim();
      where.OR = [{ quoteNumber: { contains: term } }, { account: { name: { contains: term } } }, { deal: { title: { contains: term } } }];
    }

    const [total, data, stats] = await Promise.all([
      this.prisma.quote.count({ where }),
      this.prisma.quote.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ createdAt: 'desc' }],
        include: {
          account: { select: { id: true, name: true } },
          deal: { select: { id: true, title: true } },
          contact: { select: { id: true, name: true, email: true } },
          owner: { select: { id: true, name: true, email: true } },
          _count: { select: { items: true, invoices: true } },
        },
      }),
      this.prisma.quote.groupBy({
        by: ['status'],
        where: { tenantId },
        _count: { _all: true },
        _sum: { totalAmount: true },
      }),
    ]);

    const summary = {
      allCount: 0,
      allTotal: 0,
      sentCount: 0,
      sentTotal: 0,
      acceptedCount: 0,
      acceptedTotal: 0,
      draftCount: 0,
      draftTotal: 0,
    };

    stats.forEach((s: any) => {
      const count = s._count?._all ?? s._count ?? 0;
      const sum = s._sum?.totalAmount || 0;
      summary.allCount += count;
      summary.allTotal += sum;

      if (s.status === 'SENT') {
        summary.sentCount = count;
        summary.sentTotal = sum;
      } else if (s.status === 'ACCEPTED') {
        summary.acceptedCount = count;
        summary.acceptedTotal = sum;
      } else if (s.status === 'DRAFT') {
        summary.draftCount = count;
        summary.draftTotal = sum;
      }
    });

    return {
      data,
      summary,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
    };
  }

  // Returns full quote record with line items
  async get(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const quote = await this.prisma.quote.findFirst({
      where: { id, tenantId },
      include: {
        account: { select: { id: true, name: true, phone: true, website: true, city: true } },
        deal: { select: { id: true, title: true, amount: true, dealNumber: true } },
        contact: { select: { id: true, name: true, email: true, phone: true, title: true } },
        owner: { select: { id: true, name: true, email: true } },
        items: {
          orderBy: { orderIndex: 'asc' },
          include: {
            product: { select: { id: true, name: true, sku: true, unit: true, hsnSac: true } },
          },
        },
        invoices: {
          select: { id: true, invoiceNumber: true, status: true, totalAmount: true, paidAmount: true },
        },
      },
    });

    if (!quote) {
      throw new NotFoundException('Quote not found');
    }

    return quote;
  }

  // Creates a new quote proposal with line items
  async create(ctx: RequestTenantContext, dto: CreateQuoteDto, actor?: CrmActor) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);

    const account = await this.prisma.customer.findFirst({
      where: { id: dto.accountId, tenantId },
    });
    if (!account) {
      throw new NotFoundException('Account not found in your organization');
    }

    if (dto.dealId) {
      const deal = await this.prisma.deal.findFirst({
        where: { id: dto.dealId, tenantId },
      });
      if (!deal) {
        throw new NotFoundException('Deal not found in your organization');
      }
    }

    if (dto.contactId) {
      const contact = await this.prisma.contact.findFirst({
        where: { id: dto.contactId, tenantId },
      });
      if (!contact) {
        throw new NotFoundException('Contact not found in your organization');
      }
    }

    const quoteNumber = dto.quoteNumber?.trim() || (await this.generateQuoteNumber(tenantId));

    const existing = await this.prisma.quote.findUnique({
      where: {
        tenantId_quoteNumber_version: {
          tenantId,
          quoteNumber,
          version: 1,
        },
      },
    });

    if (existing) {
      throw new ConflictException(`Quote number "${quoteNumber}" already exists`);
    }

    const computed = this.computeTotals(dto.items || []);

    return this.prisma.quote.create({
      data: {
        tenantId,
        quoteNumber,
        version: 1,
        status: 'DRAFT',
        serviceName: dto.serviceName?.trim() || null,
        accountId: dto.accountId,
        dealId: dto.dealId || null,
        contactId: dto.contactId || null,
        ownerId: dto.ownerId || actor?.id || null,
        issueDate: dto.issueDate ? new Date(dto.issueDate) : new Date(),
        expiryDate: new Date(dto.expiryDate),
        subtotal: computed.subtotal,
        discountTotal: computed.discountTotal,
        taxTotal: computed.taxTotal,
        totalAmount: computed.totalAmount,
        notes: dto.notes?.trim() || null,
        terms: dto.terms?.trim() || null,
        items: {
          create: computed.items.map((it) => ({
            productId: it.productId,
            name: it.name,
            description: it.description,
            quantity: it.quantity,
            unitPrice: it.unitPrice,
            discountPercent: it.discountPercent,
            gstRate: it.gstRate,
            lineTotal: it.lineTotal,
            orderIndex: it.orderIndex,
          })),
        },
      },
      include: {
        account: { select: { id: true, name: true } },
        items: true,
      },
    });
  }

  // Updates quote status or line items (when in DRAFT)
  async update(ctx: RequestTenantContext, id: string, dto: UpdateQuoteDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.get(ctx, id);

    let computed: ReturnType<typeof this.computeTotals> | undefined;

    if (dto.items && dto.items.length > 0) {
      if (existing.status !== 'DRAFT') {
        throw new BadRequestException('Line items can only be modified when the quote is in Draft status. Create a revision instead.');
      }
      computed = this.computeTotals(dto.items);
    }

    return this.prisma.$transaction(async (tx) => {
      if (computed) {
        await tx.quoteItem.deleteMany({
          where: { quoteId: id, tenantId },
        });

        await tx.quoteItem.createMany({
          data: computed.items.map((it) => ({
            ...it,
            tenantId,
            quoteId: id,
          })),
        });
      }

      return tx.quote.update({
        where: { id },
        data: {
          status: dto.status,
          serviceName: dto.serviceName !== undefined ? dto.serviceName?.trim() || null : undefined,
          contactId: dto.contactId !== undefined ? dto.contactId : undefined,
          ownerId: dto.ownerId !== undefined ? dto.ownerId : undefined,
          expiryDate: dto.expiryDate ? new Date(dto.expiryDate) : undefined,
          notes: dto.notes !== undefined ? dto.notes?.trim() || null : undefined,
          terms: dto.terms !== undefined ? dto.terms?.trim() || null : undefined,
          subtotal: computed ? computed.subtotal : undefined,
          discountTotal: computed ? computed.discountTotal : undefined,
          taxTotal: computed ? computed.taxTotal : undefined,
          totalAmount: computed ? computed.totalAmount : undefined,
        },
        include: {
          account: { select: { id: true, name: true } },
          deal: { select: { id: true, title: true } },
          contact: { select: { id: true, name: true, email: true } },
          items: true,
        },
      });
    });
  }

  // Creates a revised new version of a quote (version + 1 in DRAFT status)
  async revise(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const original = await this.get(ctx, id);

    const highest = await this.prisma.quote.findFirst({
      where: {
        tenantId,
        quoteNumber: original.quoteNumber,
      },
      orderBy: { version: 'desc' },
      select: { version: true },
    });

    const nextVersion = (highest?.version || original.version) + 1;

    return this.prisma.quote.create({
      data: {
        tenantId,
        quoteNumber: original.quoteNumber,
        version: nextVersion,
        status: 'DRAFT',
        serviceName: original.serviceName,
        accountId: original.accountId,
        dealId: original.dealId,
        contactId: original.contactId,
        ownerId: original.ownerId,
        issueDate: new Date(),
        expiryDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // Default 30 days
        subtotal: original.subtotal,
        discountTotal: original.discountTotal,
        taxTotal: original.taxTotal,
        totalAmount: original.totalAmount,
        notes: original.notes,
        terms: original.terms,
        items: {
          create: original.items.map((it) => ({
            productId: it.productId,
            name: it.name,
            description: it.description,
            quantity: it.quantity,
            unitPrice: it.unitPrice,
            discountPercent: it.discountPercent,
            gstRate: it.gstRate,
            lineTotal: it.lineTotal,
            orderIndex: it.orderIndex,
          })),
        },
      },
      include: {
        account: { select: { id: true, name: true } },
        items: true,
      },
    });
  }

  // Deletes quote if not linked to any invoice
  async delete(ctx: RequestTenantContext, id: string) {
    const quote = await this.get(ctx, id);

    if (quote.invoices && quote.invoices.length > 0) {
      throw new BadRequestException('Cannot delete quote that has been converted into invoices.');
    }

    await this.prisma.quote.delete({
      where: { id: quote.id },
    });

    return { success: true, message: `Quote "${quote.quoteNumber} v${quote.version}" deleted successfully` };
  }

  // Generates a professional branded PDF for the quote proposal
  async generatePdf(ctx: RequestTenantContext, id: string): Promise<{ buffer: Buffer; filename: string }> {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const [quote, org] = await Promise.all([
      this.prisma.quote.findFirst({
        where: { id, tenantId },
        include: {
          account: { select: { id: true, name: true, phone: true, website: true, city: true } },
          deal: { select: { id: true, title: true, dealNumber: true } },
          contact: { select: { id: true, name: true, email: true, phone: true } },
          owner: { select: { id: true, name: true, email: true } },
          items: {
            orderBy: { orderIndex: 'asc' },
          },
        },
      }),
      this.prisma.organization.findUnique({
        where: { id: tenantId },
        select: {
          name: true,
          legalName: true,
          addressLine1: true,
          addressLine2: true,
          city: true,
          postalCode: true,
          country: true,
          gstin: true,
          pan: true,
          defaultTerms: true,
        },
      }),
    ]);

    if (!quote) {
      throw new NotFoundException('Quote not found');
    }

    const doc = new PDFDocument({ size: 'A4', margin: 40, bufferPages: true });
    const buffers: Buffer[] = [];
    doc.on('data', (chunk) => buffers.push(chunk));

    const orgName = org?.legalName || org?.name || 'TechCMantix CRM';
    const formatINR = (val: number | string | Prisma.Decimal) => `Rs. ${Number(val || 0).toLocaleString('en-IN', { maximumFractionDigits: 2 })}`;
    const formatDate = (d: Date | string) => new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });

    // Header banner
    doc.save();
    doc.rect(40, 40, 515, 65).fill('#0f172a');
    doc.fillColor('#ffffff').fontSize(16).font('Helvetica-Bold').text(orgName.toUpperCase(), 55, 52);

    const orgMeta = [org?.city, org?.gstin ? `GSTIN: ${org.gstin}` : null, org?.pan ? `PAN: ${org.pan}` : null].filter(Boolean).join('  |  ');
    doc
      .fontSize(8)
      .font('Helvetica')
      .fillColor('#94a3b8')
      .text(orgMeta || 'Official Quotation Proposal', 55, 74);

    doc.fontSize(16).font('Helvetica-Bold').fillColor('#f59e0b').text('QUOTATION', 350, 52, { align: 'right', width: 190 });
    doc.fontSize(9).font('Helvetica-Bold').fillColor('#ffffff').text(`${quote.quoteNumber} (v${quote.version})`, 350, 72, { align: 'right', width: 190 });
    doc.fontSize(8).font('Helvetica').fillColor('#cbd5e1').text(`Status: ${quote.status}`, 350, 86, { align: 'right', width: 190 });
    doc.restore();

    let y = 120;

    // Billed To & Quote Info Columns
    doc.save();
    doc.roundedRect(40, y, 250, 85, 4).fillAndStroke('#f8fafc', '#e2e8f0');
    doc
      .fillColor('#64748b')
      .fontSize(7.5)
      .font('Helvetica-Bold')
      .text('PREPARED FOR', 52, y + 10);
    doc
      .fillColor('#0f172a')
      .fontSize(11)
      .font('Helvetica-Bold')
      .text(quote.account?.name || 'Customer', 52, y + 24, { width: 226 });

    const contactLines: string[] = [];
    if (quote.contact?.name) contactLines.push(`Attn: ${quote.contact.name}`);
    if (quote.contact?.email) contactLines.push(quote.contact.email);
    if (quote.account?.city) contactLines.push(quote.account.city);
    doc
      .fillColor('#475569')
      .fontSize(8.5)
      .font('Helvetica')
      .text(contactLines.join('  ·  ') || 'Valued Client', 52, y + 44, { width: 226 });

    doc.roundedRect(305, y, 250, 85, 4).fillAndStroke('#f8fafc', '#e2e8f0');
    doc
      .fillColor('#64748b')
      .fontSize(7.5)
      .font('Helvetica-Bold')
      .text('QUOTE DETAILS', 317, y + 10);

    const metaRows: [string, string][] = [
      ['Issue Date:', formatDate(quote.issueDate)],
      ['Valid Until:', formatDate(quote.expiryDate)],
    ];
    if (quote.serviceName) {
      metaRows.push(['Service Required:', quote.serviceName]);
    }
    if (quote.deal?.title) {
      metaRows.push(['Deal:', quote.deal.title]);
    }
    if (quote.owner?.name) {
      metaRows.push(['Prepared By:', quote.owner.name]);
    }

    let metaY = y + 24;
    metaRows.forEach(([lbl, val]) => {
      doc.fillColor('#64748b').fontSize(8.5).font('Helvetica').text(lbl, 317, metaY);
      doc.fillColor('#0f172a').fontSize(8.5).font('Helvetica-Bold').text(val, 390, metaY, { width: 155, align: 'right' });
      metaY += 16;
    });
    doc.restore();

    y = 220;

    // Items Table Header
    const cols = [
      { label: '#', x: 40, width: 25, align: 'center' },
      { label: 'ITEM / SERVICE DESCRIPTION', x: 65, width: 240, align: 'left' },
      { label: 'QTY', x: 305, width: 45, align: 'right' },
      { label: 'RATE', x: 350, width: 65, align: 'right' },
      { label: 'GST', x: 415, width: 45, align: 'right' },
      { label: 'AMOUNT', x: 460, width: 95, align: 'right' },
    ];

    doc.save();
    doc.rect(40, y, 515, 22).fill('#1e293b');
    cols.forEach((col) => {
      doc
        .fillColor('#ffffff')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text(col.label, col.x + 3, y + 7, {
          width: col.width - 6,
          align: col.align as any,
        });
    });
    doc.restore();

    y += 22;

    // Items Table Rows
    quote.items.forEach((item, idx) => {
      const isEven = idx % 2 === 0;
      const rowHeight = item.description ? 34 : 24;

      doc.save();
      if (!isEven) {
        doc.rect(40, y, 515, rowHeight).fill('#f8fafc');
      }
      doc.strokeColor('#e2e8f0').lineWidth(0.5).rect(40, y, 515, rowHeight).stroke();

      doc
        .fillColor('#64748b')
        .fontSize(8.5)
        .font('Helvetica')
        .text(String(idx + 1), cols[0].x + 3, y + 7, {
          width: cols[0].width - 6,
          align: 'center',
        });

      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(item.name, cols[1].x + 3, y + 6, {
          width: cols[1].width - 6,
          align: 'left',
        });
      if (item.description) {
        doc
          .fillColor('#64748b')
          .fontSize(7.5)
          .font('Helvetica')
          .text(item.description, cols[1].x + 3, y + 18, {
            width: cols[1].width - 6,
            align: 'left',
          });
      }

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(String(Number(item.quantity)), cols[2].x + 3, y + 7, {
          width: cols[2].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(formatINR(item.unitPrice), cols[3].x + 3, y + 7, {
          width: cols[3].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(`${Number(item.gstRate)}%`, cols[4].x + 3, y + 7, {
          width: cols[4].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(formatINR(item.lineTotal), cols[5].x + 3, y + 7, {
          width: cols[5].width - 6,
          align: 'right',
        });

      doc.restore();
      y += rowHeight;
    });

    y += 15;

    // Totals Box on Right
    const totalsBoxY = y;
    const totalsWidth = 220;
    const totalsX = 555 - totalsWidth;

    doc.save();
    doc.roundedRect(totalsX, totalsBoxY, totalsWidth, 110, 4).fillAndStroke('#f8fafc', '#e2e8f0');

    const totRows: [string, string][] = [['Subtotal:', formatINR(quote.subtotal)], ...(Number(quote.discountTotal) > 0 ? ([['Discount:', `- ${formatINR(quote.discountTotal)}`]] as [string, string][]) : []), ['GST Tax:', formatINR(quote.taxTotal)], ['Total Quote Value:', formatINR(quote.totalAmount)]];

    let tY = totalsBoxY + 12;
    totRows.forEach(([lbl, val]) => {
      const isGrand = lbl === 'Total Quote Value:';

      if (isGrand) {
        doc
          .strokeColor('#cbd5e1')
          .lineWidth(0.5)
          .moveTo(totalsX + 10, tY - 3)
          .lineTo(totalsX + totalsWidth - 10, tY - 3)
          .stroke();
      }

      const font = isGrand ? 'Helvetica-Bold' : 'Helvetica';
      const size = isGrand ? 10 : 8.5;
      const color = isGrand ? '#0f172a' : '#475569';

      doc
        .fillColor('#475569')
        .fontSize(size)
        .font(font)
        .text(lbl, totalsX + 12, tY);
      doc
        .fillColor(color)
        .fontSize(size)
        .font('Helvetica-Bold')
        .text(val, totalsX + 90, tY, {
          width: totalsWidth - 102,
          align: 'right',
        });

      tY += isGrand ? 22 : 18;
    });
    doc.restore();

    // Terms & Notes on Left
    doc.save();
    const notesBoxWidth = totalsX - 55;
    let notesY = totalsBoxY;

    if (quote.notes || quote.terms || org?.defaultTerms) {
      doc.fillColor('#0f172a').fontSize(8.5).font('Helvetica-Bold').text('TERMS & CONDITIONS', 40, notesY);
      notesY += 14;
      const termsText = quote.terms || org?.defaultTerms || quote.notes;
      doc.fillColor('#64748b').fontSize(8).font('Helvetica').text(termsText!, 40, notesY, { width: notesBoxWidth });
    }
    doc.restore();

    // Footer on all pages cleanly without page overflow
    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.save();
      doc.page.margins.bottom = 0;
      doc.rect(40, 770, 515, 0.5).fill('#cbd5e1');
      doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica').text('This quotation is subject to final acceptance.  ·  TechCMantix CRM  ·  Proposal Document', 40, 778, {
        align: 'center',
        width: 515,
        lineBreak: false,
      });
      doc.restore();
    }

    doc.end();

    return new Promise((resolve, reject) => {
      doc.on('end', () => {
        resolve({
          buffer: Buffer.concat(buffers),
          filename: `quote-${quote.quoteNumber}.pdf`,
        });
      });
      doc.on('error', reject);
    });
  }
}
