import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation('list');

  const handleCreateTask = useCallback(async (input: any, attachments: any[]) => {
    try {
      const created = await createLocalTask({ ...input, attachments });
      setShowCreateDialog(false);
      showToast(t('toast.created', { id: created.task.id }));
      setUrlState((prev: any) => ({ ...prev, taskId: created.task.id }));
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast(t('toast.createFailed'), 'error');
    }
  }, [qc, showToast, setUrlState, setShowCreateDialog, t]);

  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(t('toast.commentFailed'), 'error');
    }
  }, [taskId, qc, showToast, t]);

  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(t('toast.deleteFailed'), 'error');
    }
  }, [taskId, qc, showToast, setUrlState, t]);

  const handleCancel = useCallback(async () => {
    if (!taskId) return;
    try {
      await cancelLocalTask(taskId);
      qc.invalidateQueries({ queryKey: ['localTaskDetail', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    } catch {
      showToast(t('toast.cancelFailed'), 'error');
    }
  }, [taskId, qc, showToast, t]);

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