//! Файл большой, потому что было лень делить на компоненты
import Task from "@/components/task";

import MainSvg from "@/assets/main.svg";
import ModalCalendar from "@/components/ModalCalendar";
import ModalTags, { ITags } from "@/components/ModalTags";
import Button from "@/components/ui/Button";
import Dialog from "@/components/ui/Dialog";
import ModalWindow from "@/components/ui/Modal";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { PlusIcon } from "@heroicons/react/20/solid";
import {
  BookmarkIcon,
  BookOpenIcon,
  CalendarDaysIcon,
  DocumentDuplicateIcon,
  FunnelIcon,
  InboxArrowDownIcon,
  MagnifyingGlassIcon,
  PencilIcon,
  TrashIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import { FunctionComponent } from "preact";
import "preact/debug";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox";
import { Dropdown } from "primereact/dropdown";
import { SelectItem } from "primereact/selectitem";
import { Nullable } from "primereact/ts-helpers";
import { SubmitHandler, useForm } from "react-hook-form";
import { v4 as uuid } from "uuid";
import {
  IApiResponse,
  IAPITag,
  ICreateTaskResponse,
  IDeleteTaskResponse,
  IEditTaskResponse,
  ITask,
  ITaskDetails,
  ITaskForm,
  IViewTagsResponse,
} from "./profile_tasks.dto";
import classes from "./profile_tasks.module.scss";
import { DropdownStyles, selectedPriorityTemplate } from "./profile_tasks.prime.styles";

const priorities: SelectItem[] = [
  { label: "Приоритет 1", value: 1 },
  { label: "Приоритет 2", value: 2 },
  { label: "Приоритет 3", value: 3 },
  { label: "Приоритет 4", value: 4 },
];

const ProfileTasks: FunctionComponent = () => {
  const [openModal, setIsOpen] = useState(false); // Открыта модалка
  const [openModalCalendar, setOpenModalCalendar] = useState(false); // Открыта модалка календаря
  const [openModalTags, setOpenModalTags] = useState(false); // Открыта модалка тегов
  const [openSearchModal, setOpenSearchModal] = useState(false); // Открыто окно поиска
  const [openFilterModal, setOpenFilterModal] = useState(false);
  const [isEdit, setIsEdit] = useState(false); // Открыта задача
  const [isEditModal, setIsEditModal] = useState(false); // Включено редактирование задачи
  const [isCreating, setIsCreating] = useState(false); // Включено создание задачи
  const [editContent, setEditContent] = useState<ITask | null>(null); // Содержимое редактируемой задачи
  const [calendarDate, setCalendarDate] = useState<Nullable<Date>>(); // Выбранная в календаре дата
  const [tags, setTags] = useState<ITags>({ first: 0, second: 0, overdue: false });
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [searchQuery, setSearchQuery] = useState(""); // Текст поиска
  const [filterTags, setFilterTags] = useState<ITags>({ first: 0, second: 0, overdue: false });
  const [openFirstList, setOpenFirstList] = useState(false);
  const [openSecondList, setOpenSecondList] = useState(false);
  const [selectedPriority, setSelectedPriority] = useState(4);
  const getDate = useMemo(() => {
    const date = new Date();
    const formatter = new Intl.DateTimeFormat("ru-RU", { month: "long", day: "numeric" });
    return formatter.format(date);
  }, []);
  const [tasks, setTasks] = useState<ITask[]>([]);
  const [subjectChoices, setSubjectChoices] = useState<IAPITag[]>([]);
  const [taskTypeChoices, setTaskTypeChoices] = useState<IAPITag[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchTasks();
    fetchTags();
  }, []);

  const fetchTags = async () => {
    try {
      const response = await apiClient<IViewTagsResponse>("/api/tags/view_tags/");
      setSubjectChoices(response.subjects);
      setTaskTypeChoices(response.taskTypes);
    } catch (error) {
      console.error("Failed to fetch tags:", error);
    }
  };

  const fetchTasks = async () => {
    try {
      setIsLoading(true);
      const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
      const convertedTasks: ITask[] = response.tasks.map((apiTask) => ({
        id: apiTask.id.toString(),
        name: apiTask.title,
        priority: apiTask.priority,
        checked: apiTask.isCompleted,
        date: new Date(apiTask.due_date),
        description: apiTask.description,
        subject: apiTask.subject,
        taskType: apiTask.taskType,
      }));

      setTasks(convertedTasks);
    } catch (error) {
      console.error("Failed to fetch tasks:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const {
    handleSubmit,
    register,
    reset,
    setError,
    formState: { errors },
  } = useForm<ITaskForm>({
    defaultValues: {
      subject: {
        name: "",
        id: 0,
      },
      taskType: {
        name: "",
        id: 0,
      },
    },
  });

  const example_tags = useMemo(
    () => ({
      first: subjectChoices,
      second: taskTypeChoices,
    }),
    [subjectChoices, taskTypeChoices]
  );

  const saveTask: SubmitHandler<ITaskForm> = async (data) => {
    if (!calendarDate) {
      setError("date", { message: "Выберите дату" });
      return;
    }
    if ((!editContent?.subject.id || !editContent.taskType.id) && (!tags.first || !tags.second)) {
      setError("subject", { message: "Выберите теги" });
      return;
    }

    try {
      const selectedSubject = editContent?.subject.id || tags.first;
      const selectedTaskType = editContent?.taskType.id || tags.second;

      // Format date to DD-MM-YYYYTHH:MM
      const formattedDate = calendarDate
        .toLocaleString("en-GB", {
          day: "2-digit",
          month: "2-digit",
          year: "numeric",
          hour: "2-digit",
          minute: "2-digit",
          hour12: false,
        })
        .replace(",", "T")
        .replace(/\//g, "-")
        .replace("T ", "T");

      const taskData = {
        title: data.name,
        description: data.description || "",
        subject_id: selectedSubject,
        taskType_id: selectedTaskType,
        dateTime_due: formattedDate,
        priority: selectedPriority,
        telegram_notifications: false,
      };

      if (isCreating) {
        const response = await apiClient<ICreateTaskResponse>("/api/tasks/create_task/", {
          method: "POST",
          body: JSON.stringify(taskData),
        });

        if (!response.success) {
          throw new Error(response.message);
        }
      } else {
        const response = await apiClient<IEditTaskResponse>(`/api/tasks/edit_task/${editContent?.id}/`, {
          method: "PUT",
          body: JSON.stringify(taskData),
        });

        if (!response.success) {
          throw new Error(response.message);
        }
      }

      await fetchTasks();

      if (isCreating) setIsOpen(false);
      setTags({ first: 0, second: 0, overdue: false });
    } catch (error) {
      console.error("Failed to save task:", error);
    }
  };

  useEffect(() => {
    if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
    else reset();
  }, [editContent]);
  useEffect(() => {
    reset({
      name: "",
      description: "",
      date: "",
      subject: {
        name: "",
        id: 0,
      },
      taskType: {
        name: "",
        id: 0,
      },
      priority: 4,
      checked: false,
    });
    setSelectedPriority(4);
  }, [isCreating]);
  useEffect(() => {
    if (!editContent) return;
    const newEditContent = editContent;
    if (tags.first) newEditContent.subject = subjectChoices.find((choice) => choice.id === tags.first)!;
    if (tags.second) newEditContent.taskType = taskTypeChoices.find((choice) => choice.id === tags.second)!;
    setEditContent(newEditContent);
  }, [tags]);

  const groupTasksByDate = useMemo(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    const groupedTasks = {
      today: [] as ITask[],
      tomorrow: [] as ITask[],
      future: [] as { date: Date; tasks: ITask[] }[],
    };

    tasks.forEach((task) => {
      const taskDate = new Date(task.date);
      taskDate.setHours(0, 0, 0, 0);

      if (taskDate.getTime() === today.getTime()) {
        groupedTasks.today.push(task);
      } else if (taskDate.getTime() === tomorrow.getTime()) {
        groupedTasks.tomorrow.push(task);
      } else if (taskDate > tomorrow) {
        const existingGroup = groupedTasks.future.find((group) => group.date.getTime() === taskDate.getTime());

        if (existingGroup) {
          existingGroup.tasks.push(task);
        } else {
          groupedTasks.future.push({ date: taskDate, tasks: [task] });
        }
      }
    });

    // Sort tasks within each group
    groupedTasks.today.sort((a, b) => a.date.getTime() - b.date.getTime());
    groupedTasks.tomorrow.sort((a, b) => a.date.getTime() - b.date.getTime());
    groupedTasks.future.sort((a, b) => a.date.getTime() - b.date.getTime());
    groupedTasks.future.forEach((group) => {
      group.tasks.sort((a, b) => a.date.getTime() - b.date.getTime());
    });

    return groupedTasks;
  }, [tasks]);

  const formatDate = (date: Date) => {
    return new Intl.DateTimeFormat("ru-RU", {
      day: "numeric",
      month: "long",
      year: "numeric",
    }).format(date);
  };

  const handleDeleteTask = async () => {
    if (!editContent) return;

    try {
      const response = await apiClient<IDeleteTaskResponse>(`/api/tasks/delete_task/${editContent.id}/`, {
        method: "DELETE",
      });

      if (!response.success) {
        throw new Error(response.message);
      }

      await fetchTasks();

      setIsOpen(false);
      setShowDeleteDialog(false);
    } catch (error) {
      console.error("Failed to delete task:", error);
    }
  };

  const handleMarkTask = async (taskId: string) => {
    try {
      await apiClient(`/api/tasks/toggle_complete_task/${taskId}/`, {
        method: "PATCH",
      });

      setTasks((prevTasks) =>
        prevTasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task))
      );
    } catch (error) {
      console.error("Failed to mark task:", error);
    }
  };

  const filteredTasks = useMemo(() => {
    let filtered = tasks;

    if (searchQuery) {
      filtered = filtered.filter(
        (task) =>
          task.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          task.description?.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    if (filterTags.first || filterTags.second) {
      filtered = filtered.filter(
        (task) =>
          (!filterTags.first || task.subject.id === filterTags.first) &&
          (!filterTags.second || task.taskType.id === filterTags.second)
      );
    }

    filtered = filtered.filter((task) => (filterTags.overdue && !task.checked ? task.date < new Date() : 1));
    return filtered;
  }, [tasks, searchQuery, filterTags]);

  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (searchInputRef.current && openSearchModal) searchInputRef.current.focus();
  }, [searchInputRef, openSearchModal]);

  const handleViewTask = async (taskId: string) => {
    try {
      const taskDetails = await apiClient<ITaskDetails>(`/api/tasks/view_task/${taskId}/`);

      const task: ITask = {
        id: taskId,
        name: taskDetails.title,
        priority: taskDetails.priority,
        checked: false,
        date: new Date(taskDetails.dateTime_due),
        description: taskDetails.description,
        subject: taskDetails.subject,
        taskType: taskDetails.task_type,
      };
      console.log(task);

      setIsOpen(true);
      setIsEdit(true);
      setEditContent(task);
      setCalendarDate(task.date);
      setIsEditModal(false);
      setSelectedPriority(task.priority);
    } catch (error) {
      console.error("Failed to fetch task details:", error);
    }
  };

  return (
    <div class={classes.container}>
      {isLoading ? (
        <div class="flex w-full flex-1 items-center justify-center">
          <div class="text-2xl">Загрузка...</div>
        </div>
      ) : (
        <ModalTags
          refreshTags={fetchTags}
          zIndex={70}
          isOpen={openModalTags}
          setIsOpen={setOpenModalTags}
          tagsList={example_tags}
          value={tags}
          onClose={() => {
            if (!isCreating) setTags({ first: 0, second: 0, overdue: false });
          }}
          onChange={setTags}
        />
      )}
      <ModalCalendar
        zIndex={80}
        isOpen={openModalCalendar}
        setIsOpen={setOpenModalCalendar}
        onClose={() => {
          if (isEdit && !isEditModal) setCalendarDate(null);
        }}
        onChange={(e) => (isCreating || isEditModal) && setCalendarDate(e.value)}
        value={calendarDate!}
      />
      <ModalWindow
        zIndex={60}
        isOpen={openModal}
        setIsOpen={setIsOpen}
        onClose={() => {
          setIsEdit(false);
          setEditContent(null);
          setIsCreating(false);
          setIsEditModal(false);
          setTags({ first: 0, second: 0, overdue: false });
          setCalendarDate(null);
        }}
      >
        {isEdit && editContent && (
          <form
            class="flex h-full w-full flex-col items-start justify-between"
            onSubmit={(e) => {
              e.preventDefault();
              if (isEditModal) handleSubmit(saveTask)();
              else setIsEditModal(!isEditModal);
            }}
          >
            <div class="flex w-full flex-row items-start justify-between">
              <div class="flex flex-1 flex-col gap-1 pe-2">
                <input
                  class={cn("w-full p-2 text-2xl outline-0", {
                    "rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
                  })}
                  disabled={!isEditModal}
                  placeholder="Название"
                  {...register("name", {
                    required: "Заполните название",
                    maxLength: { value: 20, message: "Максимум 20 символов в названии" },
                  })}
                />
                <textarea
                  class={cn("h-[5rem] w-full resize-none p-2 outline-0", {
                    "rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
                  })}
                  disabled={!isEditModal}
                  placeholder={isEditModal ? "Описание" : ""}
                  {...register("description", {
                    maxLength: { value: 200, message: "Максимум 200 символов в описании" },
                  })}
                />

                <input
                  type="datetime-local"
                  value={calendarDate ? calendarDate.toISOString().slice(0, 16) : ""}
                  hidden
                  {...register("date")}
                />
                <input type="checkbox" hidden {...register("checked")} />
              </div>
              <div class="flex flex-col gap-4 md:flex-row">
                <div
                  className="flex cursor-pointer flex-col items-center gap-3"
                  onClick={() => {
                    if (isEditModal) {
                      handleSubmit(saveTask)();
                      setIsEditModal(!isEditModal);
                    } else setIsEditModal(!isEditModal);
                  }}
                >
                  {isEditModal ? (
                    <>
                      <InboxArrowDownIcon class="size-6" />
                      <p class="text-[0.7rem]">Сохранить</p>
                    </>
                  ) : (
                    <>
                      <PencilIcon class="size-6" />
                      <p class="text-[0.7rem]">Редактировать</p>
                    </>
                  )}
                </div>
                <div
                  className="flex cursor-pointer flex-col items-center gap-3"
                  onClick={() => setShowDeleteDialog(true)}
                >
                  <TrashIcon class="size-6" />
                  <p class="text-[0.7rem]">Удалить</p>
                </div>
              </div>
            </div>
            {errors.name && <p class="text-red-500">{errors.name.message}</p>}
            {errors.description && <p class="text-red-500">{errors.description.message}</p>}
            {errors.date && <p class="text-red-500">{errors.date.message}</p>}
            {errors.subject && <p class="text-red-500">{errors.subject.message}</p>}
            <div class="flex flex-col items-center gap-6 self-center md:flex-row md:justify-start md:self-start">
              <div
                class={cn("flex h-full flex-row items-center gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-2 py-1", {
                  "cursor-pointer": isEditModal,
                })}
                onClick={() => {
                  if (!isEditModal) return;
                  setOpenModalCalendar(true);
                  setCalendarDate(editContent.date);
                }}
              >
                <CalendarDaysIcon class="size-10" />
                <p>
                  {Intl.DateTimeFormat("ru-RU", {
                    day: "2-digit",
                    month: "2-digit",
                    year: "numeric",
                    hour: "2-digit",
                    minute: "2-digit",
                  }).format(calendarDate!)}
                </p>
              </div>
              <div
                class={cn("flex h-full flex-col items-start gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-4 py-2", {
                  "cursor-pointer": isEditModal,
                })}
                onClick={() => {
                  if (!isEditModal) return;
                  setTags({ first: editContent.subject.id, second: editContent.taskType.id, overdue: false });
                  setOpenModalTags(true);
                }}
              >
                <p class="flex flex-row gap-2">
                  <BookOpenIcon class="size-5" />
                  {editContent.subject.name}
                </p>
                <p class="flex flex-row gap-2">
                  <DocumentDuplicateIcon class="size-5" />
                  {editContent.taskType.name}
                </p>
              </div>
              <Dropdown
                disabled={!isEditModal}
                pt={DropdownStyles}
                options={priorities}
                value={selectedPriority}
                onChange={(e) => setSelectedPriority(e.value)}
                itemTemplate={selectedPriorityTemplate}
                valueTemplate={selectedPriorityTemplate}
              />
            </div>
          </form>
        )}
        {isCreating && (
          <form
            class="flex h-full w-full flex-col items-start justify-between"
            onSubmit={(e) => {
              e.preventDefault();
              handleSubmit((data) => saveTask({ ...data, id: uuid() }))();
            }}
          >
            <div class="flex w-full flex-1 flex-row items-start justify-between">
              <div class="flex flex-1 flex-col gap-1 pe-2">
                <input
                  class="w-full rounded-md bg-gray-400/30 p-2 text-2xl ring-1 ring-gray-400 outline-0"
                  maxLength={20}
                  placeholder="Название"
                  {...register("name", { required: "Заполните название" })}
                />
                <textarea
                  class="h-[5rem] w-full resize-none rounded-md bg-gray-400/30 p-2 ring-1 ring-gray-400 outline-0"
                  placeholder="Описание"
                  maxLength={200}
                  {...register("description")}
                />
                <input
                  type="datetime-local"
                  value={calendarDate ? calendarDate.toISOString().slice(0, 16) : ""}
                  hidden
                  {...register("date")}
                />
                <Dropdown
                  pt={DropdownStyles}
                  options={priorities}
                  value={selectedPriority}
                  onChange={(e) => setSelectedPriority(e.value)}
                  itemTemplate={selectedPriorityTemplate}
                  valueTemplate={selectedPriorityTemplate}
                />
                <input type="checkbox" checked={false} hidden {...register("checked")} />
              </div>
              <div class="flex flex-col gap-3 self-start md:flex-row">
                <CalendarDaysIcon
                  class="size-8 cursor-pointer"
                  onClick={() => {
                    setOpenModalCalendar(true);
                    setCalendarDate(calendarDate ?? new Date());
                  }}
                />
                <BookmarkIcon class="size-8 cursor-pointer" onClick={() => setOpenModalTags(true)} />
              </div>
            </div>
            {errors.name && <p class="text-red-500">{errors.name.message}</p>}
            {errors.date && <p class="text-red-500">{errors.date.message}</p>}
            {errors.subject?.message && <p class="text-red-500">{errors.subject.message}</p>}
            <div className="mb-8 flex h-16 flex-col items-center gap-6 self-center md:mb-0 md:flex-row md:self-start">
              <Button
                className="text-sm"
                onClick={() => {
                  setIsOpen(false);
                }}
              >
                Отмена
              </Button>
              <Button color="red" type="submit">
                Добавить задачу
              </Button>
            </div>
          </form>
        )}
      </ModalWindow>
      <Dialog
        isOpen={showDeleteDialog}
        setIsOpen={setShowDeleteDialog}
        title="Удаление задачи"
        onConfirm={handleDeleteTask}
        confirmText="Удалить"
        cancelText="Отмена"
      >
        <p class="mb-6 text-sm sm:text-[1rem]">"Вы уверены, что хотите удалить эту задачу?"</p>
      </Dialog>
      {!searchQuery && !filterTags.first && !filterTags.second && !filterTags.overdue ? (
        filteredTasks.length > 0 ? (
          <>
            <div class={classes.header}>
              Сегодня: {getDate}
              <div class="flex flex-row items-center gap-2 md:hidden">
                {!openSearchModal && (
                  <div
                    class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (!openSearchModal) setOpenFilterModal(false);
                      setOpenSearchModal(!openSearchModal);
                    }}
                  >
                    <MagnifyingGlassIcon class="size-6" />
                  </div>
                )}
                <div class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]">
                  <FunnelIcon
                    class="size-6"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (!openFilterModal) setOpenSearchModal(false);
                      setOpenFilterModal(!openFilterModal);
                    }}
                  />
                </div>
              </div>
            </div>
            <div class={classes.tasks_container}>
              {groupTasksByDate.today.length > 0 ? (
                <div class="w-full">
                  {groupTasksByDate.today.map((task) => (
                    <Task
                      name={task.name}
                      key={task.id}
                      priority={task.priority}
                      checked={task.checked}
                      overdue={task.date < new Date()}
                      onClick={() => handleViewTask(task.id)}
                      onMarkClick={() => handleMarkTask(task.id)}
                    />
                  ))}
                </div>
              ) : (
                <div class="w-full text-center text-xl">Задач на сегодня нет</div>
              )}
              {groupTasksByDate.tomorrow.length > 0 && (
                <div class="flex w-full flex-col gap-3 md:gap-10">
                  <div class="w-full text-3xl font-semibold md:text-5xl">Завтра</div>
                  {groupTasksByDate.tomorrow.map((task) => (
                    <Task
                      name={task.name}
                      priority={task.priority}
                      key={task.id}
                      checked={task.checked}
                      onClick={() => handleViewTask(task.id)}
                      onMarkClick={() => handleMarkTask(task.id)}
                    />
                  ))}
                </div>
              )}
              {groupTasksByDate.future.map((group) => (
                <div class="flex w-full flex-col gap-3 md:gap-10" key={group.date.getTime()}>
                  <div class="w-full text-3xl font-semibold md:text-5xl">{formatDate(group.date)}</div>
                  {group.tasks.map((task) => (
                    <Task
                      name={task.name}
                      priority={task.priority}
                      key={task.id}
                      checked={task.checked}
                      onClick={() => handleViewTask(task.id)}
                      onMarkClick={() => handleMarkTask(task.id)}
                    />
                  ))}
                </div>
              ))}
            </div>
          </>
        ) : (
          <div class="my-auto flex h-full w-full flex-col items-center justify-start">
            <img src={MainSvg} />
            <div class="flex w-full flex-1 flex-col items-center justify-center text-2xl">Начни уже сегодня!</div>
          </div>
        )
      ) : (
        <div class={classes.tasks_container}>
          <div class="mb-8 flex w-full flex-row items-center justify-between text-xl font-semibold sm:text-3xl md:text-5xl">
            {searchQuery ? "Результаты поиска" : "Результаты фильтрации"}
            <div class="flex flex-row items-center gap-2 md:hidden">
              {!openSearchModal && (
                <div
                  class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]"
                  onClick={(e) => {
                    e.stopPropagation();
                    if (!openSearchModal) setOpenFilterModal(false);
                    setOpenSearchModal(!openSearchModal);
                  }}
                >
                  <MagnifyingGlassIcon class="size-6" />
                </div>
              )}
              <div class="flex aspect-square h-12 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] hover:bg-[rgba(206,232,251,0.9)]">
                <FunnelIcon
                  class="size-6"
                  onClick={(e) => {
                    e.stopPropagation();
                    if (!openFilterModal) setOpenSearchModal(false);
                    setOpenFilterModal(!openFilterModal);
                  }}
                />
              </div>
            </div>
          </div>
          {filteredTasks.length > 0 ? (
            filteredTasks.map((task) => (
              <Task
                name={task.name}
                priority={task.priority}
                key={task.id}
                checked={task.checked}
                overdue={task.date < new Date()}
                onClick={() => handleViewTask(task.id)}
                onMarkClick={() => handleMarkTask(task.id)}
              />
            ))
          ) : (
            <div class="w-full text-center text-xl">
              {searchQuery ? "Ничего не найдено" : "Нет задач с выбранными фильтрами"}
            </div>
          )}
        </div>
      )}
      <div class="group fixed right-1 bottom-16 flex flex-row items-center justify-start space-x-3 overflow-x-hidden py-2 md:right-[22rem] md:bottom-4">
        <div
          class="flex aspect-square h-20 cursor-pointer items-center justify-center rounded-full bg-[rgb(251,194,199,0.53)] text-9xl text-white shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-all duration-300 ease-out group-hover:ml-[12rem] hover:bg-[rgb(251,194,199,0.7)]"
          onClick={() => {
            setIsCreating(true);
            setIsOpen(true);
          }}
        >
          <PlusIcon />
        </div>
        {tasks.length > 0 && (
          <div class="absolute left-0 my-auto hidden flex-row space-x-3 opacity-0 transition-opacity duration-100 group-hover:opacity-100 md:flex">
            <div
              class="pointer-events-none flex aspect-square h-20 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] group-hover:pointer-events-auto hover:bg-[rgba(206,232,251,0.9)]"
              onClick={(e) => {
                e.stopPropagation();
                if (!openSearchModal) setOpenFilterModal(false);
                setOpenSearchModal(!openSearchModal);
              }}
            >
              <MagnifyingGlassIcon class="size-12" />
            </div>
            <div class="pointer-events-none flex aspect-square h-20 cursor-pointer flex-col items-center justify-center rounded-full bg-[rgba(206,232,251,0.7)] text-xl text-gray-600 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] group-hover:pointer-events-auto hover:bg-[rgba(206,232,251,0.9)]">
              <FunnelIcon
                class="size-12"
                onClick={(e) => {
                  e.stopPropagation();
                  if (!openFilterModal) setOpenSearchModal(false);
                  setOpenFilterModal(!openFilterModal);
                }}
              />
            </div>
          </div>
        )}
      </div>
      {openSearchModal && (
        <div class="fixed bottom-28 z-50 w-full rounded-lg bg-white p-4 shadow-lg md:absolute md:right-[24rem] md:mx-0 md:w-80">
          {/* Пофиксить разфокус при вводе */}
          <div class="flex items-center gap-2">
            <MagnifyingGlassIcon class="size-6 text-gray-400" />
            <input
              type="text"
              class="w-full rounded-lg border-0 px-4 py-2 outline-none"
              placeholder="Поиск"
              ref={searchInputRef}
              value={searchQuery}
              onInput={(e) => {
                setSearchQuery((e.target as HTMLInputElement).value);
              }}
            />
            <XMarkIcon
              class="size-5 cursor-pointer text-gray-400 hover:text-gray-600"
              onClick={() => {
                setSearchQuery("");
                setOpenSearchModal(false);
              }}
            />
          </div>
        </div>
      )}
      {openFilterModal && (
        <div class="fixed top-[50%] z-50 w-full rounded-[2rem] bg-white p-4 shadow-lg md:absolute md:top-auto md:right-[24rem] md:bottom-28 md:w-80">
          <div class="flex flex-col gap-4">
            <div class="text-center text-lg font-semibold">Фильтры</div>
            <div class="flex flex-col gap-2">
              <div class="flex flex-row gap-2">
                <Checkbox
                  name="overdue"
                  checked={filterTags.overdue}
                  onChange={(e) => {
                    setFilterTags({ ...filterTags, overdue: e.target.checked! });
                  }}
                  pt={{
                    root: {
                      className: cn("cursor-pointer inline-flex relative select-none align-bottom", "w-6 h-6"),
                    },
                    input: {
                      className: cn(
                        "absolute appearance-none top-0 left-0 size-full p-0 m-0 opacity-0 z-10 outline-none cursor-pointer"
                      ),
                    },
                    box: ({ props, context }: CheckboxPassThroughMethodOptions) => ({
                      className: cn(
                        "flex items-center justify-center",
                        "border-2 w-6 h-6 text-gray-600 rounded-lg transition-colors duration-200",
                        {
                          "border-gray-300 bg-white": !context.checked,
                          "border-blue-500 bg-blue-500": context.checked,
                        },
                        {
                          "hover:border-blue-500 focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(191,219,254,1)]":
                            !props.disabled,
                          "cursor-default opacity-60": props.disabled,
                        }
                      ),
                    }),
                    icon: {
                      className: "w-4 h-4 transition-all duration-200 text-white text-base",
                    },
                  }}
                ></Checkbox>
                <label htmlFor="overdue" class="cursor-pointer">
                  Просроченные
                </label>
              </div>
              <div class="relative">
                <div
                  class={cn(
                    "flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-[rgba(206,232,251,0.7)] px-4 py-2",
                    {
                      "bg-[rgba(206,232,251,0.9)]": filterTags.first,
                    }
                  )}
                  onClick={() => {
                    setOpenFirstList(!openFirstList);
                    setOpenSecondList(false);
                  }}
                >
                  <BookOpenIcon class="size-5" />
                  <span>{subjectChoices.find((s) => s.id === filterTags.first)?.name || "Предмет"}</span>
                </div>
                {openFirstList && (
                  <div class="absolute top-full right-0 z-50 max-h-[15rem] w-64 overflow-y-auto rounded-lg bg-white p-2 shadow-lg md:top-0 md:right-full md:mr-2">
                    {example_tags.first.map((tag) => {
                      return (
                        <div
                          key={`subject_${tag.id}`}
                          class="group flex cursor-pointer items-center gap-2 rounded-lg px-4 py-2 hover:bg-[rgba(206,232,251,0.3)]"
                          onClick={() => {
                            setFilterTags({ ...filterTags, first: tag.id });
                            setOpenFirstList(false);
                          }}
                        >
                          <div
                            class={cn("flex h-5 w-5 items-center justify-center rounded-full border-2", {
                              "border-[#FBC2C7] bg-[#FBC2C7]": filterTags.first === tag.id,
                              "border-[#D4D4D4]": filterTags.first !== tag.id,
                            })}
                          >
                            {filterTags.first === tag.id && <div class="h-2.5 w-2.5 rounded-full bg-white" />}
                          </div>
                          <span class="text-sm font-medium text-[#404040]">{tag.name}</span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <div class="relative">
                <div
                  class={cn(
                    "flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-[rgba(206,232,251,0.7)] px-4 py-2",
                    {
                      "bg-[rgba(206,232,251,0.9)]": filterTags.second,
                    }
                  )}
                  onClick={() => {
                    setOpenSecondList(!openSecondList);
                    setOpenFirstList(false);
                  }}
                >
                  <DocumentDuplicateIcon class="size-5" />
                  <span>{taskTypeChoices.find((s) => s.id === filterTags.second)?.name || "Задача"}</span>
                </div>
                {openSecondList && (
                  <div class="absolute top-full right-0 z-50 max-h-[15rem] w-64 overflow-y-auto rounded-lg bg-white p-2 shadow-lg md:top-0 md:right-full md:mr-2">
                    {example_tags.second.map((tag) => (
                      <div
                        key={`taskType_${tag.id}`}
                        class="group flex cursor-pointer items-center gap-2 rounded-lg px-4 py-2 hover:bg-[rgba(206,232,251,0.3)]"
                        onClick={() => {
                          setFilterTags({ ...filterTags, second: tag.id });
                          setOpenSecondList(false);
                        }}
                      >
                        <div
                          class={cn("flex h-5 w-5 items-center justify-center rounded-full border-2", {
                            "border-[#FBC2C7] bg-[#FBC2C7]": filterTags.second === tag.id,
                            "border-[#D4D4D4]": filterTags.second !== tag.id,
                          })}
                        >
                          {filterTags.second === tag.id && <div class="h-2.5 w-2.5 rounded-full bg-white" />}
                        </div>
                        <span class="text-sm font-medium text-[#404040]">{tag.name}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {(filterTags.first || filterTags.second || filterTags.overdue) && (
                <button
                  class="mt-2 w-full rounded-lg bg-red-100 px-4 py-2 text-red-600 hover:bg-red-200"
                  onClick={() => {
                    setFilterTags({ first: 0, second: 0, overdue: false });
                    setOpenFirstList(false);
                    setOpenSecondList(false);
                  }}
                >
                  Сбросить фильтры
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default withTitle(UrlsTitle.TASKS, ProfileTasks);
