import { Accordion, Alert, Badge, Card, Col, Container, Row, Spinner, Table } from 'react-bootstrap';
import { Link, useParams } from 'react-router-dom';
import AppBreadcrumb from '../components/AppBreadcrumb';
import { useStrategy, usePaperRuns } from '../api/hooks';
import type { PaperRun } from '../types/api';

// --- helpers ---

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

const STATUS_BADGE: Record<PaperRun['status'], { bg: string; text?: string }> = {
  queued: { bg: 'info', text: 'dark' },
  running: { bg: 'primary' },
  complete: { bg: 'success' },
  failed: { bg: 'danger' },
  cancelled: { bg: 'secondary' },
};

function instrument(config: unknown): string {
  const c = config as Record<string, unknown> | null;
  const instr = c?.instrument as Record<string, unknown> | null;
  return String(instr?.name_exchange ?? '—');
}

function pnlDisplay(run: PaperRun): string {
  const summary = run.result_summary as Record<string, unknown> | null;
  if (!summary) return '—';
  const portfolios = summary.portfolios as Record<string, unknown>[] | null;
  if (!portfolios || portfolios.length === 0) return '—';
  let pnl = 0;
  for (const p of portfolios) {
    const stats = p.statistics as Record<string, unknown> | null;
    if (stats?.pnl != null) pnl += Number(stats.pnl);
  }
  const sign = pnl >= 0 ? '+' : '';
  return `${sign}${pnl.toFixed(2)}`;
}

// Render the rules for a rule_based strategy config
function RulesList({ config }: { config: unknown }) {
  const c = config as Record<string, unknown> | null;
  if (!c || c.type !== 'rule_based') return null;
  const rules = c.rules as Array<Record<string, unknown>> | null;
  if (!rules || rules.length === 0) return <p className="text-muted mb-0">No rules defined.</p>;

  return (
    <ol className="mb-0 ps-3" style={{ fontSize: '0.875em' }}>
      {rules.map((rule, i) => {
        const comment = rule.comment as string | undefined;
        const then = rule.then as Record<string, unknown> | null;
        return (
          <li key={i} className="mb-2">
            {comment && <div className="text-muted">{comment}</div>}
            <div>
              <span className="me-2">
                <Badge bg={then?.side === 'buy' ? 'success' : 'danger'}>
                  {String(then?.side ?? '?')}
                </Badge>
              </span>
              <code>{JSON.stringify(then?.quantity ?? '')}</code>
            </div>
          </li>
        );
      })}
    </ol>
  );
}

// Linked backtest table
function BacktestTable({ strategyId }: { strategyId: string }) {
  const { data, isLoading, isError } = usePaperRuns(undefined, strategyId);

  if (isLoading) return <Spinner animation="border" size="sm" />;
  if (isError) return <Alert variant="danger">Failed to load backtests.</Alert>;
  if (!data || data.length === 0) {
    return (
      <p className="text-muted mb-0">
        No backtests yet.{' '}
        <Link to={`/paper-runs/new?strategy_id=${strategyId}`}>Create one</Link> — it will be linked here automatically.
      </p>
    );
  }

  return (
    <Table striped bordered hover size="sm" responsive className="mb-0">
      <thead>
        <tr>
          <th>Status</th>
          <th>Mode</th>
          <th>Instrument</th>
          <th>Interval</th>
          <th>Start</th>
          <th>End</th>
          <th>P&amp;L</th>
        </tr>
      </thead>
      <tbody>
        {data.map((run) => {
          const badge = STATUS_BADGE[run.status];
          const pnl = pnlDisplay(run);
          const pnlNum = parseFloat(pnl);
          return (
            <tr
              key={run.id}
              style={{ cursor: 'pointer' }}
              onClick={() => (window.location.href = `/paper-runs/${run.id}`)}
            >
              <td>
                <Badge bg={badge.bg} text={badge.text as never}>
                  {run.status}
                </Badge>
              </td>
              <td>
                <Badge bg={run.mode === 'backtest' ? 'secondary' : 'primary'}>
                  {run.mode}
                </Badge>
              </td>
              <td>{instrument(run.config)}</td>
              <td>{run.candle_interval ?? '—'}</td>
              <td style={{ fontSize: '0.8em' }}>{new Date(run.starts_at).toLocaleDateString()}</td>
              <td style={{ fontSize: '0.8em' }}>{new Date(run.finishes_at).toLocaleDateString()}</td>
              <td
                style={{
                  color: pnl === '—' ? undefined : pnlNum >= 0 ? 'green' : 'red',
                  fontWeight: pnl !== '—' ? 600 : undefined,
                }}
              >
                {pnl}
              </td>
            </tr>
          );
        })}
      </tbody>
    </Table>
  );
}

