import { Alert, Badge, Container, Spinner, Table } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import AppBreadcrumb from '../components/AppBreadcrumb';
import { useStrategies } from '../api/hooks';
import type { Strategy } from '../types/api';

function strategyType(config: unknown): string {
  if (config && typeof config === 'object' && 'type' in config) {
    return String((config as Record<string, unknown>).type);
  }
  return 'unknown';
}

function candleInterval(config: unknown): string {
  if (config && typeof config === 'object' && 'candle_interval' in config) {
    return String((config as Record<string, unknown>).candle_interval);
  }
  return '—';
}

function ruleCount(config: unknown): string {
  if (
    config &&
    typeof config === 'object' &&
    'rules' in config &&
    Array.isArray((config as Record<string, unknown>).rules)
  ) {
    return String(((config as Record<string, unknown>).rules as unknown[]).length);
  }
  return '—';
}

function shortHash(hash: string): string {
  return hash.slice(0, 12);
}

function typeLabel(type: string): React.ReactNode {
  const map: Record<string, string> = {
    rule_based: 'primary',
  };
  return (
    <Badge bg={map[type] ?? 'secondary'} className="text-capitalize">
      {type.replace(/_/g, ' ')}
    </Badge>
  );
}

function StrategyRow({ strategy }: { strategy: Strategy }) {
  const navigate = useNavigate();
  const type = strategyType(strategy.config);
  return (
    <tr
      style={{ cursor: 'pointer' }}
      onClick={() => navigate(`/strategies/${strategy.id}`)}
    >
      <td>
        {strategy.name ? (
          <span>
            {strategy.name}
            <span className="text-muted ms-1" style={{ fontSize: '0.8em' }}>
              v{strategy.version}
            </span>
          </span>
        ) : (
          <code style={{ fontSize: '0.8em' }}>{shortHash(strategy.hash)}</code>
        )}
      </td>
      <td>{typeLabel(type)}</td>
      <td>{type === 'rule_based' ? candleInterval(strategy.config) : '—'}</td>
      <td>{type === 'rule_based' ? ruleCount(strategy.config) : '—'}</td>
      <td className="text-muted" style={{ fontSize: '0.85em' }}>
        {new Date(strategy.created_at).toLocaleString()}
      </td>
    </tr>
  );
}

export default function StrategiesPage() {
  const { data, isLoading, isError, error } = useStrategies();

  return (
    <Container>
      <AppBreadcrumb />
      <div className="d-flex align-items-center justify-content-between mb-3">
        <h5 className="mb-0">Strategies</h5>
        <Link to="/strategies/new" className="btn btn-primary btn-sm">
          New Strategy
        </Link>
      </div>

      {isLoading && <Spinner animation="border" size="sm" />}
      {isError && <Alert variant="danger">{String(error)}</Alert>}

      {data && data.length === 0 && (
        <p className="text-muted">
          No strategies yet. Create one above or submit a paper run — strategies are
          automatically discovered from run configs.
        </p>
      )}

      {data && data.length > 0 && (
        <Table striped bordered hover size="sm" responsive>
          <thead>
            <tr>
              <th>Name</th>
              <th>Type</th>
              <th>Interval</th>
              <th>Rules</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            {data.map((s) => (
              <StrategyRow key={s.id} strategy={s} />
            ))}
          </tbody>
        </Table>
      )}
    </Container>
  );
}
