import React from 'react';
import { MagnifyingGlassIcon, ChevronUpIcon, ChevronDownIcon, ChevronUpDownIcon } from '@heroicons/react/24/outline';

export interface Column<T> {
  key: string;
  header: string;
  render?: (row: T) => React.ReactNode;
  sortable?: boolean;
  className?: string;
}

interface Props<T> {
  columns: Column<T>[];
  data: T[];
  loading?: boolean;
  searchValue?: string;
  onSearchChange?: (v: string) => void;
  searchPlaceholder?: string;
  actions?: (row: T) => React.ReactNode;
  emptyMessage?: string;
  emptyAction?: React.ReactNode;
  headerExtra?: React.ReactNode;
  sortKey?: string | null;
  sortDir?: 'asc' | 'desc';
  onSort?: (key: string) => void;
  /** محتوای ردیف بازشونده‌ی زیر هر ردیف؛ `null`/`undefined` یعنی بسته است. */
  renderExpanded?: (row: T) => React.ReactNode;
}

function SkeletonRow({ cols }: { cols: number }) {
  return (
    <tr>
      {Array.from({ length: cols }).map((_, i) => (
        <td key={i}>
          <div className="skeleton" style={{ height: 14, borderRadius: 6, width: `${55 + (i * 17) % 40}%` }} />
        </td>
      ))}
    </tr>
  );
}

export default function DataTable<T extends object>({
  columns,
  data,
  loading,
  searchValue,
  onSearchChange,
  searchPlaceholder = 'جستجو...',
  actions,
  emptyMessage = 'هیچ موردی یافت نشد',
  emptyAction,
  headerExtra,
  sortKey,
  sortDir,
  onSort,
  renderExpanded,
}: Props<T>) {
  const allColumns = actions
    ? [...columns, { key: '__actions', header: 'اقدامات', className: 'w-[120px]' }]
    : columns;

  return (
    <div>
      {/* Toolbar row */}
      {(onSearchChange !== undefined || headerExtra) && (
        // لنگرهای data-tour اینجا تعریف می‌شوند تا هر صفحه‌ای که DataTable دارد
        // بدون تغییر کد خودش، در تور راهنما قابل اشاره باشد.
        <div className="toolbar" data-tour="page-toolbar">
          {onSearchChange !== undefined && (
            <div className="field" data-tour="page-search" style={{ flex: '0 0 auto', minWidth: 240 }}>
              <MagnifyingGlassIcon style={{ width: 16, height: 16, flexShrink: 0 }} />
              <input
                type="text"
                value={searchValue}
                onChange={(e) => onSearchChange(e.target.value)}
                placeholder={searchPlaceholder}
              />
            </div>
          )}
          {headerExtra && <>{headerExtra}</>}
        </div>
      )}

      <div className="table-wrap" data-tour="page-table">
        <table className="t">
          <thead>
            <tr>
              {allColumns.map((col) => {
                const sortable = (col as Column<T>).sortable && onSort;
                const active = sortKey === col.key;
                return (
                  <th
                    key={col.key}
                    className={col.className ?? ''}
                    onClick={sortable ? () => onSort!(col.key) : undefined}
                    style={sortable ? { cursor: 'pointer', userSelect: 'none' } : undefined}
                  >
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      {col.header}
                      {sortable && (
                        active
                          ? (sortDir === 'desc'
                              ? <ChevronDownIcon style={{ width: 13, height: 13 }} />
                              : <ChevronUpIcon style={{ width: 13, height: 13 }} />)
                          : <ChevronUpDownIcon style={{ width: 13, height: 13, opacity: 0.4 }} />
                      )}
                    </span>
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 6 }).map((_, i) => (
                <SkeletonRow key={i} cols={allColumns.length} />
              ))
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={allColumns.length}>
                  <div style={{ textAlign: 'center', padding: '48px 20px' }}>
                    <div style={{
                      width: 56, height: 56, borderRadius: 16, background: 'var(--surface-2)',
                      display: 'grid', placeItems: 'center', margin: '0 auto 12px',
                    }}>
                      <svg style={{ width: 28, height: 28, color: 'var(--text-3)' }} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                          d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                      </svg>
                    </div>
                    <p style={{ fontSize: 13.5, color: 'var(--text-3)', margin: '0 0 12px' }}>{emptyMessage}</p>
                    {emptyAction}
                  </div>
                </td>
              </tr>
            ) : (
              data.map((row, rowIdx) => {
                const expanded = renderExpanded?.(row);
                return (
                  <React.Fragment key={rowIdx}>
                    <tr>
                      {columns.map((col) => (
                        <td key={col.key} className={col.className ?? ''}>
                          {col.render
                            ? col.render(row)
                            : ((row as Record<string, unknown>)[col.key] as React.ReactNode) ?? '—'}
                        </td>
                      ))}
                      {actions && (
                        <td>
                          <div className="row-actions">
                            {actions(row)}
                          </div>
                        </td>
                      )}
                    </tr>
                    {expanded && (
                      <tr>
                        <td colSpan={allColumns.length} style={{ height: 'auto', padding: '12px 16px', background: 'var(--surface-2)' }}>
                          {expanded}
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