// Render description as pre-formatted text (preserves markdown structure without a parser dep)
function DescriptionBlock({ markdown }: { markdown: string }) {
  if (!markdown.trim()) return null;
  return (
    <Card className="mb-3">
      <Card.Header>Description</Card.Header>
      <Card.Body>
        <pre
          style={{
            fontFamily: 'inherit',
            fontSize: '0.875em',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
            margin: 0,
          }}
        >
          {markdown.trim()}
        </pre>
      </Card.Body>
    </Card>
  );
}

// --- Page ---

export default function StrategyDetailPage() {
  const { id } = useParams<{ id: string }>();
  const { data: strategy, isLoading, isError, error } = useStrategy(id);

  if (isLoading) {
    return (
      <Container>
        <AppBreadcrumb />
        <Spinner animation="border" />
      </Container>
    );
  }

  if (isError || !strategy) {
    return (
      <Container>
        <AppBreadcrumb />
        <Alert variant="danger">{error ? String(error) : 'Strategy not found.'}</Alert>
      </Container>
    );
  }

  const config = strategy.config as Record<string, unknown>;
  const type = String(config.type ?? 'unknown');
  const isRuleBased = type === 'rule_based';

  return (
    <Container>
      <AppBreadcrumb />

      {/* Header */}
      <Card className="mb-3">
        <Card.Body>
          <div className="d-flex align-items-start justify-content-between flex-wrap gap-2">
            <div>
              <h5 className="mb-1">
                {strategy.name ? (
                  <>
                    <span className="me-2">{strategy.name}</span>
                    <Badge bg="secondary" className="me-2">
                      v{strategy.version}
                    </Badge>
                    <Badge bg="primary" className="me-2 text-capitalize" style={{ fontSize: '0.75em' }}>
                      {type.replace(/_/g, ' ')}
                    </Badge>
                  </>
                ) : (
                  <Badge bg="primary" className="me-2 text-capitalize">
                    {type.replace(/_/g, ' ')}
                  </Badge>
                )}
                <code style={{ fontSize: '0.85em' }}>{shortHash(strategy.hash)}</code>
              </h5>
              <div className="text-muted" style={{ fontSize: '0.85em' }}>
                Created {new Date(strategy.created_at).toLocaleString()}
              </div>
            </div>
            <Link to={`/paper-runs/new?strategy_id=${strategy.id}`} className="btn btn-outline-primary btn-sm">
              New Backtest
            </Link>
          </div>

          {isRuleBased && (
            <Row className="mt-3">
              <Col xs="auto">
                <div className="text-muted" style={{ fontSize: '0.8em' }}>INTERVAL</div>
                <strong>{String(config.candle_interval ?? '—')}</strong>
              </Col>
              <Col xs="auto">
                <div className="text-muted" style={{ fontSize: '0.8em' }}>RULES</div>
                <strong>
                  {Array.isArray(config.rules) ? config.rules.length : '—'}
                </strong>
              </Col>
              <Col xs="auto">
                <div className="text-muted" style={{ fontSize: '0.8em' }}>ID</div>
                <code style={{ fontSize: '0.8em' }}>{strategy.id}</code>
              </Col>
            </Row>
          )}
        </Card.Body>
      </Card>

      {/* Description */}
      {strategy.description && <DescriptionBlock markdown={strategy.description} />}

      {/* Rules */}
      {isRuleBased && (
        <Card className="mb-3">
          <Card.Header>Rules</Card.Header>
          <Card.Body>
            <RulesList config={strategy.config} />
          </Card.Body>
        </Card>
      )}

      {/* Backtests */}
      <Card className="mb-3">
        <Card.Header>Backtests</Card.Header>
        <Card.Body>
          <BacktestTable strategyId={strategy.id} />
        </Card.Body>
      </Card>

      {/* Raw config */}
      <Accordion className="mb-3">
        <Accordion.Item eventKey="0">
          <Accordion.Header>Full Config JSON</Accordion.Header>
          <Accordion.Body>
            <pre style={{ fontSize: '0.8em', maxHeight: '400px', overflowY: 'auto' }}>
              {JSON.stringify(strategy.config, null, 2)}
            </pre>
          </Accordion.Body>
        </Accordion.Item>
        <Accordion.Item eventKey="1">
          <Accordion.Header>Hash Input (normalized)</Accordion.Header>
          <Accordion.Body>
            <pre style={{ fontSize: '0.8em', maxHeight: '300px', overflowY: 'auto' }}>
              {JSON.stringify(strategy.hash_input, null, 2)}
            </pre>
          </Accordion.Body>
        </Accordion.Item>
      </Accordion>
    </Container>
  );
}
