import { useQuery, useMutation } from '@tanstack/react-query';
import { Task, Label, User } from '@shared/schema';
import TaskCard from '@/components/TaskCard';
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { CalendarOff } from 'lucide-react';
import { apiRequest, queryClient } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';

interface UnscheduledTasksProps {
    user: User;
    onToggleCompletion: (taskId: string, currentStatus: string) => void;
    onDelete: (taskId: string) => void;
    onUpdate: (taskId: string, updates: Partial<Task>) => void;
    onSelect: (task: Task) => void;
}

export default function UnscheduledTasksPage({ user, onToggleCompletion, onDelete, onUpdate, onSelect }: UnscheduledTasksProps) {
    const { t } = useTranslation();
    const { toast } = useToast();

    const { data: tasks = [] } = useQuery<Task[]>({
        queryKey: ['/api/tasks'],
        select: (data) => data
            .filter(task => !task.dueDate && task.status !== 'done')
            .map(task => ({
                ...task,
                dueDate: task.dueDate ? new Date(task.dueDate) : null
            }))
    });

    const { data: labels = [] } = useQuery<Label[]>({
        queryKey: ['/api/labels']
    });

    // We need a dummy toggleTaskCompletion and onDelete for display purposes, 
    // or we pass the real ones if we lift state up. 
    // Ideally we use the mutations directly in TaskCard or pass them from App.tsx context.
    // For now, let's assume TaskCard handles some, but it takes props.
    // Checking TaskCard props... it needs `onToggleCompletion`, `onDelete`, `onUpdate`, `onSelect`.
    // This suggests I should wrap this page in App.tsx or pass these handlers down.
    // Refactoring: I'll create this component but it might need to accept props from App.tsx 
    // if I want it to be fully functional without duplicating handler logic.
    // Alternatively, I can implement the handlers here using mutations.

    // Mutation for Auto Schedule
    const autoScheduleMutation = useMutation({
        mutationFn: async (taskId: string) => {
            const res = await apiRequest("POST", "/api/ai/schedule", { taskId });
            return res.json();
        },
        onSuccess: (data) => {
            if (data.success && data.scheduledDate) {
                toast({
                    title: t('schedule.saved', 'Schedule saved'),
                    description: t('taskDetails.scheduledFor', { date: new Date(data.scheduledDate).toLocaleString() })
                });
                queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
            } else {
                toast({
                    title: t('common.error'),
                    description: data.error || data.message || "Failed to schedule",
                    variant: "destructive"
                });
            }
        },
        onError: (err: any) => {
            toast({
                title: t('common.error'),
                description: err.message,
                variant: "destructive"
            });
        }
    });

    return (
        <div className="p-6 space-y-6 overflow-y-auto h-full">
            <div className="flex items-center gap-3">
                <div className="p-3 bg-muted rounded-xl">
                    <CalendarOff className="w-6 h-6 text-muted-foreground" />
                </div>
                <div>
                    <h1 className="text-2xl font-bold">{t('unscheduled.title')}</h1>
                    <p className="text-muted-foreground">{tasks.length} {t('taskList.taskCount', { count: tasks.length })}</p>
                </div>
            </div>

            {tasks.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-[50vh] text-center space-y-4">
                    <div className="p-6 bg-muted/30 rounded-full">
                        <CalendarOff className="w-12 h-12 text-muted-foreground/50" />
                    </div>
                    <div>
                        <h3 className="text-lg font-medium">{t('unscheduled.empty')}</h3>
                        <p className="text-muted-foreground max-w-sm mx-auto mt-2">
                            {t('taskList.noUnscheduledTasks')}
                        </p>
                    </div>
                </div>
            ) : (
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                    {tasks.map(task => (
                        <TaskCard
                            key={task.id}
                            task={task}
                            onStatusChange={(status) => onUpdate(task.id, { status })}
                            onDelete={() => onDelete(task.id)}
                            onUpdate={(updates) => onUpdate(task.id, updates)}
                            onEdit={() => onSelect(task)}
                            onAutoSchedule={() => autoScheduleMutation.mutate(task.id)}
                        />
                    ))}
                </div>
            )}
        </div>
    );
}
