import React, { createContext, useContext, useEffect, useState } from "react";
import GlobalModel from "../common/GlobalModel";
import NewDocument from "./ManageDocument";
import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants";
import { useParams } from "react-router-dom";
import DocumentsList from "./DocumentsList";
import DocumentFilterPanel from "./DocumentFilterPanel";
import { useFab } from "../../Context/FabContext";
import { useForm } from "react-hook-form";
import {
  DocumentFilterDefaultValues,
  DocumentFilterSchema,
} from "./DocumentSchema";
import { zodResolver } from "@hookform/resolvers/zod";
import ManageDocument from "./ManageDocument";
import ViewDocument from "./ViewDocument";
import DocumentViewerModal from "./DocumentViewerModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useProfile } from "../../hooks/useProfile";

// Context
export const DocumentContext = createContext();
export const useDocumentContext = () => {
  const context = useContext(DocumentContext);
  if (!context) {
    throw new Error(
      "useDocumentContext must be used within an DocumentProvider"
    );
  }
  return context;
};

export const getDocuementsStatus = (status) => {
  switch (status) {
    case true:
      return (
        <span className="badge rounded-pill bg-label-success">Verified</span>
      );
    case false:
      return (
        <span className="badge rounded-pill bg-label-danger">Rejected</span>
      );
    case null:
    default:
      return (
        <span className="badge rounded-pill bg-label-warning"> Pending</span>
      );
  }
};
const Documents = ({ Document_Entity, Entity }) => {
  const [isSelf, setIsSelf] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [filters, setFilter] = useState();
  const [isRefetching, setIsRefetching] = useState(false);
  const [refetchFn, setRefetchFn] = useState(null);
  const [DocumentEntity, setDocumentEntity] = useState(Document_Entity);
  const { employeeId } = useParams();
  const [OpenDocument, setOpenDocument] = useState(false);
  const [ManageDoc, setManageDoc] = useState({
    document: null,
    isOpen: false,
  });
  const [viewDoc, setViewDoc] = useState({
    document: null,
    isOpen: false,
  });
  const { profile } = useProfile();

  useEffect(() => {
    if (profile?.employeeInfo?.id) {
      setIsSelf(profile.employeeInfo.id === employeeId);
    }
  }, [profile?.employeeInfo?.id, employeeId]);
  const canUploadDocument = useHasUserPermission(UPLOAD_DOCUMENT);

  const { setOffcanvasContent, setShowTrigger } = useFab();

  const methods = useForm({
    resolver: zodResolver(DocumentFilterSchema),
    defaultValues: DocumentFilterDefaultValues,
  });

  const { reset } = methods;

  const clearFilter = () => {
    setFilter(DocumentFilterDefaultValues);
    reset();
  };

  useEffect(() => {
    setShowTrigger(true);
    setOffcanvasContent(
      "Document Filters",
      <DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} />
    );

    return () => {
      setShowTrigger(false);
      setOffcanvasContent("", null);
    };
  }, []);

  const contextValues = {
    ManageDoc,
    setManageDoc,
    viewDoc,
    setViewDoc,
    setOpenDocument,
    OpenDocument,
  };

  useEffect(() => {
    if (Document_Entity) {
      setDocumentEntity(Document_Entity);
    }
  }, [Document_Entity]);
  return (
    <DocumentContext.Provider value={contextValues}>
      <div className="mt-5">
        <div className="card page-min-h d-flex p-2">
          <div className="row align-items-center">
            {/* Search */}
            <div className="d-flex col-8 col-md-8 col-lg-4 mb-md-0 align-items-center">
              <div className="d-flex">
                {" "}
                <input
                  type="search"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  className="form-control form-control-sm"
                  placeholder="Search Document"
                />
              </div>
              <label className="switch switch-sm mx-2">
                <input
                  type="checkbox"
                  className="switch-input"
                  checked={isActive}
                  onChange={(e) => setIsActive(e.target.checked)}
                />
                <span className="switch-toggle-slider">
                  <span className="switch-on"></span>
                  <span className="switch-off"></span>
                </span>
                <span className="switch-label">
                  {isActive ? "Active" : "In-Active"}
                </span>
              </label>
            </div>

            <div className="col-6 col-md-6 col-lg-8 text-end">
              {(isSelf || canUploadDocument) && (
                <button
                  className="btn btn-sm btn-primary me-3"
                  type="button"
                  onClick={() =>
                    setManageDoc({
                      document: null,
                      isOpen: true,
                    })
                  }
                >
                  <i className="bx bx-plus-circle me-2"></i>
                  <span className="d-none d-md-inline-block">
                    Add New Document
                  </span>
                </button>
              )}
            </div>
          </div>
          <DocumentsList
            Document_Entity={DocumentEntity}
            Entity={Entity}
            filters={filters}
            searchText={searchText}
            setIsRefetching={setIsRefetching}
            setRefetchFn={setRefetchFn}
            isActive={isActive}
          />
        </div>

        {ManageDoc.isOpen && (
          <GlobalModel
            isOpen={ManageDoc.isOpen}
            closeModal={() =>
              setManageDoc({
                document: null,
                isOpen: false,
              })
            }
          >
            <ManageDocument
              closeModal={() =>
                setManageDoc({
                  document: null,
                  isOpen: false,
                })
              }
              Document_Entity={DocumentEntity}
              Entity={Entity}
            />
          </GlobalModel>
        )}

        {viewDoc.isOpen && (
          <GlobalModel
            size="lg"
            isOpen={viewDoc.isOpen}
            closeModal={() =>
              setViewDoc({
                document: null,
                isOpen: false,
              })
            }
          >
            <ViewDocument />
          </GlobalModel>
        )}

        {OpenDocument && (
          <GlobalModel
            isOpen={OpenDocument}
            closeModal={() => setOpenDocument(false)}
          >
            <DocumentViewerModal />
          </GlobalModel>
        )}
      </div>
    </DocumentContext.Provider>
  );
};

export default Documents;
