import morphData from 'virtual:morph-data';

// ─── Constants ────────────────────────────────────────────────────────────────

const PHASE_ORDER = ['proposal', 'uiux', 'plan', 'implement', 'review'];

const STATUS_BADGE = {
  in_progress: { label: 'In Progress', bg: 'bg-blue-900/60', border: 'border-blue-600', text: 'text-blue-300' },
  completed:   { label: 'Completed',   bg: 'bg-green-900/60', border: 'border-green-600', text: 'text-green-300' },
  draft:       { label: 'Draft',        bg: 'bg-gray-800',    border: 'border-gray-600', text: 'text-gray-400' },
};

const TASK_STATUS_ICON = {
  completed:   { icon: '✓', color: 'text-green-400' },
  in_progress: { icon: '►', color: 'text-blue-400' },
  pending:     { icon: '○', color: 'text-gray-600' },
};

// ─── Sub Components ───────────────────────────────────────────────────────────

function StatusBadge({ status }) {
  const s = STATUS_BADGE[status] || STATUS_BADGE.draft;
  return (
    <span className={`px-2 py-0.5 rounded text-xs font-medium border ${s.bg} ${s.border} ${s.text}`}>
      {s.label}
    </span>
  );
}

function PhaseProgressBar({ currentPhase, approvals }) {
  const approvedSet = new Set(Object.keys(approvals || {}));
  const currentIdx = PHASE_ORDER.indexOf(currentPhase);

  return (
    <div className="flex gap-1 mt-2">
      {PHASE_ORDER.map((phase, idx) => {
        const isCurrent = phase === currentPhase;
        const isApproved = approvedSet.has(phase);
        const isPast = idx < currentIdx && !isCurrent;
        const isFuture = idx > currentIdx;

        let bg, text, extra;
        if (isApproved) {
          bg = 'bg-green-800 border-green-600';
          text = 'text-green-300';
          extra = '✓';
        } else if (isCurrent) {
          bg = 'bg-blue-800 border-blue-500';
          text = 'text-blue-100 font-bold';
          extra = null;
        } else if (isFuture) {
          bg = 'bg-gray-800 border-gray-700';
          text = 'text-gray-600';
          extra = null;
        } else {
          // Past but not approved
          bg = 'bg-gray-700 border-gray-600';
          text = 'text-gray-400';
          extra = null;
        }

        return (
          <div
            key={phase}
            className={`flex-1 px-1 py-1 rounded border text-center text-[9px] leading-tight ${bg} ${text}`}
            title={phase}
          >
            <div className="truncate">{phase}</div>
            {extra && <div className="text-[8px] mt-0.5">{extra}</div>}
          </div>
        );
      })}
    </div>
  );
}

function TaskList({ taskList }) {
  if (!taskList?.length) return <p className="text-gray-600 text-xs italic">No tasks</p>;

  return (
    <div className="space-y-1">
      {taskList.map((task, i) => {
        const status = task.status || 'pending';
        const { icon, color } = TASK_STATUS_ICON[status] || TASK_STATUS_ICON.pending;
        return (
          <div key={i} className="flex items-start gap-2 text-xs">
            <span className={`${color} font-mono flex-shrink-0 mt-0.5 w-3 text-center`}>{icon}</span>
            <span className={`flex-1 leading-snug ${status === 'completed' ? 'text-gray-500' : 'text-gray-300'}`}>
              {task.text || task.description || String(task)}
            </span>
            {task.agent && (
              <span className="text-gray-600 text-[10px] font-mono flex-shrink-0 ml-1">{task.agent}</span>
            )}
          </div>
        );
      })}
    </div>
  );
}

function FeatureCard({ featureId, feature }) {
  const status = feature.status || 'draft';
  const phase = feature.phase || feature.currentPhase || PHASE_ORDER[0];
  const approvals = feature.approvals || {};
  const taskList = Array.isArray(feature.taskList)
    ? feature.taskList
    : typeof feature.taskList === 'object' && feature.taskList !== null
      ? Object.values(feature.taskList)
      : [];

  return (
    <div className="bg-gray-900 border border-gray-700 rounded-xl p-4 space-y-3">
      {/* Header */}
      <div className="flex items-center justify-between gap-3">
        <h3 className="text-white font-semibold text-sm truncate">{featureId}</h3>
        <div className="flex items-center gap-1.5 flex-shrink-0">
          {feature._worktree && (
            <span
              className="px-2 py-0.5 rounded text-xs font-medium border bg-purple-900/60 border-purple-600 text-purple-300"
              title={`In progress in .worktrees/${feature._worktree}`}
            >
              worktree
            </span>
          )}
          <StatusBadge status={status} />
        </div>
      </div>

      {/* Phase progress */}
      <div>
        <p className="text-gray-500 text-[10px] uppercase tracking-wide mb-1">Phase Progress</p>
        <PhaseProgressBar currentPhase={phase} approvals={approvals} />
      </div>

      {/* Task list */}
      {taskList.length > 0 && (
        <div>
          <p className="text-gray-500 text-[10px] uppercase tracking-wide mb-1.5">
            Tasks ({taskList.length})
          </p>
          <TaskList taskList={taskList} />
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function LiveState() {
  const { liveState } = morphData;

  if (!liveState) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center space-y-3">
          <div className="text-4xl text-gray-700">○</div>
          <p className="text-gray-400 text-lg font-medium">No active project</p>
          <p className="text-gray-600 text-sm">
            Run <code className="px-1.5 py-0.5 bg-gray-800 border border-gray-700 rounded font-mono text-gray-300">morph-spec init</code> to get started
          </p>
        </div>
      </div>
    );
  }

  const features = liveState.features || {};
  const featureEntries = Object.entries(features);

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-800 flex-shrink-0 flex items-center justify-between">
        <div>
          <h1 className="text-white text-xl font-bold">Live State</h1>
          <p className="text-gray-400 text-sm mt-0.5">
            {liveState.project?.name || 'Project'} · state v{liveState.version}
          </p>
        </div>
        <div className="flex items-center gap-4 text-xs text-gray-400">
          <span>{featureEntries.length} feature{featureEntries.length !== 1 ? 's' : ''}</span>
          {liveState.project?.stack && (
            <span className="px-2 py-0.5 bg-gray-800 border border-gray-700 rounded font-mono">
              {liveState.project.stack}
            </span>
          )}
        </div>
      </div>

      {/* Feature list */}
      <div className="flex-1 overflow-y-auto px-6 py-5">
        {featureEntries.length === 0 ? (
          <div className="flex items-center justify-center h-48">
            <p className="text-gray-500 text-sm">No features tracked yet</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            {featureEntries.map(([featureId, feature]) => (
              <FeatureCard key={featureId} featureId={featureId} feature={feature} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
