import React, { useEffect, useState,useMemo } from "react";
import { FormProvider, useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultFilter, SearchSchema } from "./ExpenseSchema";

import DateRangePicker, { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple";

import { useProjectName } from "../../hooks/useProjects";
import { useExpenseStatus } from "../../hooks/masterHook/useMaster";
import { useEmployeesAllOrByProjectId } from "../../hooks/useEmployees";
import { useSelector } from "react-redux";
import moment from "moment";
import { useExpenseFilter } from "../../hooks/useExpense";
import { ExpenseFilterSkeleton } from "./ExpenseSkeleton";



const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
  const selectedProjectId = useSelector((store) => store.localVariables.projectId);
  const { data, isLoading,isError,error,isFetching , isFetched} = useExpenseFilter();

const groupByList = useMemo(() => {
  return [
    { id: "transactionDate", name: "Transaction Date" },
    { id: "status", name: "Status" },
    { id: "submittedBy", name: "Submitted By" },
    { id: "project", name: "Project" },
    { id: "paymentMode", name: "Payment Mode" },
    { id: "expensesType", name: "Expense Type" },
    { id: "createdAt", name: "Submitted Date" }
  ].sort((a, b) => a.name.localeCompare(b.name));
}, []);


  const [selectedGroup, setSelectedGroup] = useState(groupByList[0]);
  const [resetKey, setResetKey] = useState(0);

  const methods = useForm({
    resolver: zodResolver(SearchSchema),
    defaultValues: defaultFilter,
  });

  const { control, register, handleSubmit, reset, watch } = methods;
  const isTransactionDate = watch("isTransactionDate");

  const closePanel = () => {
    document.querySelector(".offcanvas.show .btn-close")?.click();
  };

  const handleGroupChange = (e) => {
    const group = groupByList.find((g) => g.id === e.target.value);
    if (group) setSelectedGroup(group);
  };

  const onSubmit = (formData) => {
    onApply({
      ...formData,
      startDate: moment.utc(formData.startDate, "DD-MM-YYYY").toISOString(),
      endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(),
    });
    handleGroupBy(selectedGroup.id);
    closePanel();
  };

  const onClear = () => {
    reset(defaultFilter);
    setResetKey((prev) => prev + 1);
    setSelectedGroup(groupByList[0]);
    onApply(defaultFilter);
    handleGroupBy(groupByList[0].id);
    closePanel();
  };

  if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
  if(isError && isFetched) return <div>Something went wrong Here- {error.message} </div>
  return (
    <>

      <FormProvider {...methods}>
        <form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
          <div className="mb-3 w-100">
            <div className="d-flex align-items-center mb-2">
              <label className="form-label me-2">Choose Date:</label>
              <div className="form-check form-switch m-0">
                <input
                  className="form-check-input"
                  type="checkbox"
                  id="switchOption1"
                  {...register("isTransactionDate")}
                />
              </div>
              <label className="form-label mb-0 ms-2">
                {isTransactionDate ? "Submitted": "Transaction" }
              </label>
            </div>

            <DateRangePicker1
              placeholder="DD-MM-YYYY To DD-MM-YYYY"
              startField="startDate"
              endField="endDate"
              resetSignal={resetKey}
            />
          </div>

          <div className="row g-2">
            <SelectMultiple
              name="projectIds"
              label="Projects :"
              options={data.projects}
              labelKey="name"
              valueKey="id"
            />
            <SelectMultiple
              name="createdByIds"
              label="Submitted By :"
              options={data.createdBy}
              labelKey={(item) => item.name}
              valueKey="id"
            />
            <SelectMultiple
              name="paidById"
              label="Paid By :"
              options={data.paidBy}
              labelKey={(item) => item.name}
              valueKey="id"
            />

            <div className="mb-3">
              <label className="form-label">Status :</label>
              <div className="row flex-wrap">
                {data?.status
                  ?.slice()
                  .sort((a, b) => a.name.localeCompare(b.name))
                  .map((status) => (
                    <div className="col-6" key={status.id}>
                      <Controller
                        control={control}
                        name="statusIds"
                        render={({ field: { value = [], onChange } }) => (
                          <div className="d-flex align-items-center me-3 mb-2">
                            <input
                              type="checkbox"
                              className="form-check-input"
                              value={status.id}
                              checked={value.includes(status.id)}
                              onChange={(e) => {
                                const checked = e.target.checked;
                                onChange(
                                  checked
                                    ? [...value, status.id]
                                    : value.filter((v) => v !== status.id)
                                );
                              }}
                            />
                            <label className="ms-2 mb-0">{status.name}</label>
                          </div>
                        )}
                      />
                    </div>
                  ))}
              </div>
            </div>
          </div>
            <div className="mb-2 text-start ">
        <label htmlFor="groupBySelect" className="form-label">Group By :</label>
        <select
          id="groupBySelect"
          className="form-select form-select-sm"
          value={selectedGroup?.id || ""}
          onChange={handleGroupChange}
        >
          {groupByList.map((group) => (
            <option key={group.id} value={group.id}>
              {group.name}
            </option>
          ))}
        </select>
      </div>

          <div className="d-flex justify-content-end py-3 gap-2">
            <button
              type="button"
              className="btn btn-secondary btn-xs"
              onClick={onClear}
            >
              Clear
            </button>
            <button type="submit" className="btn btn-primary btn-xs">
              Apply
            </button>
          </div>
        </form>
      </FormProvider>
      
    </>
  );
};

export default ExpenseFilterPanel;