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

function DiffRow({ path, a, b }: { path: string; a: unknown; b: unknown }) {
  const f = (v: unknown) => v == null ? null : JSON.stringify(v, null, 2);
  const aStr = f(a);
  const bStr = f(b);
  return (
    <tr style={{ borderBottom: '1px solid var(--border)' }}>
      <td style={{ padding: '9px 14px', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text3)', verticalAlign: 'top', whiteSpace: 'nowrap', width: 240 }}>
        {path}
      </td>
      <td style={{ padding: '9px 14px', fontFamily: 'var(--font-mono)', fontSize: 15, color: 'var(--red)', background: 'var(--red-dim)', verticalAlign: 'top', whiteSpace: 'pre-wrap', wordBreak: 'break-all', width: '50%' }}>
        {aStr ?? <span style={{ color: 'var(--text3)' }}>null</span>}
      </td>
      <td style={{ padding: '9px 14px', fontFamily: 'var(--font-mono)', fontSize: 15, color: 'var(--green)', background: 'var(--green-dim)', verticalAlign: 'top', whiteSpace: 'pre-wrap', wordBreak: 'break-all', width: '50%' }}>
        {bStr ?? <span style={{ color: 'var(--text3)' }}>null</span>}
      </td>
    </tr>
  );
}

export function ExperimentDiffPage() {
  const { name, other } = useParams<{ name: string; other?: string }>();
  const expName = decodeURIComponent(name ?? '');
  const initialOther = other ? decodeURIComponent(other) : '';
  const [otherName, setOtherName] = useState(initialOther);
  const [submitted, setSubmitted] = useState(initialOther);

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

  const entries = data ? Object.entries(data) : [];

  return (
    <div style={{ padding: '36px 40px' }} className="fade-up">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
        <GitCompare size={17} style={{ color: 'var(--cyan)' }} />
        <h1 style={{ fontSize: 28, fontWeight: 700, color: 'var(--text1)', letterSpacing: '-0.02em' }}>Diff</h1>
      </div>

      <div style={{ display: 'flex', gap: 10, marginBottom: 24 }}>
        <div style={{
          padding: '8px 14px', background: 'var(--red-dim)', border: '1px solid var(--border)',
          borderRadius: 8, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--red)',
          minWidth: 240,
        }}>
          {expName}
        </div>
        <input
          type="text"
          placeholder="Compare with... (experiment name)"
          value={otherName}
          onChange={e => setOtherName(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && setSubmitted(otherName)}
          style={{ flex: 1, maxWidth: 400 }}
        />
        <button
          onClick={() => setSubmitted(otherName)}
          disabled={!otherName}
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '8px 18px', borderRadius: 8, fontSize: 13,
            background: 'var(--cyan-dim)', border: '1px solid rgba(0,119,182,0.25)',
            color: 'var(--cyan)', cursor: 'pointer', opacity: otherName ? 1 : 0.4,
          }}
        >
          <Search size={13} /> Compare
        </button>
      </div>

      {isLoading && <Loading />}
      {error && <ErrorState error={error as Error} />}

      {data && (
        <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
          {/* Column headers */}
          <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 1fr', borderBottom: '1px solid var(--border-md)', background: 'var(--bg2)' }}>
            <div style={{ padding: '11px 14px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Field</div>
            <div style={{ padding: '11px 14px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--red)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>{expName}</div>
            <div style={{ padding: '11px 14px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--green)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>{submitted}</div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <tbody>
              {entries.length === 0 ? (
                <tr>
                  <td colSpan={3} style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text3)', fontFamily: 'var(--font-mono)', fontSize: 15 }}>
                    identical — no differences found
                  </td>
                </tr>
              ) : (
                entries.map(([path, [a, b]]) => <DiffRow key={path} path={path} a={a} b={b} />)
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
