from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Dict, Any
from app.core.database import get_db
from app.core.security import get_current_user
from app.models.invoice_template import InvoiceTemplate
from app.models.user import User
import json

router = APIRouter(prefix="/api/v1/invoice-templates", tags=["Invoice Templates"])


@router.get("/", response_model=List[Dict[str, Any]])
def list_templates(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """List all invoice templates"""
    templates = db.query(InvoiceTemplate).filter(InvoiceTemplate.is_active == True).all()
    return [t.to_dict() for t in templates]


@router.get("/default", response_model=Dict[str, Any])
def get_default_template(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Get the default invoice template"""
    template = db.query(InvoiceTemplate).filter(InvoiceTemplate.is_default == True).first()
    if not template:
        raise HTTPException(status_code=404, detail="No default template found")
    return template.to_dict()


@router.get("/{template_id}", response_model=Dict[str, Any])
def get_template(template_id: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Get a specific invoice template"""
    template = db.query(InvoiceTemplate).filter(InvoiceTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")
    return template.to_dict()


@router.post("/", response_model=Dict[str, Any])
def create_template(data: Dict[str, Any], db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Create a new invoice template"""
    # Check if template with this name already exists
    existing = db.query(InvoiceTemplate).filter(InvoiceTemplate.name == data.get('name')).first()
    if existing:
        raise HTTPException(status_code=400, detail="Template with this name already exists")

    # If this is the first template, make it default
    count = db.query(InvoiceTemplate).count()
    is_default = count == 0 or data.get('is_default', False)

    template = InvoiceTemplate(
        name=data.get('name'),
        description=data.get('description'),
        is_default=is_default,
        show_logo=data.get('show_logo', True),
        logo_width_mm=data.get('logo_width_mm', 80),
        logo_height_mm=data.get('logo_height_mm', 80),
        logo_position=data.get('logo_position', 'left'),
        show_header=data.get('show_header', True),
        show_company_name=data.get('show_company_name', True),
        show_company_address=data.get('show_company_address', True),
        show_company_phone=data.get('show_company_phone', True),
        show_company_email=data.get('show_company_email', True),
        show_company_website=data.get('show_company_website', True),
        show_company_vat=data.get('show_company_vat', True),
        show_invoice_details=data.get('show_invoice_details', True),
        show_invoice_number=data.get('show_invoice_number', True),
        show_invoice_date=data.get('show_invoice_date', True),
        show_due_date=data.get('show_due_date', True),
        show_payment_terms=data.get('show_payment_terms', True),
        show_branch=data.get('show_branch', True),
        show_generated_at=data.get('show_generated_at', True),
        show_customer=data.get('show_customer', True),
        show_customer_address=data.get('show_customer_address', True),
        show_customer_phone=data.get('show_customer_phone', True),
        show_customer_email=data.get('show_customer_email', True),
        show_customer_vat=data.get('show_customer_vat', True),
        items_header_background=data.get('items_header_background', '#343a40'),
        items_header_text_color=data.get('items_header_text_color', '#ffffff'),
        items_border_color=data.get('items_border_color', '#dee2e6'),
        items_stripe_color=data.get('items_stripe_color', '#f8f9fa'),
        items_font_size=data.get('items_font_size', 12),
        show_totals=data.get('show_totals', True),
        show_subtotal=data.get('show_subtotal', True),
        show_discount=data.get('show_discount', True),
        show_vat=data.get('show_vat', True),
        show_total=data.get('show_total', True),
        show_footer=data.get('show_footer', True),
        footer_text=data.get('footer_text', 'Thank you for your business!'),
        font_family=data.get('font_family', 'Helvetica'),
        base_font_size=data.get('base_font_size', 12),
        primary_color=data.get('primary_color', '#007bff'),
    )

    # Set items columns if provided
    if 'items_columns' in data:
        template.set_items_columns(data['items_columns'])

    db.add(template)
    db.commit()
    db.refresh(template)
    return template.to_dict()


@router.put("/{template_id}", response_model=Dict[str, Any])
def update_template(template_id: str, data: Dict[str, Any], db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Update an invoice template"""
    template = db.query(InvoiceTemplate).filter(InvoiceTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")

    # Update fields
    if 'name' in data:
        template.name = data['name']
    if 'description' in data:
        template.description = data['description']
    if 'is_default' in data:
        template.is_default = data['is_default']
    if 'show_logo' in data:
        template.show_logo = data['show_logo']
    if 'logo_width_mm' in data:
        template.logo_width_mm = data['logo_width_mm']
    if 'logo_height_mm' in data:
        template.logo_height_mm = data['logo_height_mm']
    if 'logo_position' in data:
        template.logo_position = data['logo_position']
    if 'show_header' in data:
        template.show_header = data['show_header']
    if 'show_company_name' in data:
        template.show_company_name = data['show_company_name']
    if 'show_company_address' in data:
        template.show_company_address = data['show_company_address']
    if 'show_company_phone' in data:
        template.show_company_phone = data['show_company_phone']
    if 'show_company_email' in data:
        template.show_company_email = data['show_company_email']
    if 'show_company_website' in data:
        template.show_company_website = data['show_company_website']
    if 'show_company_vat' in data:
        template.show_company_vat = data['show_company_vat']
    if 'show_customer' in data:
        template.show_customer = data['show_customer']
    if 'show_customer_address' in data:
        template.show_customer_address = data['show_customer_address']
    if 'show_customer_phone' in data:
        template.show_customer_phone = data['show_customer_phone']
    if 'show_customer_email' in data:
        template.show_customer_email = data['show_customer_email']
    if 'show_customer_vat' in data:
        template.show_customer_vat = data['show_customer_vat']
    if 'items_columns' in data:
        template.set_items_columns(data['items_columns'])
    if 'items_header_background' in data:
        template.items_header_background = data['items_header_background']
    if 'items_font_size' in data:
        template.items_font_size = data['items_font_size']
    if 'show_totals' in data:
        template.show_totals = data['show_totals']
    if 'show_footer' in data:
        template.show_footer = data['show_footer']
    if 'footer_text' in data:
        template.footer_text = data['footer_text']
    if 'font_family' in data:
        template.font_family = data['font_family']
    if 'base_font_size' in data:
        template.base_font_size = data['base_font_size']
    if 'primary_color' in data:
        template.primary_color = data['primary_color']

    db.commit()
    db.refresh(template)
    return template.to_dict()


@router.delete("/{template_id}")
def delete_template(template_id: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Delete an invoice template (soft delete - mark as inactive)"""
    template = db.query(InvoiceTemplate).filter(InvoiceTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")

    template.is_active = False
    db.commit()
    return {"message": "Template deleted"}


@router.post("/{template_id}/set-default")
def set_default_template(template_id: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Set a template as the default"""
    template = db.query(InvoiceTemplate).filter(InvoiceTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")

    # Unset all other defaults
    db.query(InvoiceTemplate).update({InvoiceTemplate.is_default: False})

    # Set this one as default
    template.is_default = True
    db.commit()
    db.refresh(template)
    return template.to_dict()
