from django.db import models
from django.utils import timezone
from django.conf import settings
from enum import Enum
from lib.choices import choices_the_options
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle


from crm.models import Invoice

class PaymentMethod(Enum):
    CASH = "Cash"
    CHEQUE = "Cheque"
    ONLINE = "Online"
    UPI = "UPI"
    CREDIT_CARD = "Credit Card"
    DEBIT_CARD = "Debit Card"

class Payment(models.Model):
    invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='payments')
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    payment_date = models.DateTimeField(default=timezone.now)
    payment_method = models.CharField(max_length=50, choices=choices_the_options(PaymentMethod), default=PaymentMethod.CASH.value, blank=True, null=True)
    transaction_id = models.CharField(max_length=100, blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    pdf_file = models.FileField(upload_to='media/payments/', null=True, blank=True)
    created_at = models.DateTimeField(default=timezone.now())


    def __str__(self):
        return f"Payment of {self.amount} for Invoice {self.invoice.invoice_number}"

    class Meta:
        ordering = ['-created_at']

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if self.invoice:
            items = self.invoice.items.all()
            total_amount = float(sum(item.amount for item in items))
            print(total_amount, "total_amount")
            total_paid = float(self.invoice.get_total_paid())
            print(total_paid, "total_paid")
            pending_amount = max(total_amount - total_paid, 0)
            print(pending_amount, "pending_amount")
            is_paid = pending_amount == 0
            print(is_paid, "is_paid")
            self.invoice.pending_amount = pending_amount
            print(self.invoice.pending_amount, "self.invoice.pending_amount")
            self.invoice.is_paid = is_paid
            self.invoice.save(update_fields=["pending_amount", "is_paid"])
            print(self.invoice.is_paid, "self.invoice.is_paid")
            quote = getattr(self.invoice, 'quote', None)
            print(quote, "quote")
            if quote and hasattr(quote, 'is_paid'):
                print(quote.is_paid, "quote.is_paid")
                quote.is_paid = is_paid
                print(quote.is_paid, "quote.is_paid")
                quote.save(update_fields=["is_paid"])
                print(quote.is_paid, "quote.is_paid")

        if not self.pdf_file:
            self.generate_pdf()


    def generate_pdf(self):
        import os

        total_invoice_amount = float(sum(item.amount for item in self.invoice.items.all()))

        # Generate PDF using ReportLab with professional design
        payments_dir = os.path.join(settings.MEDIA_ROOT, "payments")
        os.makedirs(payments_dir, exist_ok=True)
        pdf_path = os.path.join(payments_dir, f"payment_{self.id}.pdf")
        
        doc = SimpleDocTemplate(
            pdf_path,
            pagesize=A4,
            rightMargin=25,
            leftMargin=25,
            topMargin=25,
            bottomMargin=25,
        )
        
        story = []
        styles = getSampleStyleSheet()
        
        # Custom styles for professional design
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Normal'],
            fontSize=24,
            fontName='Helvetica-Bold',
            textColor=colors.HexColor('#f7931e'),
            alignment=1,  # Center
            spaceAfter=6,
        )
        
        subtitle_style = ParagraphStyle(
            'CustomSubtitle',
            parent=styles['Normal'],
            fontSize=14,
            fontName='Helvetica',
            textColor=colors.HexColor('#666666'),
            alignment=1,  # Center
            spaceAfter=20,
        )
        
        receipt_title_style = ParagraphStyle(
            'ReceiptTitle',
            parent=styles['Normal'],
            fontSize=32,
            fontName='Helvetica-Bold',
            textColor=colors.black,
            alignment=1,  # Center
            spaceAfter=6,
        )
        
        section_style = ParagraphStyle(
            'Section',
            parent=styles['Normal'],
            fontSize=12,
            fontName='Helvetica-Bold',
            textColor=colors.HexColor('#f7931e'),
            spaceAfter=8,
        )
        
        normal_style = ParagraphStyle(
            'Normal',
            parent=styles['Normal'],
            fontSize=10,
            fontName='Helvetica',
            spaceAfter=4,
        )
        
        company_style = ParagraphStyle(
            'Company',
            parent=styles['Normal'],
            fontSize=10,
            fontName='Helvetica',
            spaceAfter=2,
        )

        # Header Section
        story.append(Paragraph("Marketizr", title_style))
        story.append(Paragraph("Business Expertise", subtitle_style))
        story.append(Paragraph("PAYMENT RECEIPT", receipt_title_style))
        story.append(Spacer(1, 30))
        
        # Company and Client Information Table
        company_info = f"""
        <b>Marketizr</b><br/>
         IInd Floor<br/>
        Fathima Arcade Building, Opp New Busstand<br/>
        Kasaragod Kerala 671121, India<br/>
        Phone: 9995 555 861<br/>
        Email: marketizrksd@gmail.com<br/>
        Website: www.marketizr.in
        """
        
        client_info = "No client information"
        lead = self.invoice.lead if self.invoice else None
        if lead:
            client_info = f"""
            <b>Client Details:</b><br/>
            {lead.company or ''}<br/>
            {lead.first_name or ''} {lead.last_name or ''}<br/>
            {lead.address or ''}<br/>
            {lead.city or ''}, {lead.state or ''} {lead.zip_code or ''}<br/>
            {lead.country or ''}
            """
        
        info_data = [
            [Paragraph(company_info, company_style), Paragraph(client_info, normal_style)]
        ]
        
        info_table = Table(info_data, colWidths=[250, 250])
        info_table.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('LEFTPADDING', (0, 0), (-1, -1), 0),
            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
            ('TOPPADDING', (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
        ]))
        story.append(info_table)
        story.append(Spacer(1, 20))
        
        # Payment Information
        payment_info = f"""
        <b>Receipt Date:</b> {self.payment_date.strftime('%d-%m-%Y')}<br/>
        <b>Invoice Number:</b> {self.invoice.invoice_number}<br/>
        <b>Invoice Date:</b> {self.invoice.invoice_date.strftime('%d-%m-%Y')}<br/>
        <b>Payment Method:</b> {self.payment_method}<br/>
        """
        if self.transaction_id:
            payment_info += f"<b>Transaction ID:</b> {self.transaction_id}<br/>"
        payment_info += f"<b>Receipt Number:</b> {self.id}"
        
        story.append(Paragraph(payment_info, normal_style))
        story.append(Spacer(1, 20))
        
        # Payment Details Section
        story.append(Paragraph("<b>Payment Details</b>", section_style))
        story.append(Spacer(1, 10))
        
        payment_data = [
            ["Payment Amount:", f"{self.amount:.2f} {self.invoice.currency}"],
            ["Payment Method:", self.payment_method],
            ["Payment Date:", self.payment_date.strftime('%d-%m-%Y %H:%M')],
        ]
        
        if self.notes:
            payment_data.append(["Notes:", self.notes])
        
        payment_data.append(["Total Paid:", f"{self.amount:.2f} {self.invoice.currency}"])
        
        payment_table = Table(payment_data, colWidths=[150, 200])
        payment_table.setStyle(TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("FONTSIZE", (0, 0), (-1, -1), 10),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
            ("BACKGROUND", (0, 0), (0, -1), colors.HexColor("#f9f9f9")),
            ("BACKGROUND", (0, -1), (-1, -1), colors.HexColor("#f0f8ff")),
            ("TOPPADDING", (0, 0), (-1, -1), 8),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ]))
        story.append(payment_table)
        story.append(Spacer(1, 20))
        
        # Invoice Summary Section
        story.append(Paragraph("<b>Invoice Summary</b>", section_style))
        story.append(Spacer(1, 10))
        
        summary_data = [
            ["Total Invoice Amount:", f"{total_invoice_amount:.2f} {self.invoice.currency}"],
            ["Total Paid:", f"{self.invoice.get_total_paid():.2f} {self.invoice.currency}"],
            ["Pending Amount:", f"{self.invoice.get_pending_amount():.2f} {self.invoice.currency}"],
        ]
        
        summary_table = Table(summary_data, colWidths=[150, 200])
        summary_table.setStyle(TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("FONTSIZE", (0, 0), (-1, -1), 10),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
            ("BACKGROUND", (0, 0), (0, -1), colors.HexColor("#f9f9f9")),
            ("BACKGROUND", (0, -1), (-1, -1), colors.HexColor("#f7931e")),
            ("TEXTCOLOR", (0, -1), (-1, -1), colors.white),
            ("TOPPADDING", (0, 0), (-1, -1), 8),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ]))
        story.append(summary_table)
        story.append(Spacer(1, 30))
        
        # Thank You Message
        thank_you_style = ParagraphStyle(
            'ThankYou',
            parent=styles['Normal'],
            fontSize=12,
            fontName='Helvetica-Bold',
            textColor=colors.black,
            alignment=1,  # Center
            spaceAfter=6,
        )
        
        thank_you = Paragraph(
            "<b>Thank you for your payment!</b><br/>"
            "Your payment has been received and processed successfully.",
            thank_you_style
        )
        story.append(thank_you)
        story.append(Spacer(1, 30))
        
        # Signature Section
        signature_style = ParagraphStyle(
            'Signature',
            parent=styles['Normal'],
            fontSize=10,
            fontName='Helvetica',
            alignment=2,  # Right
            spaceAfter=30,
        )
        
        story.append(Paragraph("Authorized Signature", signature_style))
        story.append(Paragraph("_________________________", signature_style))
        
        # Footer
        footer_style = ParagraphStyle(
            'Footer',
            parent=styles['Normal'],
            fontSize=8,
            fontName='Helvetica',
            textColor=colors.HexColor('#888888'),
            alignment=1,  # Center
            spaceAfter=0,
        )
        
        story.append(Spacer(1, 40))
        story.append(Paragraph("This receipt serves as proof of payment for your records.", footer_style))
        story.append(Paragraph("Powered by Marketizr - Business Expertise", footer_style))

        # Build PDF
        doc.build(story)
        
        self.pdf_file.name = f"payments/payment_{self.id}.pdf"
        self.save(update_fields=["pdf_file"])


def get_total_paid(self):
    return float(sum(p.amount for p in self.payments.all()))

def get_pending_amount(self):
    total = float(sum(item.amount for item in self.items.all()))
    return max(total - self.get_total_paid(), 0)

def get_payments_info(self):
    total_invoice_amount = float(sum(item.amount for item in self.items.all()))
    return {
        "total_invoice_amount": total_invoice_amount,
        "total_paid": self.get_total_paid(),
        "pending_amount": self.get_pending_amount(),
        "payments": list(self.payments.all().values('id', 'amount', 'payment_date', 'payment_method', 'transaction_id', 'pdf_file')),
    }

def get_latest_payment(self):
    return self.payments.order_by('-payment_date').first()

Invoice.add_to_class("get_total_paid", get_total_paid)
Invoice.add_to_class("get_pending_amount", get_pending_amount)
Invoice.add_to_class("get_payments_info", get_payments_info)
Invoice.add_to_class("get_latest_payment", get_latest_payment)
