import { useNavigate } from 'react-router-dom';
import type { Symbol } from '../types';
import { DataTable } from '@/components/ui/DataTable';
import type { ColumnDef } from '@tanstack/react-table';

interface SymbolsTableProps {
  symbols: Symbol[];
  isLoading?: boolean;
}

export function SymbolsTable({ symbols, isLoading }: SymbolsTableProps) {
  const navigate = useNavigate();

  const formatMarketCap = (value?: number) => {
    if (!value) return '-';
    if (value >= 1e12) return `$${(value / 1e12).toFixed(2)}T`;
    if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
    if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
    return `$${value.toLocaleString()}`;
  };

  const columns: ColumnDef<Symbol>[] = [
    {
      accessorKey: 'symbol',
      header: 'Symbol',
      size: 120,
      cell: ({ row }) => (
        <div>
          <div className="text-sm font-medium text-text-primary">{row.original.symbol}</div>
          <div className="text-xs text-text-secondary">{row.original.currency}</div>
        </div>
      ),
    },
    {
      accessorKey: 'name',
      header: 'Name',
      size: 250,
      cell: ({ getValue }) => (
        <div className="text-sm text-text-primary">{getValue() as string}</div>
      ),
    },
    {
      accessorKey: 'exchange',
      header: 'Exchange',
      size: 150,
      cell: ({ row }) => (
        <div>
          <div className="text-sm text-text-primary">{row.original.exchange}</div>
          <div className="text-xs text-text-secondary">{row.original.country}</div>
        </div>
      ),
    },
    {
      accessorKey: 'type',
      header: 'Type',
      size: 120,
      cell: ({ getValue }) => (
        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-primary-100 text-primary-800">
          {getValue() as string}
        </span>
      ),
    },
    {
      accessorKey: 'marketCap',
      header: 'Market Cap',
      size: 120,
      cell: ({ getValue }) => (
        <span className="text-sm text-text-primary">{formatMarketCap(getValue() as number)}</span>
      ),
    },
    {
      accessorKey: 'sector',
      header: 'Sector',
      size: 200,
      cell: ({ row }) => (
        <div>
          <div className="text-sm text-text-primary">{row.original.sector || '-'}</div>
          <div className="text-xs text-text-secondary">{row.original.industry || '-'}</div>
        </div>
      ),
    },
  ];

  if (symbols.length === 0 && !isLoading) {
    return (
      <div className="bg-surface-secondary border-t border-border p-8">
        <div className="text-center text-text-secondary">
          No symbols found matching your criteria
        </div>
      </div>
    );
  }

  return (
    <DataTable
      data={symbols}
      columns={columns}
      loading={isLoading}
      onRowClick={(symbol) => navigate(`/symbols/${symbol.symbol}`)}
      className="border-0 rounded-none border-t h-full"
    />
  );
}