from .base_theme import BaseTheme
from ..utils.images import load_image, resize_image, create_gradient
from ..utils.text import load_font, draw_text_with_shadow
from PIL import Image, ImageDraw
import math

class ModernTheme(BaseTheme):
    def render(self, image: Image.Image, draw: ImageDraw.ImageDraw, metadata: dict):
        title = metadata.get('title', 'Musicard')
        artist = metadata.get('artist', 'By Unburn')
        progress = metadata.get('progress', 0.0)
        thumbnail_url = metadata.get('thumbnail')
        background_color = metadata.get('background_color', '#1a1a1a')
        progress_color = metadata.get('progress_color', '#00ff88')
        name_color = metadata.get('name_color', '#ffffff')
        author_color = metadata.get('author_color', '#cccccc')

        # Truncate
        if len(title) > 20:
            title = title[:20] + '...'
        if len(artist) > 20:
            artist = artist[:20] + '...'

        # Gradient background
        gradient_start = metadata.get('gradient_start', (26, 26, 26))  # Dark gray
        gradient_end = metadata.get('gradient_end', (10, 10, 10))  # Darker gray
        gradient_img = create_gradient((image.width, image.height), gradient_start, gradient_end)
        image.paste(gradient_img, (0, 0))

        # Thumbnail
        if thumbnail_url:
            try:
                thumb = load_image(thumbnail_url)
                thumb = resize_image(thumb, (300, 300))
                # Rounded rectangle mask
                mask = Image.new('L', (300, 300), 0)
                mask_draw = ImageDraw.Draw(mask)
                mask_draw.rounded_rectangle((0, 0, 300, 300), radius=20, fill=255)
                thumb.putalpha(mask)
                image.paste(thumb, (image.width - 350, 50), thumb)
            except:
                pass

        # Progress bar
        bar_width = 700
        bar_height = 15
        bar_x = 50
        bar_y = image.height - 80
        # Background bar
        draw.rectangle([bar_x, bar_y, bar_x + bar_width, bar_y + bar_height], fill='#333333')
        # Progress
        progress_width = int(bar_width * progress)
        draw.rectangle([bar_x, bar_y, bar_x + progress_width, bar_y + bar_height], fill=progress_color)

        # Title with shadow
        title_font = load_font('PlusJakartaSans-Bold.ttf', 70)
        draw_text_with_shadow(draw, title, title_font, name_color, '#000000', (50, 120))

        # Artist with shadow
        artist_font = load_font('PlusJakartaSans-Medium.ttf', 50)
        draw_text_with_shadow(draw, artist, artist_font, author_color, '#333333', (50, 220))