import { useParams } from '@tanstack/react-router';
import { useState } from 'react';
import { useTrend, useTrendEvidence, useTrendProjection } from '../api/hooks';
import { TrendArrow, ConfidenceBar, StatusBadge, LoadingSpinner, Card } from '../components/ui';

export function TrendDetailPage() {
  const { id } = useParams({ from: '/trends/$id' });
  const { data: trend, isLoading } = useTrend(id);
  const { data: evidenceData } = useTrendEvidence(id);
  const { data: projection } = useTrendProjection(id);

  if (isLoading || !trend) return <LoadingSpinner />;

  const evidence = (evidenceData?.evidence ?? []) as Array<Record<string, unknown>>;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <h1 className="text-xl font-semibold text-gray-100">{trend.entity_id}</h1>
        <TrendArrow direction={trend.trend_direction} />
        <span className="rounded bg-surface-800 px-2 py-0.5 text-xs text-gray-400">{trend.window}</span>
      </div>

      <Card>
        <dl className="grid grid-cols-2 gap-x-8 gap-y-3 text-sm sm:grid-cols-4">
          <div>
            <dt className="text-gray-500">Direction</dt>
            <dd className="flex items-center gap-1 text-gray-200">
              <TrendArrow direction={trend.trend_direction} /> {trend.trend_direction}
            </dd>
          </div>
          <div>
            <dt className="text-gray-500">Strength</dt>
            <dd><ConfidenceBar value={trend.trend_strength} /></dd>
          </div>
          <div>
            <dt className="text-gray-500">Confidence</dt>
            <dd><ConfidenceBar value={trend.confidence} /></dd>
          </div>
          <div>
            <dt className="text-gray-500">Contradiction</dt>
            <dd className={`font-mono ${trend.contradiction_score > 0.5 ? 'text-yellow-400' : 'text-gray-300'}`}>
              {(trend.contradiction_score * 100).toFixed(0)}%
            </dd>
          </div>
          <div>
            <dt className="text-gray-500">Generated</dt>
            <dd className="text-gray-300">{new Date(trend.generated_at).toLocaleString()}</dd>
          </div>
        </dl>
      </Card>

      {trend.dominant_catalysts && trend.dominant_catalysts.length > 0 && (
        <Card>
          <h2 className="mb-2 text-sm font-medium text-gray-400">Dominant Catalysts</h2>
          <div className="flex flex-wrap gap-2">
            {trend.dominant_catalysts.map((c, i) => (
              <span key={i} className="rounded bg-surface-800 px-2 py-0.5 text-xs text-gray-300">{c}</span>
            ))}
          </div>
        </Card>
      )}

      {trend.material_risks && trend.material_risks.length > 0 && (
        <Card>
          <h2 className="mb-2 text-sm font-medium text-gray-400">Material Risks</h2>
          <ul className="ml-4 list-disc text-sm text-red-400">
            {trend.material_risks.map((r, i) => <li key={i}>{r}</li>)}
          </ul>
        </Card>
      )}

      {/* Trend Projection (Task 17.5) */}
      {projection && <TrendProjectionPanel projection={projection} />}

      {/* Evidence drill-down */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">Contributing Evidence ({evidence.length})</h2>
        {evidence.length === 0 ? (
          <p className="text-sm text-gray-500">No evidence records</p>
        ) : (
          <div className="space-y-2">
            {evidence.map((ev, i) => {
              const isMacro = String(ev.document_type) === 'macro_event' || String(ev.evidence_type) === 'macro_event';
              const isPattern = String(ev.evidence_type) === 'pattern_signal' || String(ev.document_type) === 'pattern_signal';
              const isCompetitive = String(ev.evidence_type) === 'competitive_signal' || String(ev.document_type) === 'competitive_signal';

              let borderClass = 'border-surface-700 bg-surface-950';
              if (isMacro) borderClass = 'border-purple-700/50 bg-purple-900/10';
              else if (isCompetitive) borderClass = 'border-cyan-700/50 bg-cyan-900/10';
              else if (isPattern) borderClass = 'border-amber-700/50 bg-amber-900/10';

              return (
                <div key={i} className={`rounded-lg border p-3 ${borderClass}`}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      {isMacro && <span className="rounded bg-purple-900/40 border border-purple-700/50 px-1.5 py-0.5 text-[10px] font-medium text-purple-400">MACRO</span>}
                      {isPattern && <span className="rounded bg-amber-900/40 border border-amber-700/50 px-1.5 py-0.5 text-[10px] font-medium text-amber-400">PATTERN</span>}
                      {isCompetitive && <span className="rounded bg-cyan-900/40 border border-cyan-700/50 px-1.5 py-0.5 text-[10px] font-medium text-cyan-400">COMPETITIVE</span>}
                      <StatusBadge status={String(ev.evidence_type)} />
                      <span className="text-sm text-gray-200">{String(ev.title ?? 'Untitled')}</span>
                    </div>
                    <span className="font-mono text-xs text-gray-500">rank: {((ev.rank_score as number) ?? 0).toFixed(3)}</span>
                  </div>
                  <div className="mt-1 flex gap-4 text-xs text-gray-500">
                    <span>{String(ev.document_type)}</span>
                    <span>{String(ev.source_type)}</span>
                    {ev.publisher ? <span>{String(ev.publisher)}</span> : null}
                    {ev.published_at ? <span>{new Date(String(ev.published_at)).toLocaleDateString()}</span> : null}
                  </div>
                  {ev.intelligence ? (
                    <div className="mt-2 text-xs text-gray-400">
                      <span className="text-gray-500">Summary: </span>
                      {String((ev.intelligence as Record<string, unknown>).summary ?? '—')}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
}

function TrendProjectionPanel({ projection }: { projection: import('../api/hooks').TrendProjection }) {
  const [expanded, setExpanded] = useState(false);

  return (
    <Card className={projection.diverges_from_current ? 'border-yellow-700/50' : ''}>
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-sm font-medium text-gray-400">
          Trend Projection
          {projection.diverges_from_current && (
            <span className="ml-2 rounded bg-yellow-900/40 border border-yellow-700/50 px-1.5 py-0.5 text-[10px] font-medium text-yellow-400">DIVERGENCE</span>
          )}
        </h2>
        <span className="rounded bg-surface-800 px-2 py-0.5 text-xs text-gray-400">{projection.projection_horizon}</span>
      </div>

      <dl className="grid grid-cols-2 gap-x-8 gap-y-3 text-sm sm:grid-cols-4">
        <div>
          <dt className="text-gray-500">Projected Direction</dt>
          <dd className="flex items-center gap-1 text-gray-200">
            <TrendArrow direction={projection.projected_direction} /> {projection.projected_direction}
          </dd>
        </div>
        <div>
          <dt className="text-gray-500">Projected Strength</dt>
          <dd><ConfidenceBar value={projection.projected_strength} /></dd>
        </div>
        <div>
          <dt className="text-gray-500">Projection Confidence</dt>
          <dd><ConfidenceBar value={projection.projected_confidence} /></dd>
        </div>
        <div>
          <dt className="text-gray-500">Macro Contribution</dt>
          <dd className="text-gray-200">{(projection.macro_contribution_pct * 100).toFixed(0)}%</dd>
        </div>
      </dl>

      {projection.driving_factors.length > 0 && (
        <div className="mt-3">
          <button
            onClick={() => setExpanded(!expanded)}
            className="text-xs text-brand-400 hover:underline"
          >
            {expanded ? 'Hide' : 'Show'} driving factors ({projection.driving_factors.length})
          </button>
          {expanded && (
            <ul className="mt-2 ml-4 list-disc text-sm text-gray-300">
              {projection.driving_factors.map((f, i) => <li key={i}>{f}</li>)}
            </ul>
          )}
        </div>
      )}
    </Card>
  );
}
