"use client";

import Button from "@/components/Button/Button";
import DashboardProduct from "@/components/DashboardProduct/DashboardProduct";

import { callAction } from "@/lib/action-utils";
import { deleteProducts } from "@/services/actions/productsAPI";
import type { Category } from "@/services/models/Category";
import type { Collection } from "@/services/models/Collection";
import type { FullyPopulatedProduct } from "@/services/models/Product";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { useState } from "react";
import toast from "react-hot-toast";
import SearchInput from "../SearchInput/SearchInput";
import { Select } from "../Select";
import styles from "./DashboardProducts.module.scss";

export default function DashboardProducts({
  products,
  categories,
  collections,
}: {
  products: FullyPopulatedProduct[];
  categories: Category[];
  collections: Collection[];
}) {
  const [selectedProducts, setSelectedProducts] = useState<string[]>([]);

  function handleDeleteSelectedProducts() {
    void toast.promise(callAction(deleteProducts(selectedProducts)), {
      loading: "Удаляем продукты...",
      success: "Продукты успешно удалены.",
      error: (error: unknown) => {
        if (isRedirectError(error)) return null;

        return error?.toString() ?? "Упс! Что-то пошло не так :(";
      },
    });
  }

  function handleToggleSelectAllProducts() {
    const allSlugs = products.map((product) => product.slug);
    setSelectedProducts((selectedProducts) =>
      allSlugs.every((slug) => selectedProducts.includes(slug)) ? [] : allSlugs,
    );
  }

  function handleToggleSelectProduct(slug: string) {
    setSelectedProducts((selectedProducts) =>
      selectedProducts.includes(slug)
        ? selectedProducts.filter((selectedProduct) => selectedProduct !== slug)
        : [...selectedProducts, slug],
    );
  }

  return (
    <div className={styles["dashboard-products"]}>
      <div className={styles["dashboard-products__header"]}>
        <div className={styles["dashboard-products__header-top"]}>
          <span className={styles["dashboard-products__heading"]}>
            Продукты{" "}
            <span className={styles["dashboard-products__heading-right"]}>
              /{" "}
              <span className={styles["dashboard-products__products-quantity"]}>
                ({products.length})
              </span>
            </span>
          </span>

          <div className={styles["dashboard-products__button-group"]}>
            {selectedProducts.length > 0 && (
              <Button
                variant="primary"
                onClick={() => {
                  handleDeleteSelectedProducts();
                }}
                className={styles["dashboard-products__add-button"]}
              >
                Удалить
              </Button>
            )}

            <Button
              variant="primary"
              href="/dashboard/products/new"
              className={styles["dashboard-products__add-button"]}
            >
              Добавить
            </Button>
          </div>
        </div>

        <div className={styles["dashboard-products__header-bottom"]}>
          <SearchInput
            name="query"
            id="query"
            label="Название"
            placeholder="Введите название"
          />

          <div className={styles["dashboard-products__select-filters"]}>
            <Select.Root name="category" placeholder="Выберите категорию">
              {categories.map((category) => (
                <Select.Option key={category.slug} value={category.slug}>
                  {category.name}
                </Select.Option>
              ))}
            </Select.Root>

            <Select.Root name="collection" placeholder="Выберите коллекцию">
              {collections.map((collection) => (
                <Select.Option key={collection.slug} value={collection.slug}>
                  {collection.name}
                </Select.Option>
              ))}
            </Select.Root>

            <Select.Root
              name="configuration"
              placeholder="Выберите конфигурацию"
            >
              <Select.Option value="euro-book">Eврокнижка</Select.Option>
              <Select.Option value="puma">Пума</Select.Option>
              <Select.Option value="tick-tock">Тик-Так</Select.Option>
              <Select.Option value="trampoline">Трамплин</Select.Option>
              <Select.Option value="dolphin">Дельфин</Select.Option>
            </Select.Root>
          </div>
        </div>
      </div>

      <div className={styles["dashboard-products__body"]}>
        <table className={styles["dashboard-products__table"]}>
          <thead>
            <tr>
              <th></th>
              <th>
                <input
                  type="checkbox"
                  name="select-all"
                  id="select-all"
                  checked={products.every((product) =>
                    selectedProducts.includes(product.slug),
                  )}
                  onChange={() => {
                    handleToggleSelectAllProducts();
                  }}
                />
              </th>
              <th>Наименование</th>
              <th>Ссылка</th>
              <th>Категория</th>
              <th>Коллекция</th>
              <th>Конфигурация</th>
              <th></th>
            </tr>
          </thead>

          <tbody>
            {products.map((product) => (
              <DashboardProduct
                key={product._id.toString()}
                product={
                  JSON.parse(JSON.stringify(product)) as FullyPopulatedProduct
                }
                isSelected={selectedProducts.includes(product.slug)}
                onToggleSelectProduct={handleToggleSelectProduct}
              />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
