import { useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { GitBranch } from 'lucide-react';
import { experimentsApi } from '../api/client';
import { Loading, ErrorState } from '../components/common/Loading';
import { LineageTree } from '../components/experiments/LineageTree';

export function LineagePage() {
  const { name } = useParams<{ name: string }>();
  const expName = decodeURIComponent(name ?? '');

  const { data, isLoading, error } = useQuery({
    queryKey: ['lineage', expName],
    queryFn: () => experimentsApi.lineage(expName),
    enabled: !!expName,
  });

  return (
    <div style={{ padding: '36px 40px' }} className="fade-up">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
        <GitBranch size={17} style={{ color: 'var(--cyan)' }} />
        <h1 style={{ fontSize: 28, fontWeight: 700, color: 'var(--text1)', letterSpacing: '-0.02em' }}>
          Strategy Tree
        </h1>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 15, color: 'var(--cyan)' }}>
          {expName}
        </span>
      </div>
      {isLoading && <Loading />}
      {error && <ErrorState error={error as Error} />}
      {data && data.tree && (
        <LineageTree
          tree={data.tree}
          ancestorChain={data.ancestor_chain as any[]}
          current={expName}
          height={680}
        />
      )}
      {data && !data.tree && (
        <div style={{ padding: '64px 0', textAlign: 'center', color: 'var(--text3)', fontFamily: 'var(--font-mono)', fontSize: 15 }}>
          lineage data not available
        </div>
      )}
    </div>
  );
}
