import React, { createContext, useContext, useEffect, useState } from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useServices } from "../../hooks/masterHook/useMaster";
import TaskReportList from "../../components/DailyProgressRport/TaskReportList";
import GlobalModel from "../../components/common/GlobalModel";
import ReportTaskComments from "../../components/Activities/ReportTaskComments";
import ReportTask from "../../components/Activities/ReportTask";
import TaskReportFilterPanel from "../../components/DailyProgressRport/TaskReportFilterPanel";
import { useFab } from "../../Context/FabContext";
import SubTask from "../../components/Activities/SubTask";
import { useProjectAssignedServices } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
import SelectField from "../../components/common/Forms/SelectField";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import { useForm } from "react-hook-form";

const DailyProgrssContext = createContext();
export const useDailyProgrssContext = () => {
  const context = useContext(DailyProgrssContext);
  if (!context) {
    throw new Error(
      "useDailyTaskContext must be used within a DailyTaskProvider"
    );
  }
  return context;
};

const DailyProgrssReport = () => {
  const selectedProject = useSelectedProject()
  const [service, setService] = useState("");
  const [filter, setFilter] = useState('')
  const { setOffcanvasContent, setShowTrigger } = useFab();
  const { data, isLoading, isError, error } = useProjectAssignedServices(selectedProject);

  const [modal, setModal] = useState({ type: null, data: null });

  const openModal = (type, data = null) => setModal({ type, data });
  const closeModal = () => setModal({ type: null, data: null });

  const contextDispatcher = {
    service,
    openModal,
    closeModal,
    filter,
  };

  const { control } = useForm({
    defaultValues: {
      serviceFilter: ""
    }
  });

  const handleFilter = (filterObj) => {
    setFilter(filterObj)
  }

  useEffect(() => {
    setShowTrigger(true);
    setOffcanvasContent("Report Filter", <TaskReportFilterPanel handleFilter={handleFilter} />);

    return () => {
      setShowTrigger(false);
      setOffcanvasContent("", null);
    };
  }, []);
  return (
    <div className="container-fluid">
      <DailyProgrssContext.Provider value={contextDispatcher}>
        {modal.type === "report" && (
          <GlobalModel isOpen size="md" closeModal={closeModal}>
            <ReportTask report={modal.data} closeModal={closeModal} />
          </GlobalModel>
        )}
        {modal.type === "comments" && (
          <GlobalModel isOpen size="lg" closeModal={closeModal}>
            <ReportTaskComments
              commentsData={modal.data.task}
              actionAllow={modal.data.isActionAllow}
              handleCloseAction={(isSubTask) => {
                if (isSubTask) openModal("subtask", modal.data.task);
                else closeModal();
              }}
              closeModal={closeModal}
            />
          </GlobalModel>
        )}
        {modal.type === "subtask" && (
          <GlobalModel isOpen size="lg" closeModal={closeModal}>
            <SubTask activity={modal.data} onClose={closeModal} />
          </GlobalModel>
        )}

        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Daily Progress Report" },
          ]}
        />

        <div className="card page-min-h p-5">
          {data?.length > 0 && (
            <div className="col-sm-4 col-md-3 col-12 text-start">
              <AppFormController
                name="serviceFilter"
                control={control}
                defaultValue={service ?? ""}
                render={({ field }) => (
                  <SelectField
                    label="Services"
                    options={[{ id: "", name: "All Projects" }, ...(data ?? [])]} 
                    placeholder="Select Service"
                    labelKey="name"  
                    valueKey="id"
                    isLoading={isLoading}
                    value={field.value}
                    onChange={(val) => {
                      field.onChange(val);  
                      setService(val);      
                    }}
                    className="m-0"
                  />
                )}
              />
            </div>
          )}

          <div>
            <TaskReportList />
          </div>
        </div>


      </DailyProgrssContext.Provider>
    </div>
  );
};

export default DailyProgrssReport;
