import { useState, useEffect } from 'react';
import { Calendar, List, Plus, CheckCircle, Clock, RefreshCw, User, MapPin } from 'lucide-react';
import { tasksApi, Task } from '../lib/tasksApi';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import CreateTaskModal from '../components/tasks/CreateTaskModal';
import CompleteTaskModal from '../components/tasks/CompleteTaskModal';
import { PullToRefresh } from '../components/ui/PullToRefresh';
import { SwipeableRow } from '../components/ui/SwipeableRow';
import { usePersistedFilter } from '../hooks/usePersistedState';
import { hapticFeedback } from '../lib/haptics';
import { PageHeader, EmptyState, CardSkeleton } from '../components/ui/LinearPrimitives';

export default function TasksPage() {
    const { user } = useAuth();
    const { addToast } = useToast();
    const [view, setView] = useState<'list' | 'calendar'>('list');
    const [tasks, setTasks] = useState<Task[]>([]);
    const [filter, setFilter] = usePersistedFilter<'all' | 'mine'>('tasks-filter', 'mine');
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [completionTask, setCompletionTask] = useState<Task | null>(null);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);

    useEffect(() => {
        loadTasks();
    }, [filter]);

    const loadTasks = async (showLoader = true) => {
        if (showLoader) setLoading(true);
        try {
            const data = await tasksApi.getAll({
                assigneeId: filter === 'mine' ? user?.id : undefined
            });
            setTasks(data);
        } catch (e) {
            console.error(e);
            addToast('Failed to load tasks', 'error');
        } finally {
            setLoading(false);
            setRefreshing(false);
        }
    };

    const handleRefresh = async () => {
        setRefreshing(true);
        await loadTasks(false);
    };

    const handleTaskCreated = () => {
        loadTasks(false);
        addToast('Task created successfully', 'success');
    };

    const handleTaskCompleted = () => {
        loadTasks(false);
        setCompletionTask(null);
        hapticFeedback('success');
        addToast('Task completed!', 'success');
    };

    const getPriorityBadge = (priority: string) => {
        switch (priority) {
            case 'URGENT':
                return <span className="badge badge-destructive animate-pulse">Urgent</span>;
            case 'HIGH':
                return <span className="badge badge-warning">High</span>;
            default:
                return null;
        }
    };

    return (
        <PullToRefresh onRefresh={handleRefresh} disabled={loading}>
            <div className="max-w-4xl mx-auto space-y-6 pb-20 animate-in">
                <PageHeader
                    title="Tasks"
                    subtitle="Manage operations and assignments"
                    actions={
                        <div className="flex gap-2">
                            <button
                                onClick={handleRefresh}
                                disabled={refreshing}
                                className="btn btn-ghost"
                                title="Refresh"
                            >
                                <RefreshCw size={16} className={refreshing ? 'animate-spin' : ''} />
                            </button>
                            <button
                                onClick={() => window.location.href = '/tasks/templates'}
                                className="btn btn-secondary"
                            >
                                <List size={16} />
                                <span className="hidden md:inline">SOPs</span>
                            </button>
                            <button
                                onClick={() => setIsCreateOpen(true)}
                                className="btn btn-primary"
                            >
                                <Plus size={16} />
                                <span className="hidden md:inline">New Task</span>
                            </button>
                        </div>
                    }
                />

                <CreateTaskModal
                    isOpen={isCreateOpen}
                    onClose={() => setIsCreateOpen(false)}
                    onSuccess={handleTaskCreated}
                />

                {/* Filter & View Toggle */}
                <div className="flex justify-between items-center card p-1">
                    <div className="flex">
                        <button
                            onClick={() => setFilter('mine')}
                            className={`px-4 py-2 rounded-md text-sm font-medium transition-colors duration-fast ${filter === 'mine'
                                    ? 'bg-accent-muted text-accent'
                                    : 'text-secondary hover:text-primary hover:bg-tertiary'
                                }`}
                        >
                            My Tasks
                        </button>
                        <button
                            onClick={() => setFilter('all')}
                            className={`px-4 py-2 rounded-md text-sm font-medium transition-colors duration-fast ${filter === 'all'
                                    ? 'bg-accent-muted text-accent'
                                    : 'text-secondary hover:text-primary hover:bg-tertiary'
                                }`}
                        >
                            All Tasks
                        </button>
                    </div>

                    <div className="flex gap-0.5 border-l border-default pl-2">
                        <button
                            onClick={() => setView('list')}
                            className={`p-2 rounded-md transition-colors duration-fast ${view === 'list' ? 'bg-tertiary text-primary' : 'text-tertiary'
                                }`}
                        >
                            <List size={16} />
                        </button>
                        <button
                            onClick={() => setView('calendar')}
                            className={`p-2 rounded-md transition-colors duration-fast ${view === 'calendar' ? 'bg-tertiary text-primary' : 'text-tertiary'
                                }`}
                        >
                            <Calendar size={16} />
                        </button>
                    </div>
                </div>

                {/* Task List */}
                <div className="space-y-2">
                    {loading ? (
                        Array.from({ length: 5 }).map((_, i) => (
                            <div key={i} className="card p-4 space-y-2">
                                <div className="skeleton w-3/4 h-5" />
                                <div className="skeleton w-1/2 h-4" />
                            </div>
                        ))
                    ) : tasks.length === 0 ? (
                        <EmptyState
                            icon={Calendar}
                            title="No tasks found"
                            description={filter === 'mine' ? 'You have no assigned tasks' : 'No tasks have been created yet'}
                            action={
                                <button onClick={() => setIsCreateOpen(true)} className="btn btn-primary">
                                    <Plus size={16} />
                                    Create Task
                                </button>
                            }
                        />
                    ) : (
                        tasks.map(task => (
                            <SwipeableRow
                                key={task.id}
                                onSwipeRight={task.status !== 'COMPLETED' ? () => setCompletionTask(task) : undefined}
                                rightAction={task.status !== 'COMPLETED' ? {
                                    icon: <CheckCircle size={20} />,
                                    color: 'bg-success',
                                    label: 'Complete'
                                } : undefined}
                                disabled={task.status === 'COMPLETED'}
                            >
                                <div className="card p-4 flex items-center gap-4">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                                            <h3 className={`font-medium text-sm ${task.status === 'COMPLETED'
                                                    ? 'text-tertiary line-through'
                                                    : 'text-primary'
                                                }`}>
                                                {task.title}
                                            </h3>
                                            {getPriorityBadge(task.priority)}
                                            {task.status === 'COMPLETED' && (
                                                <span className="badge badge-success">Done</span>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-4 text-xs text-tertiary flex-wrap">
                                            <span className="flex items-center gap-1">
                                                <Clock size={12} />
                                                {task.dueDate ? new Date(task.dueDate).toLocaleDateString() : 'No date'}
                                            </span>
                                            {task.room && (
                                                <span className="flex items-center gap-1">
                                                    <MapPin size={12} />
                                                    {task.room.name}
                                                </span>
                                            )}
                                            {task.assignee && (
                                                <span className="flex items-center gap-1">
                                                    <User size={12} />
                                                    {task.assignee.name}
                                                </span>
                                            )}
                                        </div>
                                        {task.notes && task.status === 'COMPLETED' && (
                                            <p className="text-xs text-secondary mt-2 p-2 bg-tertiary rounded-md">
                                                {task.notes}
                                            </p>
                                        )}
                                    </div>

                                    {task.status !== 'COMPLETED' && (
                                        <button
                                            onClick={() => setCompletionTask(task)}
                                            className="w-9 h-9 rounded-full border border-default flex items-center justify-center hover:bg-success-muted hover:border-success transition-colors duration-fast group flex-shrink-0"
                                            title="Mark as complete"
                                        >
                                            <CheckCircle size={16} className="text-tertiary group-hover:text-success" />
                                        </button>
                                    )}
                                </div>
                            </SwipeableRow>
                        ))
                    )}
                </div>

                {completionTask && (
                    <CompleteTaskModal
                        task={completionTask}
                        onClose={() => setCompletionTask(null)}
                        onSuccess={handleTaskCompleted}
                    />
                )}
            </div>
        </PullToRefresh>
    );
}
