'use client';

import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { CheckSquare, Flag, Calendar, FolderOpen, CheckCircle } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useTasks, useProjects, useCompleteTask } from '@/hooks/integrations';
import type { TodoistPriority } from '@/types/integrations';

interface TodoistContentProps {
  locale: string;
}

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

const PRIORITY_LABEL_KEYS: Record<TodoistPriority, string> = {
  1: 'priority1',
  2: 'priority2',
  3: 'priority3',
  4: 'noPriority',
};

/**
 * Todoist integration content - displays tasks and projects
 */
export function TodoistContent({ locale }: TodoistContentProps) {
  const t = useTranslations('widgets.todoistTasks');
  const tInt = useTranslations('integrations');
  const { data: tasks, isLoading: tasksLoading } = useTasks();
  const { data: projects, isLoading: projectsLoading } = useProjects();
  const completeTask = useCompleteTask();

  const pendingTasks = tasks?.filter((task) => !task.isCompleted) ?? [];
  const todayTasks = pendingTasks.filter((task) => {
    if (!task.dueDate) return false;
    const today = new Date();
    const due = new Date(task.dueDate);
    return due.toDateString() === today.toDateString();
  });

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

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Heute faellig</CardTitle>
            <Calendar className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {tasksLoading ? <Skeleton className="h-8 w-12" /> : todayTasks.length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Gesamt offen</CardTitle>
            <CheckSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {tasksLoading ? <Skeleton className="h-8 w-12" /> : pendingTasks.length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Hohe Prioritaet</CardTitle>
            <Flag className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-500">
              {tasksLoading ? (
                <Skeleton className="h-8 w-12" />
              ) : (
                pendingTasks.filter((t) => t.priority === 1).length
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Projekte</CardTitle>
            <FolderOpen className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {projectsLoading ? <Skeleton className="h-8 w-12" /> : projects?.length ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Projects */}
        <Card>
          <CardHeader>
            <CardTitle>Projekte</CardTitle>
            <CardDescription>Ihre Todoist Projekte</CardDescription>
          </CardHeader>
          <CardContent>
            {projectsLoading ? (
              <div className="space-y-2">
                {Array.from({ length: 4 }).map((_, i) => (
                  <Skeleton key={i} className="h-10 w-full" />
                ))}
              </div>
            ) : projects && projects.length > 0 ? (
              <div className="space-y-2">
                {projects.map((project) => {
                  const taskCount = pendingTasks.filter((t) => t.projectId === project.id).length;
                  return (
                    <div
                      key={project.id}
                      className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
                    >
                      <div className="flex items-center gap-2">
                        <div
                          className="h-3 w-3 rounded-full"
                          style={{ backgroundColor: project.color }}
                        />
                        <span className="font-medium">{project.name}</span>
                        {project.isInbox && (
                          <Badge variant="secondary" className="text-xs">
                            Inbox
                          </Badge>
                        )}
                      </div>
                      <Badge variant="outline">{taskCount}</Badge>
                    </div>
                  );
                })}
              </div>
            ) : (
              <p className="text-center text-muted-foreground">{tInt('noProjectsFound')}</p>
            )}
          </CardContent>
        </Card>

        {/* Tasks */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Aufgaben</CardTitle>
            <CardDescription>Alle offenen Aufgaben</CardDescription>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[400px]">
              {tasksLoading ? (
                <div className="space-y-2">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <Skeleton key={i} className="h-14 w-full" />
                  ))}
                </div>
              ) : pendingTasks.length > 0 ? (
                <div className="space-y-2">
                  {pendingTasks.map((task, index) => (
                    <motion.div
                      key={task.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.2, delay: index * 0.03 }}
                      className={cn(
                        'flex items-start gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50',
                        task.isCompleted && 'opacity-50'
                      )}
                    >
                      <Checkbox
                        checked={task.isCompleted}
                        onCheckedChange={() => handleComplete(task.id)}
                        className="mt-0.5"
                      />
                      <div className="min-w-0 flex-1">
                        <p
                          className={cn(
                            'font-medium',
                            task.isCompleted && 'line-through text-muted-foreground'
                          )}
                        >
                          {task.content}
                        </p>
                        {task.description && (
                          <p className="text-sm text-muted-foreground">{task.description}</p>
                        )}
                        <div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                          {task.projectName && (
                            <span className="flex items-center gap-1">
                              <FolderOpen className="h-3 w-3" />
                              {task.projectName}
                            </span>
                          )}
                          {task.dueString && (
                            <span className="flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              {task.dueString}
                            </span>
                          )}
                          {task.labels.length > 0 && (
                            <div className="flex gap-1">
                              {task.labels.map((label) => (
                                <Badge key={label} variant="secondary" className="text-xs">
                                  {label}
                                </Badge>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                      <Flag className={cn('h-4 w-4 shrink-0', priorityColors[task.priority])} />
                    </motion.div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                  <CheckCircle className="mb-2 h-10 w-10" />
                  <p>{t('noTasks')}</p>
                </div>
              )}
            </ScrollArea>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
