use std::cmp::Ordering;

use leptos::ev;
use leptos::prelude::*;

use super::unified::TableColumn;

/// Sort direction for table columns
#[derive(Clone, Copy, Debug, PartialEq)]
enum SortDirection {
    None,
    Ascending,
    Descending,
}

impl SortDirection {
    fn next(self) -> Self {
        match self {
            Self::None => Self::Ascending,
            Self::Ascending => Self::Descending,
            Self::Descending => Self::None,
        }
    }

    fn icon(self) -> &'static str {
        match self {
            Self::None => "↕",
            Self::Ascending => "↑",
            Self::Descending => "↓",
        }
    }
}

#[component]
pub fn TableClient(
    columns: Vec<TableColumn>,
    rows: Vec<Vec<String>>,
    on_sort: Callback<String>,
    class: &'static str,
) -> impl IntoView {
    // Sort state
    let (sort_column, set_sort_column) = signal::<Option<String>>(None);
    let (sort_direction, set_sort_direction) = signal(SortDirection::None);

    // Store original rows and columns for sorting
    let original_rows = StoredValue::new(rows);
    let columns_stored = StoredValue::new(columns.clone());

    // Computed sorted rows
    let sorted_rows = Memo::new(move |_| {
        let rows = original_rows.get_value();
        let col_key = sort_column.get();
        let direction = sort_direction.get();

        if direction == SortDirection::None || col_key.is_none() {
            return rows;
        }

        let col_key = col_key.unwrap();
        let columns = columns_stored.get_value();
        let col_index = columns.iter().position(|c| c.key == col_key);

        if let Some(idx) = col_index {
            let mut sorted = rows.clone();
            sorted.sort_by(|a, b| {
                let a_val = a.get(idx).map(|s| s.as_str()).unwrap_or("");
                let b_val = b.get(idx).map(|s| s.as_str()).unwrap_or("");

                let cmp = a_val.cmp(b_val);
                match direction {
                    SortDirection::Ascending => cmp,
                    SortDirection::Descending => cmp.reverse(),
                    SortDirection::None => Ordering::Equal,
                }
            });
            sorted
        } else {
            rows
        }
    });
    view! {
        <div class={format!("ds-card overflow-hidden {}", class)}>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-white/5 border-b border-white/10">
                        <tr>
                            {columns.iter().map(|col| {
                                let col_clone = col.clone();
                                let col_key = col.key.clone();

                                let handle_sort = move |_: ev::MouseEvent| {
                                    if col_clone.sortable {
                                        let current_col = sort_column.get();
                                        let current_dir = sort_direction.get();

                                        if current_col.as_ref() == Some(&col_clone.key) {
                                            // Same column: cycle direction
                                            set_sort_direction.set(current_dir.next());
                                            if current_dir.next() == SortDirection::None {
                                                set_sort_column.set(None);
                                            }
                                        } else {
                                            // New column: start with ascending
                                            set_sort_column.set(Some(col_clone.key.clone()));
                                            set_sort_direction.set(SortDirection::Ascending);
                                        }

                                        // Notify external handler
                                        on_sort.run(col_clone.key.clone());
                                    }
                                };

                                let header_class = if col.sortable {
                                    "px-6 py-3 text-left text-sm font-medium text-white cursor-pointer hover:bg-white/8 transition-colors"
                                } else {
                                    "px-6 py-3 text-left text-sm font-medium text-white"
                                };

                                view! {
                                    <th
                                        class=header_class
                                        on:click=handle_sort
                                    >
                                        <div class="flex items-center gap-2">
                                            {col.header.clone()}
                                            {col.sortable.then(move || {
                                                let is_active = sort_column.get().as_ref() == Some(&col_key);
                                                let icon = if is_active {
                                                    sort_direction.get().icon()
                                                } else {
                                                    SortDirection::None.icon()
                                                };
                                                let color = if is_active { "text-cyan-400" } else { "text-white/40" };
                                                view! {
                                                    <span class={format!("{} transition-colors", color)}>
                                                        {icon}
                                                    </span>
                                                }
                                            })}
                                        </div>
                                    </th>
                                }
                            }).collect::<Vec<_>>()}
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-white/10">
                        {move || sorted_rows.get().into_iter().map(|row| {
                            view! {
                                <tr class="hover:bg-white/5 transition-colors">
                                    {row.into_iter().map(|cell| {
                                        view! {
                                            <td class="px-6 py-4 text-sm text-white/80">
                                                {cell}
                                            </td>
                                        }
                                    }).collect::<Vec<_>>()}
                                </tr>
                            }
                        }).collect::<Vec<_>>()}
                    </tbody>
                </table>
            </div>
        </div>
    }
}
