from sqlalchemy import Column, String, Text, Boolean, Integer, Float, DateTime
from sqlalchemy.sql import func
import json
import uuid
from typing import Dict, Any, List, Optional
from app.models.base import BaseModel


class InvoiceTemplate(BaseModel):
    """Invoice template model for customizable PDF layouts"""

    __tablename__ = "invoice_templates"

    # Primary Key
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))

    # Template metadata
    name = Column(String(255), nullable=False, unique=True)
    description = Column(Text)
    is_default = Column(Boolean, default=False)
    is_active = Column(Boolean, default=True)

    # Logo configuration
    show_logo = Column(Boolean, default=True)
    logo_width_mm = Column(Integer, default=80)
    logo_height_mm = Column(Integer, default=80)
    logo_position = Column(String(20), default='left')  # left, center, right

    # Header configuration
    show_header = Column(Boolean, default=True)
    show_company_name = Column(Boolean, default=True)
    show_company_address = Column(Boolean, default=True)
    show_company_phone = Column(Boolean, default=True)
    show_company_email = Column(Boolean, default=True)
    show_company_website = Column(Boolean, default=True)
    show_company_vat = Column(Boolean, default=True)
    header_background_color = Column(String(20), default='#ffffff')

    # Invoice details section
    show_invoice_details = Column(Boolean, default=True)
    show_invoice_number = Column(Boolean, default=True)
    show_invoice_date = Column(Boolean, default=True)
    show_due_date = Column(Boolean, default=True)
    show_payment_terms = Column(Boolean, default=True)
    show_branch = Column(Boolean, default=True)
    show_generated_at = Column(Boolean, default=True)

    # Customer section
    show_customer = Column(Boolean, default=True)
    show_customer_address = Column(Boolean, default=True)
    show_customer_phone = Column(Boolean, default=True)
    show_customer_email = Column(Boolean, default=True)
    show_customer_vat = Column(Boolean, default=True)
    customer_section_background_color = Column(String(20), default='#f8f9fa')

    # Items table columns (JSON string with column definitions)
    items_columns = Column(Text)  # JSON array of column definitions

    # Items table styling
    items_header_background = Column(String(20), default='#343a40')
    items_header_text_color = Column(String(20), default='#ffffff')
    items_border_color = Column(String(20), default='#dee2e6')
    items_stripe_color = Column(String(20), default='#f8f9fa')
    items_font_size = Column(Integer, default=12)

    # Totals section
    show_totals = Column(Boolean, default=True)
    show_subtotal = Column(Boolean, default=True)
    show_discount = Column(Boolean, default=True)
    show_vat = Column(Boolean, default=True)
    show_total = Column(Boolean, default=True)
    totals_background_color = Column(String(20), default='#f8f9fa')
    totals_font_size = Column(Integer, default=14)

    # Footer section
    show_footer = Column(Boolean, default=True)
    show_footer_text = Column(Boolean, default=True)
    show_terms_conditions = Column(Boolean, default=True)
    show_bank_details = Column(Boolean, default=False)
    footer_text = Column(Text, default='Thank you for your business!')
    footer_background_color = Column(String(20), default='#ffffff')
    footer_font_size = Column(Integer, default=11)

    # Page layout
    page_margin_top = Column(Integer, default=20)
    page_margin_bottom = Column(Integer, default=20)
    page_margin_left = Column(Integer, default=20)
    page_margin_right = Column(Integer, default=20)

    # Typography
    font_family = Column(String(100), default='Helvetica')
    base_font_size = Column(Integer, default=12)
    line_height = Column(Float, default=1.4)

    # Colors
    primary_color = Column(String(20), default='#007bff')
    secondary_color = Column(String(20), default='#6c757d')
    accent_color = Column(String(20), default='#28a745')
    text_color = Column(String(20), default='#000000')
    border_color = Column(String(20), default='#dee2e6')

    # Template configuration as JSON
    config = Column(Text)

    # Timestamps
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

    def get_config(self) -> Dict[str, Any]:
        """Get template configuration as dictionary"""
        try:
            return json.loads(self.config) if self.config else {}
        except json.JSONDecodeError:
            return {}

    def set_config(self, config: Dict[str, Any]) -> None:
        """Set template configuration"""
        self.config = json.dumps(config)

    def get_items_columns(self) -> List[Dict[str, Any]]:
        """Get items table column definitions"""
        try:
            cols = json.loads(self.items_columns) if self.items_columns else []
            return cols if isinstance(cols, list) else []
        except json.JSONDecodeError:
            return []

    def set_items_columns(self, columns: List[Dict[str, Any]]) -> None:
        """Set items table column definitions"""
        self.items_columns = json.dumps(columns)

    def to_dict(self) -> Dict[str, Any]:
        """Convert template to dictionary"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'is_default': self.is_default,
            'is_active': self.is_active,
            'show_logo': self.show_logo,
            'logo_width_mm': self.logo_width_mm,
            'logo_height_mm': self.logo_height_mm,
            'logo_position': self.logo_position,
            'show_header': self.show_header,
            'show_company_name': self.show_company_name,
            'show_company_address': self.show_company_address,
            'show_company_phone': self.show_company_phone,
            'show_company_email': self.show_company_email,
            'show_company_website': self.show_company_website,
            'show_company_vat': self.show_company_vat,
            'header_background_color': self.header_background_color,
            'show_invoice_details': self.show_invoice_details,
            'show_invoice_number': self.show_invoice_number,
            'show_invoice_date': self.show_invoice_date,
            'show_due_date': self.show_due_date,
            'show_payment_terms': self.show_payment_terms,
            'show_branch': self.show_branch,
            'show_generated_at': self.show_generated_at,
            'show_customer': self.show_customer,
            'show_customer_address': self.show_customer_address,
            'show_customer_phone': self.show_customer_phone,
            'show_customer_email': self.show_customer_email,
            'show_customer_vat': self.show_customer_vat,
            'customer_section_background_color': self.customer_section_background_color,
            'items_columns': self.get_items_columns(),
            'items_header_background': self.items_header_background,
            'items_header_text_color': self.items_header_text_color,
            'items_border_color': self.items_border_color,
            'items_stripe_color': self.items_stripe_color,
            'items_font_size': self.items_font_size,
            'show_totals': self.show_totals,
            'show_subtotal': self.show_subtotal,
            'show_discount': self.show_discount,
            'show_vat': self.show_vat,
            'show_total': self.show_total,
            'totals_background_color': self.totals_background_color,
            'totals_font_size': self.totals_font_size,
            'show_footer': self.show_footer,
            'show_footer_text': self.show_footer_text,
            'show_terms_conditions': self.show_terms_conditions,
            'show_bank_details': self.show_bank_details,
            'footer_text': self.footer_text,
            'footer_background_color': self.footer_background_color,
            'footer_font_size': self.footer_font_size,
            'page_margin_top': self.page_margin_top,
            'page_margin_bottom': self.page_margin_bottom,
            'page_margin_left': self.page_margin_left,
            'page_margin_right': self.page_margin_right,
            'font_family': self.font_family,
            'base_font_size': self.base_font_size,
            'line_height': self.line_height,
            'primary_color': self.primary_color,
            'secondary_color': self.secondary_color,
            'accent_color': self.accent_color,
            'text_color': self.text_color,
            'border_color': self.border_color,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
