'use client';

import React from 'react';
import { Empty, Pagination, Skeleton } from 'antd';
import { Icon, type IconName } from '../ui/Icon';
import { ORG_STATUS_LABEL, ORG_STATUS_TONE } from './platformData';
import type { BadgeTone, OrganizationStatus } from './platformTypes';

export function PageHeader({ eyebrow, title, subtitle, actions }: { eyebrow: string; title: string; subtitle: string; actions?: React.ReactNode }) {
  return (
    <div className="tcx-page-head">
      <div>
        <div className="tcx-eyebrow">{eyebrow}</div>
        <h1 className="tcx-h1">{title}</h1>
        <p className="tcx-page-sub">{subtitle}</p>
      </div>
      {actions ? <div className="tcx-page-actions">{actions}</div> : null}
    </div>
  );
}

export function StatusBadge({ label, tone = 'gray', dot = true }: { label: string; tone?: BadgeTone; dot?: boolean }) {
  return (
    <span className={`tcx-badge tcx-tone-${tone}`}>
      {dot ? <i className="tcx-badge-dot" aria-hidden="true" /> : null}
      {label}
    </span>
  );
}

export function OrgStatusBadge({ status }: { status: OrganizationStatus }) {
  return <StatusBadge label={ORG_STATUS_LABEL[status] ?? status} tone={ORG_STATUS_TONE[status] ?? 'gray'} />;
}

export function ChipTag({ children, mono = false }: { children: React.ReactNode; mono?: boolean }) {
  return <span className={`tcx-chip ${mono ? 'font-mono text-[11.5px]' : ''}`}>{children}</span>;
}

export function KpiCard({ label, value, subtext, iconName, tone = 'k1', dark = false }: { label: string; value: string | number; subtext: string; iconName: IconName; tone?: 'k1' | 'k2' | 'k3' | 'k4'; dark?: boolean }) {
  return (
    <div className={`tcx-kpi tcx-s-3 tcx-kpi-${tone} ${dark ? 'tcx-kpi-dark' : ''}`}>
      <div className="tcx-kpi-row">
        <span className="tcx-kpi-ico">
          <Icon name={iconName} size={20} />
        </span>
      </div>
      <div className="tcx-kpi-label">{label}</div>
      <div className="tcx-kpi-val">{value}</div>
      <div className="tcx-kpi-sub">{subtext}</div>
    </div>
  );
}

export function KeyValueList({ rows }: { rows: Array<{ label: string; value: React.ReactNode }> }) {
  return (
    <div className="tcx-kv">
      {rows.map((row) => (
        <div key={row.label} className="tcx-kv-row">
          <span>{row.label}</span>
          <b>{row.value}</b>
        </div>
      ))}
    </div>
  );
}

export function FilterTabsBar({ tabs, activeKey, onChange }: { tabs: Array<{ key: string; label: string; count?: number }>; activeKey: string; onChange: (key: string) => void }) {
  return (
    <div className="tcx-tabs" role="tablist">
      {tabs.map((tab) => {
        const selected = tab.key === activeKey;
        return (
          <button key={tab.key} type="button" role="tab" aria-selected={selected} className={`tcx-tab ${selected ? 'tcx-tab-active' : ''}`} onClick={() => onChange(tab.key)}>
            {tab.label}
            {typeof tab.count === 'number' ? <span className="tcx-tab-n">{tab.count}</span> : null}
          </button>
        );
      })}
    </div>
  );
}

export function TablePager({ page, pageSize, total, onPageChange, onPageSizeChange, pageSizeOptions = ['10', '20', '50', '100'] }: { page: number; pageSize: number; total: number; onPageChange: (nextPage: number) => void; onPageSizeChange?: (nextPageSize: number) => void; pageSizeOptions?: string[] }) {
  const start = total === 0 ? 0 : (page - 1) * pageSize + 1;
  const end = Math.min(total, page * pageSize);

  return (
    <div className="tcx-table-foot">
      <span>
        Showing <b>{start}</b> to <b>{end}</b> of <b>{total}</b> results
      </span>
      <Pagination
        current={page}
        pageSize={pageSize}
        total={total}
        showSizeChanger={true}
        pageSizeOptions={pageSizeOptions}
        showQuickJumper={false}
        onChange={(newPage, newPageSize) => {
          if (newPageSize && newPageSize !== pageSize) {
            onPageSizeChange?.(newPageSize);
            onPageChange(1);
          } else {
            onPageChange(newPage);
          }
        }}
      />
    </div>
  );
}

