import { TaskService } from '../../../tasks/service';
import { ICONS } from '../../../utils/icons';
import { codeId, formatDDMM, italic } from '../../../utils/formatting';
import {
  parseMultipleIds, resolveAndValidate,
  formatDue, handleBatch
} from '../shared';
import type { BatchOutcome } from '../shared';

type Ctx = {
  sender: string;
  groupId: string;
  message: string;
};

type Msg = {
  recipient: string;
  message: string;
  mentions?: string[];
};

// ---------------------------------------------------------------------------
// Single claim outcome
// ---------------------------------------------------------------------------

function claimOne(idInput: number, sender: string): BatchOutcome {
  const rv = resolveAndValidate(idInput, sender);

  if ('error' in rv) {
    const isNotFound = rv.error.includes('no encontrada');
    return {
      status: isNotFound ? 'notFound' : 'blocked',
      line: rv.error,
    };
  }

  const { resolvedId } = rv;
  const res = TaskService.claimTask(resolvedId, sender);
  const due = formatDue(res.task);
  const desc = res.task?.description || '(sin descripción)';
  const dc = res.task?.display_code;

  switch (res.status) {
    case 'claimed':
      return {
        status: 'claimed',
        line: `${ICONS.take} ${codeId(resolvedId, dc)} tomada — ${desc}${due}`,
      };
    case 'already':
      return {
        status: 'already',
        line: `ℹ️ ${codeId(resolvedId, dc)} ya la tenías — ${desc}${due}`,
      };
    case 'completed':
      return {
        status: 'completed',
        line: `ℹ️ ${codeId(resolvedId, dc)} ya estaba completada — ${desc}${due}`,
      };
    default:
      return {
        status: 'notFound',
        line: `⚠️ ${codeId(resolvedId)} no encontrada.`,
      };
  }
}

// ---------------------------------------------------------------------------
// Single-ID mode
// ---------------------------------------------------------------------------

function handleSingleClaim(idInput: number, sender: string): Msg[] {
  const rv = resolveAndValidate(idInput, sender);
  if ('error' in rv) {
    return [{ recipient: sender, message: rv.error }];
  }

  const { resolvedId } = rv;
  const res = TaskService.claimTask(resolvedId, sender);
  const due = formatDue(res.task);
  const dc = res.task?.display_code;

  if (res.status === 'not_found') {
    return [{ recipient: sender, message: `⚠️ Tarea ${codeId(resolvedId)} no encontrada.` }];
  }
  if (res.status === 'completed') {
    return [{
      recipient: sender,
      message: `ℹ️ ${codeId(resolvedId, dc)} ya estaba completada — ${res.task?.description || '(sin descripción)'}${due}`,
    }];
  }
  if (res.status === 'already') {
    return [{
      recipient: sender,
      message: `ℹ️ ${codeId(resolvedId, dc)} ya la tenías — ${res.task?.description || '(sin descripción)'}${due}`,
    }];
  }

  // Success
  const lines = [
    italic(`${ICONS.take} Has tomado ${codeId(resolvedId, dc)}`),
    res.task?.description || '(sin descripción)',
    res.task?.due_date ? `${ICONS.date} ${formatDDMM(res.task?.due_date)}` : '',
  ].filter(Boolean);

  return [{ recipient: sender, message: lines.join('\n') }];
}

// ---------------------------------------------------------------------------
// Main handler
// ---------------------------------------------------------------------------

export async function handleTomar(context: Ctx): Promise<Msg[]> {
  const tokens = (context.message || '').trim().split(/\s+/);
  const { ids, truncated } = parseMultipleIds(tokens.slice(2), 10);

  if (ids.length === 0) {
    return [{
      recipient: context.sender,
      message: 'ℹ️ Uso: `t tomar 26` o múltiples: `t tomar 12 19 50` o `t tomar 12,19,50` (máx. 10)',
    }];
  }

  if (ids.length === 1 && ids[0] != null) {
    return handleSingleClaim(ids[0], context.sender);
  }

  return handleBatch(
    context.sender,
    ids,
    truncated,
    claimOne,
    { claimed: 'tomadas', already: 'ya las tenías', completed: 'ya completadas', notFound: 'no encontradas', blocked: 'bloqueadas' },
    '',
  ) as Msg[];
}
