import { createFileRoute } from '@tanstack/react-router';
import { useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { ClipboardCheck, ListTodo, Clock, CheckCircle2 } from 'lucide-react';
import { useFloatingChat } from '@/context/FloatingChatContext';
import { trpc } from '@/lib/trpc';
import { Item, ItemMedia, ItemContent, ItemTitle, ItemDescription } from '@/components/ui/item';
import { TaskListView } from '@/components/tasks/TaskListView';

export const Route = createFileRoute('/tasks')({ component: TasksPage });

function TasksPage() {
  const { t } = useTranslation();
  const overviewRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const { registerSection, unregisterSection } = useFloatingChat();

  useEffect(() => {
    registerSection({ id: 'tasks-overview', label: 'Tasks Overview', ref: overviewRef });
    registerSection({ id: 'tasks-list', label: 'Task List', ref: listRef });
    return () => {
      unregisterSection('tasks-overview');
      unregisterSection('tasks-list');
    };
  }, [registerSection, unregisterSection]);

  const { data: allTasks } = trpc.tasks.list.useQuery({});
  const stats = useMemo(() => {
    const all = allTasks ?? [];
    return {
      total: all.length,
      todo: all.filter((task) => task.status === 'todo').length,
      inProgress: all.filter((task) => task.status === 'in_progress').length,
      completed: all.filter((task) => task.status === 'done').length,
    };
  }, [allTasks]);

  return (
    <div className="flex flex-col gap-6 p-6 pt-0 w-full">
      <div ref={overviewRef} data-ai-section="tasks-overview" className="grid grid-cols-4 gap-4">
        <Item variant="muted">
          <ItemMedia variant="icon"><ClipboardCheck /></ItemMedia>
          <ItemContent><ItemTitle>{stats.total}</ItemTitle><ItemDescription>{t('tasks.totalTasks')}</ItemDescription></ItemContent>
        </Item>
        <Item variant="muted">
          <ItemMedia variant="icon"><ListTodo /></ItemMedia>
          <ItemContent><ItemTitle>{stats.todo}</ItemTitle><ItemDescription>{t('tasks.toDo')}</ItemDescription></ItemContent>
        </Item>
        <Item variant="muted" className="bg-sky-50 dark:bg-sky-950/30">
          <ItemMedia variant="icon"><Clock /></ItemMedia>
          <ItemContent><ItemTitle>{stats.inProgress}</ItemTitle><ItemDescription>{t('tasks.inProgress')}</ItemDescription></ItemContent>
        </Item>
        <Item variant="muted" className="bg-green-50 dark:bg-green-950/30">
          <ItemMedia variant="icon"><CheckCircle2 /></ItemMedia>
          <ItemContent><ItemTitle>{stats.completed}</ItemTitle><ItemDescription>{t('tasks.completed')}</ItemDescription></ItemContent>
        </Item>
      </div>

      <div ref={listRef} data-ai-section="tasks-list">
        <TaskListView />
      </div>
    </div>
  );
}
