import { useQuery, useMutation } from '@tanstack/react-query';
import { Task } from '@shared/schema';
import WeekListView from '@/components/WeekListView';
import { queryClient } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import { useState } from 'react';
import TaskDetailsModal from '@/components/TaskDetailsModal';

export default function WeekListPage() {
  const { toast } = useToast();
  const [editingTask, setEditingTask] = useState<Task | null>(null);

  // Fetch all tasks
  const { data: tasks = [] } = useQuery<Task[]>({
    queryKey: ['/api/tasks'],
  });

  // Update task mutation
  const updateTaskMutation = useMutation({
    mutationFn: async ({ taskId, updates }: { taskId: string; updates: Partial<Task> }) => {
      const response = await fetch(`/api/tasks/${taskId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates),
      });
      if (!response.ok) throw new Error('Failed to update task');
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
      toast({
        title: 'Task updated',
        description: 'Task has been updated successfully',
      });
    },
    onError: (error) => {
      console.error('Error updating task:', error);
      toast({
        title: 'Error',
        description: 'Failed to update task',
        variant: 'destructive',
      });
    },
  });

  // Delete task mutation
  const deleteTaskMutation = useMutation({
    mutationFn: async (taskId: string) => {
      const response = await fetch(`/api/tasks/${taskId}`, {
        method: 'DELETE',
      });
      if (!response.ok) throw new Error('Failed to delete task');
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
      toast({
        title: 'Task deleted',
        description: 'Task has been deleted successfully',
      });
    },
    onError: (error) => {
      console.error('Error deleting task:', error);
      toast({
        title: 'Error',
        description: 'Failed to delete task',
        variant: 'destructive',
      });
    },
  });

  const handleTaskUpdate = (taskId: string, updates: Partial<Task>) => {
    updateTaskMutation.mutate({ taskId, updates });
  };

  const handleTaskEdit = (task: Task) => {
    setEditingTask(task);
  };

  const handleTaskDelete = (taskId: string) => {
    deleteTaskMutation.mutate(taskId);
  };

  const handleStartTimer = (taskId: string) => {
    // Stop all other timers
    const runningTasks = tasks.filter(t => t.isTracking && t.id !== taskId);
    runningTasks.forEach(t => {
      updateTaskMutation.mutate({ taskId: t.id, updates: { isTracking: false } });
    });
    
    // Start this timer
    updateTaskMutation.mutate({ taskId, updates: { isTracking: true } });
  };

  const handleStopTimer = (taskId: string) => {
    updateTaskMutation.mutate({ taskId, updates: { isTracking: false } });
  };

  return (
    <div className="container mx-auto px-3 py-4 max-w-screen-2xl">
      <WeekListView
        tasks={tasks}
        onTaskUpdate={handleTaskUpdate}
        onTaskEdit={handleTaskEdit}
        onTaskDelete={handleTaskDelete}
        onStartTimer={handleStartTimer}
        onStopTimer={handleStopTimer}
      />

      {/* Task Edit Modal */}
      <TaskDetailsModal
        task={editingTask}
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSave={(updatedTask: Task) => {
          if (editingTask) {
            handleTaskUpdate(editingTask.id, updatedTask);
            setEditingTask(null);
          }
        }}
      />
    </div>
  );
}
