import type { ReactNode } from "react";
import { EmptyState } from "@/components/atoms/empty-state";
import { ChevronRightIcon } from "@heroicons/react/24/outline";

interface Column<T> {
  key: string;
  header: string;
  render: (item: T) => ReactNode;
  className?: string;
  /** If true, this column will be emphasized in mobile card view (shown first/larger) */
  primary?: boolean;
  /** If true, this column will be hidden in mobile card view */
  hideOnMobile?: boolean;
}

interface DataTableProps<T> {
  data: T[];
  columns: Column<T>[];
  emptyState?: {
    icon: ReactNode;
    title: string;
    description: string;
  };
  onRowClick?: (item: T) => void;
  className?: string;
  /** Force table view even on mobile (not recommended for UX) */
  forceTableView?: boolean;
}

function MobileCardView<T extends { id: number | string }>({
  data,
  columns,
  onRowClick,
}: {
  data: T[];
  columns: Column<T>[];
  onRowClick: ((item: T) => void) | undefined;
}) {
  const primaryColumn = columns.find(col => col.primary);
  const mobileColumns = columns.filter(col => !col.hideOnMobile && !col.primary);

  return (
    <div className="md:hidden space-y-3">
      {data.map((item, index) => (
        <div
          key={item.id}
          className={`
            bg-card border border-border rounded-xl p-4
            shadow-[var(--cp-shadow-1)]
            transition-all duration-[var(--cp-duration-fast)]
            active:scale-[0.98] active:shadow-none
            ${onRowClick ? "cursor-pointer active:bg-muted/50" : ""}
          `}
          onClick={() => onRowClick?.(item)}
          role={onRowClick ? "button" : undefined}
          tabIndex={onRowClick ? 0 : undefined}
          onKeyDown={e => {
            if (onRowClick && (e.key === "Enter" || e.key === " ")) {
              e.preventDefault();
              onRowClick(item);
            }
          }}
          style={{ animationDelay: `${index * 50}ms` }}
        >
          <div className="flex items-center justify-between gap-3 mb-3">
            <div className="min-w-0 flex-1">
              <div className="font-semibold text-foreground">
                {(primaryColumn ?? columns[0])?.render(item)}
              </div>
            </div>
            {onRowClick && (
              <ChevronRightIcon className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
            )}
          </div>
          <div className="space-y-2">
            {mobileColumns.map((column, colIndex) => {
              if (!primaryColumn && colIndex === 0 && column === columns[0]) return null;
              return (
                <div key={column.key} className="flex items-center justify-between gap-4 text-sm">
                  <span className="text-muted-foreground font-medium flex-shrink-0">
                    {column.header}
                  </span>
                  <span className="text-foreground text-right min-w-0 truncate">
                    {column.render(item)}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function DesktopTableView<T extends { id: number | string }>({
  data,
  columns,
  onRowClick,
  className = "",
  forceTableView = false,
}: {
  data: T[];
  columns: Column<T>[];
  onRowClick: ((item: T) => void) | undefined;
  className: string;
  forceTableView: boolean;
}) {
  return (
    <div className={`${forceTableView ? "" : "hidden md:block"} overflow-x-auto`}>
      <table className={`min-w-full divide-y divide-border ${className}`}>
        <thead className="bg-muted/50">
          <tr>
            {columns.map(column => (
              <th
                key={column.key}
                className={`px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider ${column.className || ""}`}
              >
                {column.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="bg-card divide-y divide-border">
          {data.map(item => (
            <tr
              key={item.id}
              className={`hover:bg-muted/30 transition-colors duration-[var(--cp-transition-fast)] ${onRowClick ? "cursor-pointer" : ""}`}
              onClick={() => onRowClick?.(item)}
            >
              {columns.map(column => (
                <td
                  key={column.key}
                  className={`px-6 py-4 whitespace-nowrap ${column.className || ""}`}
                >
                  {column.render(item)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export function DataTable<T extends { id: number | string }>({
  data,
  columns,
  emptyState,
  onRowClick,
  className = "",
  forceTableView = false,
}: DataTableProps<T>) {
  if (data.length === 0 && emptyState) {
    return (
      <EmptyState
        icon={emptyState.icon}
        title={emptyState.title}
        description={emptyState.description}
        variant="compact"
      />
    );
  }

  return (
    <>
      {!forceTableView && <MobileCardView data={data} columns={columns} onRowClick={onRowClick} />}
      <DesktopTableView
        data={data}
        columns={columns}
        onRowClick={onRowClick}
        className={className}
        forceTableView={forceTableView}
      />
    </>
  );
}

export type { DataTableProps, Column };
