import { FC, useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import Select from "react-select";

import {
  useActivateDataset,
  useCreateDatasetsDraft,
  useDeleteDataset,
  useDeleteFileFromDataset,
  useGetDatasets,
} from "@/api/documents/hooks";
import Button from "@/components/generics/button/Button";
import Modal from "@/components/generics/modal/Modal";
import { DocsList } from "@/components/views/documents/docsList/DocsList";
import { CreateDatasetForm } from "@/components/views/documents/createDatasetForm/CreateDatasetForm";
import { AddDocumentForm } from "@/components/views/documents/addDocuimentForm/AddDocumentForm";

import "./Documents.scss";

const Documents: FC = () => {
  const { data: datasetsData, isLoading } = useGetDatasets();
  const { mutate: deleteDatasetFn, isPending: isPendingDelete } = useDeleteDataset();
  const { mutate: activateDatasetFn } = useActivateDataset();
  const { mutate: deleteFileFn } = useDeleteFileFromDataset();
  const { mutate: createDatasetsDraftFn } = useCreateDatasetsDraft();

  const [searchParams, setSearchParams] = useSearchParams();

  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [modalContent, setModalContent] = useState<React.ReactNode>(null);

  useEffect(() => {
    if (
      (!searchParams.get("datasetId") ||
        !datasetsData?.find((e) => e.id.toString() == searchParams.get("datasetId"))) &&
      datasetsData?.[0]?.id
    ) {
      setSearchParams({ datasetId: String(datasetsData?.[0]?.id) });
    }
  }, [datasetsData, searchParams, setSearchParams]);

  const closeModal = () => setIsOpen(false);

  const currentDataset = useMemo(
    () => datasetsData?.find((e) => searchParams.get("datasetId") == e.id.toString()),
    [datasetsData, searchParams]
  );

  const deleteDatasetModal = useMemo(
    () => (
      <div className="docs-modal">
        <p>Вы уверены что хотите удалить базу документов?</p>
        <div className="docs-modal-actions">
          <Button name="Отмена" onClick={closeModal} />
          <Button
            loading={isPendingDelete}
            name="Продолжить"
            onClick={() =>
              currentDataset?.id
                ? deleteDatasetFn(currentDataset?.id, {
                    onSuccess: () => {
                      setSearchParams({ datasetId: String(datasetsData?.[0].id) });
                      setIsOpen(false);
                    },
                  })
                : null
            }
          />
        </div>
      </div>
    ),
    [currentDataset?.id, datasetsData, deleteDatasetFn, isPendingDelete, setSearchParams]
  );

  const activateDatasetModal = useMemo(
    () => (
      <div className="docs-modal">
        <p>
          Вы уверены что хотите выбрать новую базу документов? Процесс векторизации может занять продолжительное время.
        </p>
        <div className="docs-modal-actions">
          <Button name="Отмена" onClick={closeModal} />
          <Button
            name="Продолжить"
            onClick={() => activateDatasetFn(Number(currentDataset?.id), { onSuccess: () => location.reload() })}
          />
        </div>
      </div>
    ),
    [activateDatasetFn, currentDataset?.id]
  );

  const handleSelectChange = (selectedOption: { value: string; label: string } | null) => {
    const datasetId = selectedOption?.value ?? "";
    setSearchParams({ datasetId });
  };

  const handleDeleteFile = useCallback(
    (fileId: number) => {
      if (currentDataset) {
        if (!currentDataset.isDraft) {
          createDatasetsDraftFn(currentDataset.id, {
            onSuccess: (newDatasetData) => {
              setSearchParams({ datasetId: newDatasetData.id.toString() });
              deleteFileFn({ datasetId: newDatasetData.id, fileId: fileId });
            },
          });
        } else {
          deleteFileFn({ datasetId: currentDataset.id, fileId: fileId });
        }
      }
    },
    [createDatasetsDraftFn, currentDataset, deleteFileFn, setSearchParams]
  );

  const options = useMemo(
    () =>
      datasetsData?.map((dataset) => ({
        value: dataset.id.toString(),
        label: `${dataset.name} ${dataset.isDraft ? "(черновик)" : ""} ${dataset.isActive ? "(активный)" : ""}`,
      })),
    [datasetsData]
  );

  return (
    <div className="documents-page">
      <div className="datasets-actions">
        <Select
          options={options}
          placeholder=""
          isLoading={isLoading}
          classNamePrefix="react-select"
          value={options?.find((e) => e.value === searchParams.get("datasetId"))}
          onChange={handleSelectChange}
          theme={(theme) => ({
            ...theme,
            colors: {
              ...theme.colors,
              text: "orangered",
              primary25: "var(--primary-color)",
              primary50: "var(--primary-color)",
              primary: "var(--secondary-color)",
            },
          })}
        />
        <Button
          name="Загрузить базу документов"
          onClick={() => {
            setModalContent(<CreateDatasetForm closeModal={closeModal} setSearchParams={setSearchParams} />);
            setIsOpen(true);
          }}
        />
      </div>

      <div className="docs-actions">
        <div className="datasets-name">
          {currentDataset?.name} {currentDataset?.isDraft ? "(черновик)" : ""}
        </div>
        <div className="actions">
          <Button
            name="Добавить новый документ"
            onClick={() => {
              setModalContent(
                <AddDocumentForm
                  datasetId={Number(searchParams.get("datasetId"))}
                  isDraft={currentDataset?.isDraft ?? true}
                  closeModal={closeModal}
                  setSearchParams={setSearchParams}
                />
              );
              setIsOpen(true);
            }}
          />
          {!currentDataset?.isActive && (
            <Button
              name="Удалить базу документов"
              onClick={() => {
                setModalContent(deleteDatasetModal);
                setIsOpen(true);
              }}
            />
          )}
          <Button
            name="Использовать базу документов"
            onClick={() => {
              setModalContent(activateDatasetModal);
              setIsOpen(true);
            }}
            buttonType="secondary"
          />
        </div>
      </div>
      {searchParams.get("datasetId") &&
        datasetsData?.findIndex((e) => e.id === Number(searchParams.get("datasetId"))) != null && (
          <DocsList datasetId={Number(searchParams.get("datasetId"))} handleDeleteFile={handleDeleteFile} />
        )}
      <Modal isOpen={isOpen} closeModal={closeModal} label="Загрузить базу документов">
        {modalContent}
      </Modal>
    </div>
  );
};

export default Documents;
