import { useState } from 'react'
import { AccordionItem } from '../components/accordion-item';
import { TaskTable } from '../components/task-table';
import { TaskForm } from '../components/task-form';

function App() {
  const [tasks, setTasks] = useState<TodoTasks>([
    {
      id: 1,
      type: 'task',
      title: 'Lipk iš lovos',
      status: 'in progress',
    },
    {
      id: 2,
      type: 'task',
      title: 'Susirask kavos',
      status: 'paused',
    },
    {
      id: 3,
      type: 'bug',
      title: 'Sudaryk TODO sąrašą',
      status: 'testing',
    },
  ]);

  const createTask = (data: Record<string, FormDataEntryValue>) => {
    const task = {
      id: tasks.reduce((max, row) => row.id > max ? row.id : max, 1) + 1,
      type: data.type as TaskType,
      title: data.title as string,
      status: data.status as TaskStatus,
    };

    setTasks(data.insert ? [task, ...tasks] : [...tasks, task]);

    scroll(0, 0);
  }

  const updateTask = (task: TodoTask) => {
    const index = tasks.findIndex(t => t.id == task.id);
    setTasks([...tasks.slice(0, index), task, ...tasks.slice(index + 1)]);
  };

  const deleteTask = (id: number) => {
    setTasks(tasks.filter(t => t.id != id));
  };

  const swapTasks = (fromId: number, toId: number) => {
    const from = tasks.findIndex(t => t.id == fromId);
    const to = tasks.findIndex(t => t.id == toId);
    const length = tasks.length;
    const task = tasks[from]

    if (from === to || from > length || to > length) {
      return;
    }

    setTasks(tasks.flatMap((item, index) => {
      if (index === from) return [];
      if (index === to) return from < to ? [item, task] : [task, item];
      return item;
    }));
  };

  return (
    <>
      <AccordionItem title='Užduočių sąrašas' isOpen>
        <TaskTable tasks={tasks} updateTask={updateTask} deleteTask={deleteTask} orderTasks={swapTasks} />
      </AccordionItem>
      <AccordionItem title='Nauja užduotis'>
        <TaskForm createTask={createTask} />
      </AccordionItem>
    </>
  )
}

export default App
