import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Task } from '@shared/schema';
import TaskCard from './TaskCard';
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Trophy, Target, Calendar as CalendarIcon, ArrowRight, GripVertical, Sun, Moon } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors
} from '@dnd-kit/core';
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    useSortable,
    verticalListSortingStrategy
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface FocusModeProps {
    tasks: Task[];
    onTaskUpdate: (taskId: string, updates: Partial<Task>) => void;
    onTaskEdit: (task: Task) => void;
    onTaskDelete: (taskId: string) => void;
    onStartTimer: (taskId: string) => void;
    onStopTimer: (taskId: string) => void;
    onNavigateToTasks: () => void;
}

export default function FocusMode({
    tasks,
    onTaskUpdate,
    onTaskEdit,
    onTaskDelete,
    onStartTimer,
    onStopTimer,
    onNavigateToTasks
}: FocusModeProps) {
    const { t, i18n } = useTranslation();

    const greeting = useMemo(() => {
        const hour = new Date().getHours();
        if (hour < 12) return t('focus.greeting.morning');
        if (hour < 18) return t('focus.greeting.afternoon');
        return t('focus.greeting.evening');
    }, [t, i18n.language]);

    const stats = useMemo(() => {
        const today = new Date();
        const completedToday = tasks.filter(t => {
            // This is a mock check for 'completed today' since we don't track completion date in this schema
            // We'll just use 'done' tasks for the prototype visual
            return t.status === 'done';
        }).length;

        const totalActive = tasks.filter(t => t.status !== 'done').length;
        return { completedToday, totalActive };
    }, [tasks]);

    // Sortable item component
    const SortableTaskItem = ({ task }: { task: Task }) => {
        const {
            attributes,
            listeners,
            setNodeRef,
            transform,
            transition,
        } = useSortable({ id: task.id });

        const style = {
            transform: CSS.Transform.toString(transform),
            transition,
        };

        return (
            <div ref={setNodeRef} style={style} className="group relative touch-none">
                <div {...attributes} {...listeners} className="absolute left-2 top-1/2 -translate-y-1/2 p-2 cursor-grab opacity-0 group-hover:opacity-100 transition-opacity z-10">
                    <GripVertical className="w-4 h-4 text-muted-foreground" />
                </div>
                <div className="pl-8">
                    <TaskCard
                        task={task}
                        onStatusChange={(status) => onTaskUpdate(task.id, { status })}
                        onUpdate={(updates) => onTaskUpdate(task.id, updates)}
                        onEdit={() => onTaskEdit(task)}
                        onDelete={() => onTaskDelete(task.id)}
                        onStartTimer={() => onStartTimer(task.id)}
                        onStopTimer={() => onStopTimer(task.id)}
                    />
                </div>
            </div>
        );
    };

    const focusTasks = useMemo(() => {
        // Return tasks for focus list
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        return tasks.filter(t => t.status !== 'done')
            .sort((a, b) => {
                // 1. Due Date (Overdue/Today first)
                if (a.dueDate && b.dueDate) {
                    return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
                }
                // Tasks with due dates come before those without
                if (a.dueDate && !b.dueDate) return -1;
                if (!a.dueDate && b.dueDate) return 1;

                // 2. Priority
                if (a.priority === 'high' && b.priority !== 'high') return -1;
                if (b.priority === 'high' && a.priority !== 'high') return 1;

                return 0;
            })
            // Take top 5 to include more subtasks if relevant
            .slice(0, 5);
    }, [tasks]);

    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    const handleDragEnd = (event: any) => {
        // In a real app we'd persist the new order
        // For now we just animate it visually 
        const { active, over } = event;
        if (active.id !== over.id) {
            // logic to reorder would go here
            console.log('Reordered', active.id, over.id);
        }
    };

    return (
        <div className="max-w-4xl mx-auto space-y-8 p-4">
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="space-y-2"
            >
                <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-violet-600 to-indigo-600 bg-clip-text text-transparent">
                    {greeting}, Paul
                </h1>
                <p className="text-muted-foreground text-lg">
                    {t('focus.stats.activeTasksMessage', { count: stats.totalActive })}
                </p>
            </motion.div>

            <div className="grid gap-6 md:grid-cols-2">
                <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.1 }}
                >
                    <Card className="p-6 h-full bg-gradient-to-br from-violet-50 to-indigo-50 dark:from-violet-950/20 dark:to-indigo-950/20 border-violet-100 dark:border-violet-900/50">
                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 bg-white dark:bg-violet-900/50 rounded-xl shadow-sm">
                                <Trophy className="w-6 h-6 text-violet-600 dark:text-violet-400" />
                            </div>
                            <div>
                                <h3 className="font-semibold text-lg">{t('focus.stats.dailyProgress')}</h3>
                                <p className="text-sm text-muted-foreground">{t('focus.stats.momentum')}</p>
                            </div>
                        </div>
                        <div className="space-y-4">
                            <div className="flex items-end gap-2">
                                <span className="text-4xl font-bold text-violet-700 dark:text-violet-300">{stats.completedToday}</span>
                                <span className="text-muted-foreground mb-1">{t('focus.stats.tasksCompleted')}</span>
                            </div>
                            <div className="h-2 bg-white/50 dark:bg-black/20 rounded-full overflow-hidden">
                                <div
                                    className="h-full bg-violet-500 rounded-full transition-all duration-1000"
                                    style={{ width: `${Math.min((stats.completedToday / (stats.completedToday + stats.totalActive || 1)) * 100, 100)}%` }}
                                />
                            </div>
                        </div>
                    </Card>
                </motion.div>

                <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.2 }}
                    className="grid grid-rows-2 gap-4 h-full"
                >
                    {/* Routine Actions */}
                    <div className="grid grid-cols-2 gap-4">
                        <Button
                            variant="outline"
                            className="h-full flex flex-col items-center justify-center gap-2 hover:bg-orange-50 hover:text-orange-600 dark:hover:bg-orange-950/30 border-dashed"
                            onClick={() => window.location.href = '/focus/routine/morning'}
                        >
                            <Sun className="w-5 h-5 text-orange-500" />
                            <span className="text-xs font-semibold">{t('focus.routine.morning', 'Morning Plan')}</span>
                        </Button>
                        <Button
                            variant="outline"
                            className="h-full flex flex-col items-center justify-center gap-2 hover:bg-indigo-50 hover:text-indigo-600 dark:hover:bg-indigo-950/30 border-dashed"
                            onClick={() => window.location.href = '/focus/routine/evening'}
                        >
                            <Moon className="w-5 h-5 text-indigo-500" />
                            <span className="text-xs font-semibold">{t('focus.routine.evening', 'Evening Review')}</span>
                        </Button>
                    </div>

                    <Card className="p-4 flex flex-col justify-center items-center text-center bg-card hover:shadow-md transition-all cursor-pointer" onClick={onNavigateToTasks}>
                        <div className="flex items-center gap-2 mb-2">
                            <Target className="w-5 h-5 text-muted-foreground/50" />
                            <h3 className="font-semibold text-sm">{t('focus.viewAll.title')}</h3>
                        </div>
                        <Button variant="ghost" size="sm" className="gap-1 text-xs text-muted-foreground group">
                            {t('focus.viewAll.button')} <ArrowRight className="w-3 h-3 group-hover:translate-x-1 transition-transform" />
                        </Button>
                    </Card>
                </motion.div>
            </div>

            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.3 }}
            >
                <div className="flex items-center justify-between mb-4">
                    <h2 className="text-xl font-semibold flex items-center gap-2">
                        <Target className="w-5 h-5 text-red-500" />
                        {t('focus.list.title')}
                    </h2>
                    <span className="text-xs text-muted-foreground">{t('focus.list.subtitle')}</span>
                </div>

                {focusTasks.length > 0 ? (
                    <DndContext
                        sensors={sensors}
                        collisionDetection={closestCenter}
                        onDragEnd={handleDragEnd}
                    >
                        <SortableContext
                            items={focusTasks.map(t => t.id)}
                            strategy={verticalListSortingStrategy}
                        >
                            <div className="space-y-3">
                                {focusTasks.map(task => (
                                    <SortableTaskItem key={task.id} task={task} />
                                ))}
                            </div>
                        </SortableContext>
                    </DndContext>
                ) : (
                    <Card className="p-12 text-center text-muted-foreground bg-muted/50 border-dashed">
                        <p>{t('focus.list.empty')}</p>
                    </Card>
                )}
            </motion.div>
        </div>
    );
}
