"""Table layout component for displaying media files as rows."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/components/list_view.ipynb.

# %% auto #0
__all__ = ['COLUMN_LABELS', 'render_list_header', 'render_list_row', 'render_list_view', 'render_list_empty_state']

# %% ../../nbs/components/list_view.ipynb #c3d4e5f6
from typing import Any, List, Optional

from fasthtml.common import Div, Span, Table, Thead, Tbody, Tr, Th, Td, Input

# Tailwind utilities
from cjm_fasthtml_tailwind.utilities.sizing import w, min_h, min_w
from cjm_fasthtml_tailwind.utilities.spacing import p, m
from cjm_fasthtml_tailwind.utilities.typography import (
    font_size, font_weight, truncate, text_nowrap
)
from cjm_fasthtml_tailwind.utilities.flexbox_and_grid import (
    flex_display, flex_direction, items, justify, grow
)
from cjm_fasthtml_tailwind.utilities.interactivity import cursor
from cjm_fasthtml_tailwind.utilities.layout import overflow
from cjm_fasthtml_tailwind.core.base import combine_classes

# DaisyUI utilities
from cjm_fasthtml_daisyui.utilities.semantic_colors import bg_dui, text_dui
from cjm_fasthtml_daisyui.components.data_display.table import table, table_modifiers, table_sizes
from cjm_fasthtml_daisyui.components.data_input.checkbox import checkbox, checkbox_colors, checkbox_sizes

# Local imports
from cjm_file_discovery.core.models import FileInfo, FileType
from cjm_fasthtml_media_gallery.core.config import (
    GalleryConfig, ListColumn, SelectionMode
)
from ..core.html_ids import GalleryHtmlIds
from ..core.icons import get_media_type_icon

# %% ../../nbs/components/list_view.ipynb #e5f6a7b8
COLUMN_LABELS: dict[ListColumn, str] = {
    ListColumn.NAME: "Name",
    ListColumn.TYPE: "Type",
    ListColumn.SIZE: "Size",
    ListColumn.MODIFIED: "Modified",
    ListColumn.EXTENSION: "Extension",
    ListColumn.PATH: "Path",
}

# %% ../../nbs/components/list_view.ipynb #f6a7b8c9
def render_list_header(
    config: GalleryConfig,            # Gallery configuration
    show_selection: bool = False,     # Show selection checkbox column
) -> Thead:  # Table header
    """Render the table header row."""
    headers = []
    
    # Selection checkbox column
    if show_selection:
        headers.append(Th("", cls=str(w(10))))
    
    # Configured columns
    for col in config.list.columns:
        label = COLUMN_LABELS.get(col, col.value.title())
        # Make name column wider
        col_cls = "" if col != ListColumn.NAME else min_w(48)
        headers.append(Th(label, cls=col_cls))
    
    return Thead(Tr(*headers))

# %% ../../nbs/components/list_view.ipynb #i9d0e1f2
def render_list_row(
    file_info: FileInfo,              # File to render
    config: GalleryConfig,            # Gallery configuration
    index: int,                       # Index in the list
    is_selected: bool = False,        # Whether file is selected
    preview_url: Optional[str] = None,  # URL for preview action
    select_url: Optional[str] = None,   # URL for selection action
    hx_target: Optional[str] = None,    # HTMX target for swaps
) -> Tr:  # Table row
    """Render a media file as a table row."""
    can_select = config.can_select(file_info)
    show_selection = config.selection_mode != SelectionMode.NONE
    
    # Row styling
    row_cls = combine_classes(
        "hover",
        cursor.pointer if config.preview.enable_preview else None,
        bg_dui.primary.opacity(10) if is_selected else None
    )
    
    item_id = GalleryHtmlIds.list_item_id(index)
    
    # Row attributes
    row_attrs = {
        "id": item_id,
        "cls": row_cls,
        "data-path": file_info.path,
        "data-index": str(index),
    }
    
    # Click action for preview
    if config.preview.enable_preview and preview_url:
        row_attrs["hx_post"] = preview_url
        row_attrs["hx_vals"] = f'{{"path": "{file_info.path}"}}'
        row_attrs["hx_target"] = f"#{config.preview_modal_id}"
        row_attrs["hx_swap"] = "innerHTML"
    
    cells = []
    
    # Selection checkbox
    if show_selection:
        checkbox_attrs = {
            "type": "checkbox",
            "checked": is_selected,
            "cls": combine_classes(checkbox, checkbox_colors.primary, checkbox_sizes.sm),
            "onclick": "event.stopPropagation()",
        }
        if can_select and select_url:
            checkbox_attrs["hx_post"] = select_url
            checkbox_attrs["hx_vals"] = f'{{"path": "{file_info.path}"}}'
            if hx_target:
                checkbox_attrs["hx_target"] = hx_target
            checkbox_attrs["hx_swap"] = "outerHTML"
        
        cells.append(Td(
            Input(**checkbox_attrs) if can_select else None,
            cls=str(w(10))
        ))
    
    # Render each configured column
    for col in config.list.columns:
        cells.append(_render_cell(file_info, col, config))
    
    return Tr(*cells, **row_attrs)

# %% ../../nbs/components/list_view.ipynb #j0e1f2g3
def _render_cell(
    file_info: FileInfo,              # File info
    column: ListColumn,               # Column to render
    config: GalleryConfig,            # Gallery config
) -> Td:  # Table cell
    """Render a single table cell."""
    if column == ListColumn.NAME:
        # Name with icon
        content = Div(
            Span(
                get_media_type_icon(file_info.file_type, size=4) if config.list.show_icons else None,
                cls=str(m.r(2)) if config.list.show_icons else None
            ),
            Span(file_info.name, cls=combine_classes(truncate, grow())),
            cls=combine_classes(flex_display, items.center, min_w(0))
        )
        return Td(content, title=file_info.name)
    
    elif column == ListColumn.TYPE:
        type_label = file_info.file_type.value.title()
        return Td(
            type_label,
            cls=combine_classes(text_nowrap, text_dui.base_content.opacity(70))
        )
    
    elif column == ListColumn.SIZE:
        return Td(
            file_info.size_str or "—",
            cls=combine_classes(text_nowrap, text_dui.base_content.opacity(70))
        )
    
    elif column == ListColumn.MODIFIED:
        return Td(
            file_info.modified_str or "—",
            cls=combine_classes(text_nowrap, text_dui.base_content.opacity(70))
        )
    
    elif column == ListColumn.EXTENSION:
        ext = file_info.extension.upper() if file_info.extension else "—"
        return Td(
            ext,
            cls=combine_classes(text_nowrap, text_dui.base_content.opacity(70))
        )
    
    elif column == ListColumn.PATH:
        return Td(
            file_info.path,
            cls=combine_classes(truncate, font_size.sm, text_dui.base_content.opacity(50)),
            title=file_info.path
        )
    
    return Td("")

# %% ../../nbs/components/list_view.ipynb #m3h4i5j6
def render_list_view(
    files: List[FileInfo],            # Files to display
    config: GalleryConfig,            # Gallery configuration
    selected_paths: Optional[List[str]] = None,  # Currently selected paths
    preview_url: Optional[str] = None,  # URL for preview action
    select_url: Optional[str] = None,   # URL for selection action
    hx_target: Optional[str] = None,    # HTMX target for swaps
    start_index: int = 0,               # Starting index for IDs (for pagination)
) -> Any:  # List view component
    """Render a list view of media files."""
    selected_paths = selected_paths or []
    show_selection = config.selection_mode != SelectionMode.NONE
    
    # Table classes
    table_cls = combine_classes(
        table,
        table_modifiers.zebra if config.list.striped else None,
        table_sizes.sm if config.list.compact else None
    )
    
    # Render rows
    rows = []
    for i, file_info in enumerate(files):
        is_selected = file_info.path in selected_paths
        
        row = render_list_row(
            file_info=file_info,
            config=config,
            index=start_index + i,
            is_selected=is_selected,
            preview_url=preview_url,
            select_url=select_url,
            hx_target=hx_target
        )
        rows.append(row)
    
    return Div(
        Table(
            render_list_header(config, show_selection=show_selection),
            Tbody(*rows),
            cls=table_cls
        ),
        id=GalleryHtmlIds.LIST,
        cls=overflow.x.auto
    )

# %% ../../nbs/components/list_view.ipynb #p6k7l8m9
def render_list_empty_state(
    message: str = "No media files found",  # Message to display
) -> Any:  # Empty state component
    """Render empty state for list view."""
    return Div(
        Div(
            get_media_type_icon(FileType.IMAGE, size=16, with_color=False),
            cls=combine_classes(text_dui.base_content.opacity(30), m.b(4))
        ),
        Span(
            message,
            cls=combine_classes(font_size.lg, text_dui.base_content.opacity(60))
        ),
        id=GalleryHtmlIds.LIST,
        cls=combine_classes(
            flex_display, flex_direction.col, items.center, justify.center,
            min_h(64), p(8)
        )
    )
