import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { continueTaskWithPiece, fetchLocalTaskComments } from '../../api';
import { usePieceList } from '../../hooks/usePieces';
import { resolvePieceOptions } from '../../lib/splitPieces';
import { MarkdownText } from '../../lib/markdown-text';
import { useBackdropClose } from '../../lib/useBackdropClose';

interface PrevJobInfo {
  id: string;
  pieceName: string;
  status: string;
}

interface ContinueWithPieceDialogProps {
  taskId: number;
  prevJob: PrevJobInfo;
  onClose: () => void;
}

export function ContinueWithPieceDialog({
  taskId,
  prevJob,
  onClose,
}: ContinueWithPieceDialogProps) {
  const { t } = useTranslation('detail');
  const [piece, setPiece] = useState<string>(prevJob.pieceName);
  const [instruction, setInstruction] = useState<string>('');
  const [resultExpanded, setResultExpanded] = useState<boolean>(false);
  const qc = useQueryClient();
  const backdrop = useBackdropClose(onClose);

  const piecesQuery = usePieceList();

  // Lazy-fetch comments to derive the previous job's terminal output. Re-uses
  // the same queryKey as useLocalTaskDetail so we hit the in-memory cache when
  // the parent panel has the data warm.
  const commentsQuery = useQuery({
    queryKey: ['localTaskComments', taskId],
    queryFn: () => fetchLocalTaskComments(taskId),
  });
  const prevResult = (() => {
    const comments = commentsQuery.data ?? [];
    for (let i = comments.length - 1; i >= 0; i--) {
      const c = comments[i];
      if (c.author === 'agent' && (c.kind === 'result' || c.kind === 'ask')) {
        return { body: c.body, kind: c.kind };
      }
    }
    return null;
  })();

  const continueMutation = useMutation({
    mutationFn: () => continueTaskWithPiece(taskId, { piece, instruction: instruction.trim() }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['localTaskDetail', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
      onClose();
    },
  });

  const submitDisabled =
    continueMutation.isPending || !piece || instruction.trim().length === 0;
  const submitError = continueMutation.isError
    ? ((continueMutation.error as Error)?.message ?? 'Failed to continue')
    : null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      {...backdrop}
    >
      <div className="bg-surface rounded-xl shadow-xl w-full max-w-lg mx-4 overflow-hidden flex flex-col max-h-[90vh]">
        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-4 border-b border-hairline">
          <div className="flex-1 min-w-0">
            <div className="text-sm font-semibold text-slate-800">
              {t('continue.heading', { id: taskId })}
            </div>
            <div className="text-2xs text-slate-500 mt-0.5">
              {t('continue.workspaceNote')}
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-6 h-6 flex items-center justify-center rounded hover:bg-surface-2 text-slate-400 hover:text-slate-700 transition-colors"
            aria-label="Close"
          >
            <svg viewBox="0 0 16 16" className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M3 3l10 10M13 3L3 13" />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className="flex flex-col gap-4 px-5 py-4 overflow-y-auto flex-1">
          {prevResult && (
            <div className="border border-hairline rounded-md">
              <button
                type="button"
                onClick={() => setResultExpanded(v => !v)}
                className="w-full flex justify-between items-center px-3 py-2 text-2xs font-semibold text-slate-500 uppercase tracking-wide hover:bg-surface-2 transition-colors"
                aria-expanded={resultExpanded}
              >
                <span>
                  {t('continue.prevPiece', { name: prevJob.pieceName })} {prevResult.kind === 'ask' ? t('continue.question') : t('continue.result')}
                </span>
                <span className="text-slate-400 normal-case font-normal">{resultExpanded ? '▼' : '▶'}</span>
              </button>
              {resultExpanded && (
                <div className="px-3 py-2 border-t border-hairline max-h-48 overflow-y-auto text-[13px]">
                  <MarkdownText text={prevResult.body} />
                </div>
              )}
            </div>
          )}

          <div className="flex flex-col gap-1">
            <label htmlFor="continue-piece" className="text-2xs font-semibold text-slate-500 uppercase tracking-wide">
              Piece <span className="text-red-500">*</span>
            </label>
            <select
              id="continue-piece"
              value={piece}
              onChange={e => setPiece(e.target.value)}
              disabled={piecesQuery.isLoading}
              className="px-3 py-2 rounded-md border border-hairline text-[13px] focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
            >
              {resolvePieceOptions(piecesQuery.data ?? []).map(p => (
                <option key={p.name} value={p.name}>
                  {p.name}
                  {p.name === prevJob.pieceName ? ' ' + t('continue.current') : ''}
                  {p.custom ? ' [user]' : ''}
                </option>
              ))}
            </select>
          </div>

          <div className="flex flex-col gap-1">
            <label htmlFor="continue-instruction" className="text-2xs font-semibold text-slate-500 uppercase tracking-wide">
              {t('continue.newInstruction')} <span className="text-red-500">*</span>
            </label>
            <textarea
              id="continue-instruction"
              value={instruction}
              onChange={e => setInstruction(e.target.value)}
              autoFocus
              rows={5}
              placeholder={t('continue.instructionPlaceholder')}
              className="px-3 py-2 rounded-md border border-hairline text-[13px] resize-y focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
            />
          </div>

          {submitError && (
            <div className="text-xs text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-500/15 border border-red-200 dark:border-red-500/30 rounded px-2 py-1.5">
              {submitError}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-hairline bg-surface">
          <button
            type="button"
            onClick={onClose}
            className="px-3 py-1.5 text-xs font-medium rounded-md text-slate-600 hover:text-slate-900 hover:bg-surface-2 transition-colors"
          >
            {t('continue.cancel')}
          </button>
          <button
            type="button"
            onClick={() => continueMutation.mutate()}
            disabled={submitDisabled}
            className="px-3 py-1.5 text-xs font-semibold rounded-md bg-accent text-white hover:bg-accent-hover disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {continueMutation.isPending ? t('continue.starting') : 'Continue'}
          </button>
        </div>
      </div>
    </div>
  );
}
