# ui/file_item_widget.py

import os
import cv2
from PyQt5.QtWidgets import (
    QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QSizePolicy, QSpacerItem
)
from PyQt5.QtGui import QPixmap, QImage, QIcon
from PyQt5.QtCore import Qt, QSize
from config import t
from utils.path_utils import resource_path

class FileItemWidget(QWidget):
    def __init__(self, path: str, filename: str, on_delete):
        super().__init__()
        self.path = path
        self.filename = filename
        self.on_delete = on_delete

        layout = QHBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.setSpacing(10)

        # превью
        preview = QLabel()
        pixmap = self._get_pixmap(path)
        if pixmap:
            preview.setPixmap(pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        layout.addWidget(preview)

        # путь + имя файла
        text_layout = QVBoxLayout()
        lbl_dir = QLabel(os.path.dirname(path) + os.sep)
        lbl_dir.setWordWrap(True)
        lbl_name = QLabel(filename)
        lbl_name.setWordWrap(True)
        lbl_name.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        lbl_name.setStyleSheet("font-weight: bold;")
        text_layout.addWidget(lbl_dir)
        text_layout.addWidget(lbl_name)
        layout.addLayout(text_layout)

        # отступ
        layout.addSpacerItem(QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum))

        # кнопка удаления
        btn_del = QPushButton()
        btn_del.setIcon(QIcon(resource_path("assets/icons/close_red.png")))
        btn_del.setIconSize(QSize(20, 20))
        btn_del.setCursor(Qt.PointingHandCursor)
        btn_del.setStyleSheet("""
            QPushButton {
                border: none;
                background: transparent;
            }
            QPushButton:hover {
                background-color: rgba(255, 0, 0, 30);
                border-radius: 4px;
            }
        """)
        btn_del.clicked.connect(self._on_delete_clicked)
        layout.addWidget(btn_del)

    def _on_delete_clicked(self):
        if callable(self.on_delete):
            self.on_delete(self.path)

    def _get_pixmap(self, path):
        if not os.path.exists(path):
            return None
        ext = os.path.splitext(path)[1].lower()
        if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.avif', '.gif']:
            return QPixmap(path)
        elif ext in ['.mp4', '.mov', '.avi']:
            cap = cv2.VideoCapture(path)
            ret, frame = cap.read()
            cap.release()
            if ret:
                h, w, ch = frame.shape
                bytes_per_line = ch * w
                img = QImage(frame.data, w, h, bytes_per_line, QImage.Format_BGR888)
                return QPixmap.fromImage(img)
        return None