export interface DataTableColumn<T> {
  key: string;
  dataIndex?: string;
  title?: string;
  label?: string;
  right?: boolean;
  align?: 'left' | 'center' | 'right';
  width?: string | number;
  sortable?: boolean;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  render?: (value: any, record: T, index: number) => React.ReactNode;
}

export interface DataTableProps<T> {
  columns: DataTableColumn<T>[];
  data: T[];
  rowKey?: (row: T, index: number) => string;
  loading?: boolean;
  emptyText?: React.ReactNode;
  emptyAction?: React.ReactNode;
  onRowClick?: (row: T) => void;
  sort?: { key: string; dir: 'asc' | 'desc' };
  onSortChange?: (key: string) => void;
  className?: string;
  pagination?: {
    page: number;
    pageSize: number;
    total: number;
    onPageChange: (nextPage: number) => void;
    onPageSizeChange?: (nextPageSize: number) => void;
    pageSizeOptions?: string[];
  };
}

export function DataTable<T>({ columns, data, rowKey, loading = false, emptyText = 'No records found', emptyAction, onRowClick, sort, onSortChange, className = '', pagination }: DataTableProps<T>) {
  const getKey = (row: T, idx: number): string => {
    if (rowKey) return rowKey(row, idx);
    const r = row as Record<string, unknown>;
    return typeof r.id === 'string' ? r.id : String(idx);
  };

  return (
    <div className={`tcx-surface-card overflow-hidden ${className}`}>
      {loading && data.length === 0 ? (
        <div className="p-6">
          <Skeleton active paragraph={{ rows: 6 }} />
        </div>
      ) : data.length === 0 ? (
        <div className="py-14 text-center">
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={typeof emptyText === 'string' ? <span className="text-[var(--tcx-muted)]">{emptyText}</span> : emptyText}>
            {emptyAction}
          </Empty>
        </div>
      ) : (
        <>
          <div className="tcx-table-scroll" aria-busy={loading}>
            <table className={`tcx-table ${loading ? 'opacity-60' : ''}`}>
              <thead>
                <tr>
                  {columns.map((col) => {
                    const headerLabel = col.label ?? col.title ?? '';
                    const isRight = col.right || col.align === 'right';
                    const isSorted = sort?.key === col.key;
                    return (
                      <th key={col.key} className={isRight ? 'tcx-right' : undefined} style={col.width ? { width: col.width } : undefined} aria-sort={isSorted ? (sort?.dir === 'asc' ? 'ascending' : 'descending') : undefined}>
                        {col.sortable && onSortChange ? (
                          <button type="button" className="tcx-th-sort" onClick={() => onSortChange(col.key)}>
                            {headerLabel}
                            {isSorted ? <Icon name="chevronDown" size={12} className={sort?.dir === 'asc' ? 'rotate-180' : ''} /> : null}
                          </button>
                        ) : (
                          headerLabel
                        )}
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {data.map((row, idx) => {
                  const key = getKey(row, idx);
                  return (
                    <tr
                      key={key}
                      className={onRowClick ? 'tcx-row-click' : undefined}
                      onClick={onRowClick ? () => onRowClick(row) : undefined}
                      onKeyDown={
                        onRowClick
                          ? (e) => {
                              if (e.key === 'Enter') onRowClick(row);
                            }
                          : undefined
                      }
                      tabIndex={onRowClick ? 0 : undefined}
                    >
                      {columns.map((col) => {
                        const isRight = col.right || col.align === 'right';
                        const propKey = col.dataIndex ?? col.key;
                        const rawVal = (row as Record<string, unknown>)[propKey];
                        let cellContent: React.ReactNode;
                        if (!col.render) {
                          cellContent = rawVal !== null && rawVal !== undefined ? String(rawVal) : '—';
                        } else {
                          const firstArg = rawVal !== undefined ? rawVal : row;
                          cellContent = col.render(firstArg, row, idx);
                        }
                        return (
                          <td key={col.key} className={isRight ? 'tcx-right' : undefined}>
                            {cellContent}
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {pagination && <TablePager page={pagination.page} pageSize={pagination.pageSize} total={pagination.total} onPageChange={pagination.onPageChange} onPageSizeChange={pagination.onPageSizeChange} pageSizeOptions={pagination.pageSizeOptions} />}
        </>
      )}
    </div>
  );
}
