import { useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { createLocalTask, deleteLocalTask, cancelLocalTask, postLocalTaskComment } from '../api';

interface UseTaskOperationsOptions {
  taskId: number | null;
  showToast: (msg: string, variant?: 'success' | 'error') => void;
  setUrlState: (fn: (prev: any) => any) => void;
  setShowCreateDialog: (v: boolean) => void;
}

export function useTaskOperations({ taskId, showToast, setUrlState, setShowCreateDialog }: UseTaskOperationsOptions) {
  const qc = useQueryClient();

  const handleCreateTask = useCallback(async (input: any, attachments: any[]) => {
    try {
      const created = await createLocalTask({ ...input, attachments });
      setShowCreateDialog(false);
      showToast(`Task #${created.task.id} を作成しました`);
      setUrlState((prev: any) => ({ ...prev, taskId: created.task.id }));
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast('タスクの作成に失敗しました', 'error');
    }
  }, [qc, showToast, setUrlState, setShowCreateDialog]);

  const handleComment = useCallback(async (body: string, attachments?: Array<{ name: string; contentBase64: string }>) => {
    if (!taskId) return;
    try {
      await postLocalTaskComment(taskId, body, 'user', attachments);
      qc.invalidateQueries({ queryKey: ['localTaskDetail', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast('コメントの送信に失敗しました', 'error');
    }
  }, [taskId, qc, showToast]);

  const handleDelete = useCallback(async () => {
    if (!taskId) return;
    try {
      await deleteLocalTask(taskId);
      setUrlState((prev: any) => ({ ...prev, taskId: null, detailTab: 'overview' as const }));
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast('削除に失敗しました（実行中のタスクは削除できません）', 'error');
    }
  }, [taskId, qc, showToast, setUrlState]);

  const handleCancel = useCallback(async () => {
    if (!taskId) return;
    try {
      await cancelLocalTask(taskId);
      qc.invalidateQueries({ queryKey: ['localTaskDetail', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast('停止に失敗しました', 'error');
    }
  }, [taskId, qc, showToast]);

  return { handleCreateTask, handleComment, handleDelete, handleCancel };
}
