import requests
from io import BytesIO
from PIL import Image, ImageTk
import tkinter as tk
import yt_dlp
import shadowtube.recommend as rec
import shadowtube.preprocess as prep

# kjdshfgklshdfjkglkadshf

import webbrowser

# List of 8 YouTube video IDs
video_ids = rec.recommend(
    prep.sort_history(
        prep.parse_database(
            "/home/fedir/.var/app/io.freetubeapp.FreeTube/config/FreeTube/history.db"
        )
    ),
    verbose=True,
    count=8,
)

print(video_ids)


def get_video_info(video_id):
    """Fetch the title and thumbnail URL of a YouTube video using yt_dlp."""
    ydl_opts = {"quiet": True, "no_warnings": True, "extract_flat": True}

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(
            f"https://www.youtube.com/watch?v={video_id}", download=False
        )
        return info.get("title", "Title Not Found"), info.get("thumbnail", "")


def open_video(event, video_id):
    """Open the YouTube video in the default web browser when clicked."""
    webbrowser.open(f"https://www.youtube.com/watch?v={video_id}")


def show_video_preview(video_id, row, col):
    """Fetch and display a video's title and thumbnail in a grid layout."""
    title, thumbnail_url = get_video_info(video_id)

    # Fetch thumbnail
    response = requests.get(thumbnail_url)
    if response.status_code == 200:
        image_data = Image.open(BytesIO(response.content))
        image_data = image_data.resize((200, 112))  # Resize for grid
        photo = ImageTk.PhotoImage(image_data)
    else:
        photo = None

    # Create thumbnail label (clickable)
    thumbnail_label = tk.Label(root, image=photo, cursor="hand2")
    thumbnail_label.image = photo  # Keep reference
    thumbnail_label.grid(row=row, column=col, padx=10, pady=10)
    thumbnail_label.bind("<Button-1>", lambda event, v=video_id: open_video(event, v))

    # Create title label (wrapped text)
    title_label = tk.Label(
        root, text=title, font=("Arial", 10, "bold"), wraplength=200, justify="center"
    )
    title_label.grid(row=row + 1, column=col, padx=10, pady=5)


# Create Tkinter window
root = tk.Tk()
root.title("YouTube Video Previews")

# Add all 8 videos in a 2x4 grid
for index, video_id in enumerate(video_ids):
    row = (index // 4) * 2  # Every second row for the title
    col = index % 4
    show_video_preview(video_id, row, col)

root.mainloop()


# kjdhfglkjsdhfgkljhsdkfg
