'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { CheckSquare, Plus, Flag, Calendar } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { WidgetContainer } from '../../widget-container';
import { useTodaysTasks, useCompleteTask, useCreateTask } from '@/hooks/integrations';
import type { TodoistPriority } from '@/types/integrations';

interface TasksWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  className?: string;
}

/** Priority color mapping */
const priorityColors: Record<TodoistPriority, string> = {
  1: 'text-red-500',
  2: 'text-orange-500',
  3: 'text-blue-500',
  4: 'text-muted-foreground',
};

/**
 * Tasks Widget - Displays today's Todoist tasks with quick complete
 */
export function TasksWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  className,
}: TasksWidgetProps) {
  const t = useTranslations('widgets.tasks');
  const { data: tasks, isLoading } = useTodaysTasks();
  const completeTask = useCompleteTask();
  const createTask = useCreateTask();
  const [newTaskContent, setNewTaskContent] = useState('');
  const [showNewTask, setShowNewTask] = useState(false);

  const handleComplete = (taskId: string) => {
    completeTask.mutate(taskId);
  };

  const handleCreateTask = async () => {
    if (!newTaskContent.trim()) return;

    await createTask.mutateAsync({
      content: newTaskContent,
      dueString: 'today',
    });

    setNewTaskContent('');
    setShowNewTask(false);
  };

  const pendingTasks = tasks?.filter((task) => !task.isCompleted) ?? [];

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<CheckSquare className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      <ScrollArea className="h-[200px] pr-2">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex items-center gap-3">
                <Skeleton className="h-4 w-4 rounded" />
                <Skeleton className="h-4 flex-1" />
              </div>
            ))}
          </div>
        ) : pendingTasks.length > 0 ? (
          <div className="space-y-2">
            <AnimatePresence mode="popLayout">
              {pendingTasks.map((task, index) => (
                <motion.div
                  key={task.id}
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: 10, height: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.03 }}
                  className="flex items-start gap-3 rounded-lg border p-2 transition-colors hover:bg-muted/50"
                >
                  <Checkbox
                    checked={task.isCompleted}
                    onCheckedChange={() => handleComplete(task.id)}
                    className="mt-0.5"
                  />
                  <div className="min-w-0 flex-1">
                    <p
                      className={cn(
                        'text-sm',
                        task.isCompleted && 'text-muted-foreground line-through'
                      )}
                    >
                      {task.content}
                    </p>
                    <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
                      {task.projectName && (
                        <span className="truncate">{task.projectName}</span>
                      )}
                      {task.dueString && (
                        <>
                          <span>-</span>
                          <span className="flex items-center gap-1">
                            <Calendar className="h-3 w-3" />
                            {task.dueString}
                          </span>
                        </>
                      )}
                    </div>
                  </div>
                  <Flag className={cn('h-4 w-4 shrink-0', priorityColors[task.priority])} />
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        ) : (
          <div className="flex h-full flex-col items-center justify-center text-sm text-muted-foreground">
            <CheckSquare className="mb-2 h-8 w-8" />
            <p>{t('noTasks')}</p>
          </div>
        )}
      </ScrollArea>

      {/* New Task Input */}
      <AnimatePresence>
        {showNewTask && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="mt-2"
          >
            <div className="flex gap-2">
              <Input
                value={newTaskContent}
                onChange={(e) => setNewTaskContent(e.target.value)}
                placeholder={t('newTaskPlaceholder')}
                className="h-8 text-sm"
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleCreateTask();
                  } else if (e.key === 'Escape') {
                    setShowNewTask(false);
                    setNewTaskContent('');
                  }
                }}
                autoFocus
              />
              <Button
                size="sm"
                className="h-8"
                onClick={handleCreateTask}
                disabled={!newTaskContent.trim() || createTask.isPending}
              >
                {t('add')}
              </Button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Footer actions */}
      <div className="mt-3 flex items-center justify-between border-t pt-3">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowNewTask(!showNewTask)}
        >
          <Plus className="mr-2 h-4 w-4" />
          {t('addTask')}
        </Button>
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/${locale}/integrations/todoist`}>
            {t('viewAll')}
          </Link>
        </Button>
      </div>
    </WidgetContainer>
  );
}
