/**
 * PromptRail — Durable prompt execution history rail.
 * Each turn shows: prompt text → revision produced → components created → assumptions made.
 * Replaces ephemeral chat; turns are durable (stored as PromptExecution objects).
 */
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown, CheckCircle2, AlertCircle, Loader2, Clock, BarChart2, GitCommit } from 'lucide-react';
import type { ExecutionEntry } from '../hooks/useOracleExecution';
import type { PromptExecution } from '../types/canvas';

interface PromptRailProps {
  history: ExecutionEntry[];
  inFlight: PromptExecution | null;
  isOpen: boolean;
  onToggle: () => void;
}

const STATUS_ICONS = {
  completed: { Icon: CheckCircle2, color: '#34d399' },
  failed: { Icon: AlertCircle, color: '#f87171' },
  planning: { Icon: Loader2, color: '#60a5fa', spin: true },
  executing: { Icon: Loader2, color: '#a78bfa', spin: true },
  received: { Icon: Clock, color: '#94a3b8' },
  validated: { Icon: CheckCircle2, color: '#34d399' },
  clarification_required: { Icon: AlertCircle, color: '#fbbf24' },
};

function ExecutionTurnCard({ entry }: { entry: ExecutionEntry }) {
  const [expanded, setExpanded] = useState(false);
  const { execution } = entry;
  const cfg = STATUS_ICONS[execution.status] ?? STATUS_ICONS.received;
  const Icon = cfg.Icon;

  return (
    <div
      className="rounded-xl overflow-hidden"
      style={{ background: 'rgba(255,255,255,0.025)', border: '1px solid rgba(255,255,255,0.07)' }}
    >
      <button
        className="w-full flex items-start gap-3 p-3 text-left hover:bg-white/[0.02] transition-colors"
        onClick={() => setExpanded((p) => !p)}
      >
        <Icon
          className="w-3.5 h-3.5 mt-0.5 flex-shrink-0"
          style={{ color: cfg.color, animation: 'spin' in cfg && cfg.spin ? 'spin 1s linear infinite' : undefined }}
        />
        <div className="min-w-0 flex-1">
          <p className="text-xs text-zinc-200 line-clamp-2 leading-relaxed">
            {execution.prompt}
          </p>
          {execution.summary && (
            <p className="text-[10px] text-zinc-500 mt-1 line-clamp-1">{execution.summary}</p>
          )}
        </div>
        <ChevronDown
          className="w-3.5 h-3.5 text-zinc-600 flex-shrink-0 mt-0.5 transition-transform"
          style={{ transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)' }}
        />
      </button>

      <AnimatePresence>
        {expanded && (
          <motion.div
            initial={{ height: 0 }}
            animate={{ height: 'auto' }}
            exit={{ height: 0 }}
            className="overflow-hidden"
          >
            <div className="px-3 pb-3 space-y-2.5 border-t border-white/[0.06] pt-2.5">
              {/* Revision produced */}
              <div className="flex items-center gap-2">
                <GitCommit className="w-3 h-3 text-zinc-600" />
                <span className="text-[10px] text-zinc-500">
                  Produced revision on <span className="text-zinc-400">{execution.branchId}</span>
                </span>
              </div>

              {/* Components created */}
              {entry.componentsCreated.length > 0 && (
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <BarChart2 className="w-3 h-3 text-blue-500" />
                    <span className="text-[10px] text-zinc-500">Components created</span>
                  </div>
                  {entry.componentsCreated.map((cid) => (
                    <div key={cid} className="text-[10px] text-blue-300 font-mono pl-5 truncate">
                      {cid}
                    </div>
                  ))}
                </div>
              )}

              {/* Warnings */}
              {execution.warnings.length > 0 && (
                <div>
                  <p className="text-[10px] text-amber-500 uppercase tracking-wider mb-1">Warnings</p>
                  {execution.warnings.map((w, i) => (
                    <p key={i} className="text-[10px] text-amber-300/80 pl-2 border-l border-amber-500/30 mb-0.5">
                      {w}
                    </p>
                  ))}
                </div>
              )}

              {/* Timestamps */}
              <div className="flex items-center justify-between text-[10px] text-zinc-600 pt-1">
                <span className="font-mono">{new Date(execution.createdAt).toLocaleTimeString()}</span>
                {execution.completedAt && (
                  <span>
                    {Math.round((new Date(execution.completedAt).getTime() - new Date(execution.createdAt).getTime()) / 1000)}s
                  </span>
                )}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export function PromptRail({ history, inFlight, isOpen, onToggle }: PromptRailProps) {
  return (
    <div
      className="flex-shrink-0 flex flex-col"
      style={{
        width: isOpen ? 280 : 0,
        overflow: 'hidden',
        transition: 'width 0.25s cubic-bezier(0.4,0,0.2,1)',
        borderLeft: isOpen ? '1px solid rgba(255,255,255,0.07)' : 'none',
      }}
    >
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="flex flex-col h-full overflow-hidden"
            style={{ width: 280 }}
          >
            {/* Rail header */}
            <div
              className="flex items-center justify-between px-4 py-3 flex-shrink-0"
              style={{ borderBottom: '1px solid rgba(255,255,255,0.06)' }}
            >
              <div>
                <p className="text-xs font-semibold text-zinc-200">Prompt History</p>
                <p className="text-[10px] text-zinc-600">{history.length} execution{history.length !== 1 ? 's' : ''}</p>
              </div>
              <button
                onClick={onToggle}
                className="text-zinc-600 hover:text-zinc-400 transition-colors"
              >
                <ChevronDown className="w-4 h-4 rotate-90" />
              </button>
            </div>

            {/* Scrollable turns */}
            <div className="flex-1 overflow-y-auto custom-scrollbar px-3 py-3 space-y-2">
              {/* In-flight */}
              <AnimatePresence>
                {inFlight && (
                  <motion.div
                    key="inflight"
                    initial={{ opacity: 0, y: -8 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0 }}
                    className="rounded-xl p-3"
                    style={{
                      background: 'rgba(59,130,246,0.08)',
                      border: '1px dashed rgba(59,130,246,0.25)',
                    }}
                  >
                    <div className="flex items-start gap-2">
                      <Loader2 className="w-3.5 h-3.5 text-blue-400 animate-spin flex-shrink-0 mt-0.5" />
                      <div>
                        <p className="text-[10px] text-blue-300 font-medium uppercase tracking-wider mb-0.5">
                          {inFlight.status}
                        </p>
                        <p className="text-xs text-zinc-300 line-clamp-2">{inFlight.prompt}</p>
                      </div>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

              {/* Historical turns — newest first */}
              {[...history].reverse().map((entry, i) => (
                <ExecutionTurnCard key={entry.execution.executionId + i} entry={entry} />
              ))}

              {history.length === 0 && !inFlight && (
                <div className="text-center py-8">
                  <p className="text-xs text-zinc-600">Submit a prompt to see execution history here.</p>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
