import { useState } from 'react';
import { SubtaskInfo } from '../../api';
import { statusTone, formatStatusLabel } from '../../lib/utils';

interface SubtaskInlineCardProps {
  subtasks: SubtaskInfo[];
  subtaskCount: number;
  subtaskCompleted: number;
}

function SubtaskStatusIcon({ status }: { status: string }) {
  const common = 'inline-block w-3.5 h-3.5 flex-shrink-0';
  switch (status) {
    case 'succeeded':
      return (
        <svg className={`${common} text-emerald-600`} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="8" cy="8" r="6" fill="currentColor" fillOpacity="0.12" stroke="currentColor" />
          <path d="M5.5 8.5l2 2 3-3.5" />
        </svg>
      );
    case 'failed':
      return (
        <svg className={`${common} text-red-600`} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="8" cy="8" r="6" fill="currentColor" fillOpacity="0.1" stroke="currentColor" />
          <path d="M6 6l4 4M10 6l-4 4" />
        </svg>
      );
    case 'running':
      return (
        <svg className={`${common} text-blue-500 animate-spin`} viewBox="0 0 16 16" fill="none">
          <circle className="opacity-25" cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="2" />
          <path className="opacity-75" fill="currentColor" d="M2 8a6 6 0 016-6v2a4 4 0 00-4 4H2z" />
        </svg>
      );
    case 'waiting_subtasks':
      return (
        <svg className={`${common} text-indigo-500 animate-pulse`} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75">
          <circle cx="8" cy="8" r="6" />
          <circle cx="5" cy="8" r="1" fill="currentColor" />
          <circle cx="8" cy="8" r="1" fill="currentColor" />
          <circle cx="11" cy="8" r="1" fill="currentColor" />
        </svg>
      );
    default: // queued, cancelled, etc.
      return (
        <svg className={`${common} text-slate-300`} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
          <circle cx="8" cy="8" r="6" />
        </svg>
      );
  }
}

export function SubtaskInlineCard({ subtasks, subtaskCount, subtaskCompleted }: SubtaskInlineCardProps) {
  const [expanded, setExpanded] = useState(true);
  const progressPct = subtaskCount > 0 ? Math.round((subtaskCompleted / subtaskCount) * 100) : 0;
  const allDone = subtaskCompleted === subtaskCount;
  const running = subtasks.filter(st => st.status === 'running').length;
  const failed = subtasks.filter(st => st.status === 'failed').length;

  return (
    <div className="flex justify-center">
      <div className="bg-white border border-hairline rounded-md px-3.5 py-2.5 max-w-[90%] w-full">
        {/* Header */}
        <button
          onClick={() => setExpanded(!expanded)}
          className="w-full flex items-center justify-between text-left hover:bg-surface rounded -mx-1 px-1 py-0.5 transition-colors"
        >
          <div className="flex items-center gap-2 min-w-0">
            {!allDone ? (
              <svg className="w-4 h-4 text-indigo-500 animate-spin flex-shrink-0" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="3" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
              </svg>
            ) : (
              <svg className="w-4 h-4 text-emerald-500 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 11l3 3L22 4" />
                <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" />
              </svg>
            )}
            <span className="text-[13px] font-semibold text-slate-900 truncate">サブタスク</span>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            <span className="text-2xs text-slate-500 font-mono tabular-nums">
              {subtaskCompleted}/{subtaskCount} · {progressPct}%
            </span>
            <svg className={`w-3 h-3 text-slate-400 transition-transform ${expanded ? 'rotate-90' : ''}`} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M6 4l4 4-4 4" />
            </svg>
          </div>
        </button>

        {/* Summary badges */}
        <div className="flex gap-1.5 mt-2 text-2xs">
          {subtaskCompleted > 0 && (
            <span className="inline-flex items-center gap-1 bg-emerald-50 text-emerald-700 border border-emerald-100 px-1.5 py-0.5 rounded font-mono tabular-nums">
              <SubtaskStatusIcon status="succeeded" />{subtaskCompleted}
            </span>
          )}
          {running > 0 && (
            <span className="inline-flex items-center gap-1 bg-blue-50 text-blue-700 border border-blue-100 px-1.5 py-0.5 rounded font-mono tabular-nums">
              <SubtaskStatusIcon status="running" />{running}
            </span>
          )}
          {failed > 0 && (
            <span className="inline-flex items-center gap-1 bg-red-50 text-red-700 border border-red-100 px-1.5 py-0.5 rounded font-mono tabular-nums">
              <SubtaskStatusIcon status="failed" />{failed}
            </span>
          )}
          {subtaskCount - subtaskCompleted - running - failed > 0 && (
            <span className="inline-flex items-center gap-1 bg-white text-slate-500 border border-hairline px-1.5 py-0.5 rounded font-mono tabular-nums">
              <SubtaskStatusIcon status="queued" />{subtaskCount - subtaskCompleted - running - failed}
            </span>
          )}
        </div>

        {/* Progress bar */}
        <div className="w-full bg-slate-100 rounded-full h-1 mt-2">
          <div
            className={`h-1 rounded-full transition-all duration-500 ${allDone ? 'bg-emerald-500' : 'bg-indigo-500'}`}
            style={{ width: `${progressPct}%` }}
          />
        </div>

        {/* Subtask list */}
        {expanded && (
          <div className="mt-2 pt-2 border-t border-hairline-soft max-h-[300px] overflow-y-auto">
            {subtasks.map(st => {
              const title = st.instruction.split('\n')[0]?.slice(0, 100) ?? '';
              return (
                <div key={st.id} className="flex items-start gap-2 py-1 text-xs">
                  <span className="mt-0.5"><SubtaskStatusIcon status={st.status} /></span>
                  <span className="min-w-0 flex-1">
                    <span className="block text-slate-700 truncate" title={title}>
                      #{st.issueNumber} {title}
                    </span>
                  </span>
                  {st.status === 'running' && (
                    <span className="text-blue-500 text-2xs font-mono flex-shrink-0">実行中</span>
                  )}
                  {st.status === 'succeeded' && (
                    <span className="text-emerald-500 text-2xs font-mono flex-shrink-0">完了</span>
                  )}
                  {st.status === 'failed' && (
                    <span className="text-red-500 text-2xs font-mono flex-shrink-0">失敗</span>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
