import React, { useEffect, useState } from "react";
import Label from "../common/Label";
import { Controller, useForm } from "react-hook-form";
import {
  useCurrencies,
  useExpenseCategory,
  useRecurringStatus,
} from "../../hooks/masterHook/useMaster";
import DatePicker from "../common/DatePicker";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  defaultRecurringExpense,
  PaymentRecurringExpense,
} from "./RecurringExpenseSchema";
import {
  FREQUENCY_FOR_RECURRING,
  INR_CURRENCY_CODE,
} from "../../utils/constants";
import { useProjectName } from "../../hooks/useProjects";
import {
  useCreateRecurringExpense,
  usePayee,
  useRecurringExpenseDetail,
  useUpdateRecurringExpense,
} from "../../hooks/useExpense";
import InputSuggestions from "../common/InputSuggestion";
import { useEmployeesName } from "../../hooks/useEmployees";
import PmsEmployeeInputTag from "../common/PmsEmployeeInputTag";
import HoverPopup from "../common/HoverPopup";

const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
  const {
    data,
    isLoading,
    isError,
    error: requestError,
  } = useRecurringExpenseDetail(requestToEdit);
  const { data: employees } = useEmployeesName(null, null, true);
  //APIs
  const {
    projectNames,
    loading: projectLoading,
    error,
    isError: isProjectError,
  } = useProjectName();
  const {
    data: currencyData,
    isLoading: currencyLoading,
    isError: currencyError,
  } = useCurrencies();
  const {
    data: statusData,
    isLoading: statusLoading,
    isError: statusError,
  } = useRecurringStatus();
  const {
    data: Payees,
    isLoading: isPayeeLoaing,
    isError: isPayeeError,
    error: payeeError,
  } = usePayee();
  const {
    expenseCategories,
    loading: ExpenseLoading,
    error: ExpenseError,
  } = useExpenseCategory();

  const schema = PaymentRecurringExpense();
  const {
    register,
    control,
    watch,
    handleSubmit,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: defaultRecurringExpense,
  });
  const handleClose = () => {
    reset();
    closeModal();
  };

  const { mutate: CreateRecurringExpense, isPending: createPending } =
    useCreateRecurringExpense(() => {
      handleClose();
    });
  const { mutate: RecurringExpenseUpdate, isPending } =
    useUpdateRecurringExpense(() => handleClose());
  const handleEmailGetting = (userArray = []) => {
    if (!Array.isArray(userArray) || userArray.length === 0) return [];

    return userArray
      .map((empId) => {
        const foundUser = employees?.data?.find((user) => user.id === empId);
        return foundUser?.email || null;
      })
      .filter(Boolean)
      .join(",");
  };
  useEffect(() => {
    if (requestToEdit && data) {
      reset({
        title: data.title || "",
        description: data.description || "",
        payee: data.payee || "",
        notifyTo: data.notifyTo ? data.notifyTo.map((usr) => usr.id) : [],
        currencyId: data.currency.id || "",
        amount: data.amount || "",
        strikeDate: data.strikeDate?.slice(0, 10) || "",
        projectId: data.project.id || "",
        paymentBufferDays: data.paymentBufferDays || "",
        // numberOfIteration: data.numberOfIteration || "",
        endDate: data.endDate?.slice(0, 10) || "",
        expenseCategoryId: data.expenseCategory.id || "",
        statusId: data.status.id || "",
        frequency: data.frequency || "",
        isVariable: data.isVariable || false,
      });
    }
  }, [data, reset]);

  useEffect(() => {
    if (!requestToEdit && currencyData && currencyData.length > 0) {
      const inrCurrency = currencyData.find((c) => c.id === INR_CURRENCY_CODE);
      if (inrCurrency) {
        setValue("currencyId", INR_CURRENCY_CODE, { shouldValidate: true });
      }
    }
  }, [currencyData, requestToEdit, setValue]);

  const StrikeDate = watch("strikeDate")

  const onSubmit = (fromdata) => {
    let payload = {
      ...fromdata,
      strikeDate: fromdata.strikeDate
        ? new Date(fromdata.strikeDate).toISOString()
        : null,
      endDate: fromdata.endDate
        ? new Date(fromdata.endDate).toISOString()
        : null,
      notifyTo: handleEmailGetting(fromdata.notifyTo),
    };
    if (requestToEdit) {
      const editPayload = { ...payload, id: data.id };
      RecurringExpenseUpdate({ id: data.id, payload: editPayload });
    } else {
      CreateRecurringExpense(payload);
    }
  };

  return (
    <div className="container p-3">
      <h5 className="m-0">
        {requestToEdit
          ? "Update Expense Recurring "
          : "Create Expense Recurring"}
      </h5>
      <form id="expenseForm" onSubmit={handleSubmit(onSubmit)}>
        {/* Project and Category */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label className="form-label" required>
              Select Project
            </Label>
            <select
              className="form-select form-select-sm"
              {...register("projectId")}
            >
              <option value="">Select Project</option>
              {projectLoading ? (
                <option>Loading...</option>
              ) : (
                projectNames?.map((project) => (
                  <option key={project.id} value={project.id}>
                    {project.name}
                  </option>
                ))
              )}
            </select>
            {errors.projectId && (
              <small className="danger-text">{errors.projectId.message}</small>
            )}
          </div>

          <div className="col-md-6">
            <Label htmlFor="expenseCategoryId" className="form-label" required>
              Expense Category
            </Label>
            <select
              className="form-select form-select-sm"
              id="expenseCategoryId"
              {...register("expenseCategoryId")}
            >
              <option value="" disabled>
                Select Category
              </option>
              {ExpenseLoading ? (
                <option disabled>Loading...</option>
              ) : (
                expenseCategories?.map((expense) => (
                  <option key={expense.id} value={expense.id}>
                    {expense.name}
                  </option>
                ))
              )}
            </select>
            {errors.expenseCategoryId && (
              <small className="danger-text">
                {errors.expenseCategoryId.message}
              </small>
            )}
          </div>
        </div>

        {/* Title and Is Variable  */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label htmlFor="title" className="form-label" required>
              Title
            </Label>
            <input
              type="text"
              id="title"
              className="form-control form-control-sm"
              {...register("title")}
              placeholder="Enter title"
            />
            {errors.title && (
              <small className="danger-text">{errors.title.message}</small>
            )}
          </div>

          <div className="col-md-6 mt-2">
            <div className="d-flex justify-content-start align-items-center gap-2">
              <Label htmlFor="isVariable" className="form-label mb-0" required>
                Payment Type
              </Label>
              <HoverPopup
                title="Payment Type"
                id="payment_type"
                content={
                  <p>
                    Choose whether the payment amount varies or remains fixed each cycle.
                    <br />
                    <strong>Is Variable:</strong> Amount changes per cycle.
                    <br />
                    <strong>Fixed:</strong> Amount stays constant.
                  </p>
                }
              >
                <i className="bx bx-info-circle bx-sm text-muted cursor-pointer"></i>
              </HoverPopup>
            </div>

            <Controller
              name="isVariable"
              control={control}
              defaultValue={defaultRecurringExpense.isVariable ?? false}
              render={({ field }) => (
                <div className="d-flex align-items-center gap-3 mt-1">
                  <div className="form-check">
                    <input
                      type="radio"
                      id="isVariableTrue"
                      className="form-check-input"
                      checked={field.value === true}
                      onChange={() => field.onChange(true)}
                    />
                    <Label htmlFor="isVariableTrue" className="form-check-label">
                      Is Variable
                    </Label>
                  </div>

                  <div className="form-check">
                    <input
                      type="radio"
                      id="isVariableFalse"
                      className="form-check-input"
                      checked={field.value === false}
                      onChange={() => field.onChange(false)}
                    />
                    <Label htmlFor="isVariableFalse" className="form-check-label">
                      Fixed
                    </Label>
                  </div>
                </div>
              )}
            />

            {errors.isVariable && (
              <small className="danger-text">{errors.isVariable.message}</small>
            )}
          </div>

        </div>

        {/* Date and Amount */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label htmlFor="strikeDate" className="form-label" required>
              Strike Date
            </Label>
            <DatePicker
              name="strikeDate"
              control={control}
              minDate={new Date()}
              className="w-100"
            />
            {errors.strikeDate && (
              <small className="danger-text">{errors.strikeDate.message}</small>
            )}
          </div>

          <div className="col-md-6">
            <Label htmlFor="amount" className="form-label" required>
              Amount
            </Label>
            <input
              type="number"
              id="amount"
              className="form-control form-control-sm"
              min="1"
              step="0.01"
              inputMode="decimal"
              {...register("amount", { valueAsNumber: true })}
              placeholder="Enter amount"
            />
            {errors.amount && (
              <small className="danger-text">{errors.amount.message}</small>
            )}
          </div>
        </div>

        {/* Payee and Currency  */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label htmlFor="payee" className="form-label" required>
              Payee (Supplier Name/Transporter Name/Other)
            </Label>
            <InputSuggestions
              organizationList={Payees}
              value={watch("payee") || ""}
              onChange={(val) =>
                setValue("payee", val, { shouldValidate: true })
              }
              error={errors.payee?.message}
              placeholder="Select or enter payee"
            />
          </div>

          <div className="col-md-6">
            <Label htmlFor="currencyId" className="form-label" required>
              Currency
            </Label>
            <select
              id="currencyId"
              className="form-select form-select-sm"
              {...register("currencyId")}
            >
              <option value="">Select Currency</option>

              {currencyLoading && <option>Loading...</option>}

              {!currencyLoading &&
                !currencyError &&
                currencyData?.map((currency) => (
                  <option key={currency.id} value={currency.id}>
                    {`${currency.currencyName} (${currency.symbol})`}
                  </option>
                ))}
            </select>
            {errors.currencyId && (
              <small className="danger-text">{errors.currencyId.message}</small>
            )}
          </div>
        </div>

        {/* Frequency To and Status Id  */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <div className="d-flex justify-content-start align-items-center gap-2">
              <Label htmlFor="frequency" className="form-label mb-0" required>
                Frequency
              </Label>
              <HoverPopup
                title="Frequency"
                id="frequency"
                content={
                  <p>
                    Defines how often payments or billing occur, such as monthly, quarterly, or annually.
                  </p>
                }
              >
                <i className="bx bx-info-circle bx-sm text-muted cursor-pointer"></i>
              </HoverPopup>
            </div>

            <select
              id="frequency"
              className="form-select form-select-sm mt-1"
              {...register("frequency", { valueAsNumber: true })}
            >
              <option value="">Select Frequency</option>
              {Object.entries(FREQUENCY_FOR_RECURRING).map(([key, label]) => (
                <option key={key} value={key}>
                  {label}
                </option>
              ))}
            </select>

            {errors.frequency && (
              <small className="danger-text">{errors.frequency.message}</small>
            )}
          </div>

          <div className="col-md-6">
            <Label htmlFor="statusId" className="form-label" required>
              Status
            </Label>
            <select
              id="statusId"
              className="form-select form-select-sm"
              {...register("statusId")}
            >
              <option value="">Select Status</option>
              {statusLoading && <option>Loading...</option>}
              {!statusLoading &&
                !statusError &&
                statusData?.map((status) => (
                  <option key={status.id} value={status.id}>
                    {status.name}
                  </option>
                ))}
            </select>
            {errors.statusId && (
              <small className="danger-text">{errors.statusId.message}</small>
            )}
          </div>
        </div>

        {/* Payment Buffer Days and End Date */}
        <div className="row my-2 text-start">

          <div className="col-md-6">
            <div className="d-flex justify-content-start align-items-center gap-2">
              <Label htmlFor="paymentBufferDays" className="form-label mb-0" required>
                Payment Buffer Days
              </Label>
              <HoverPopup
                title="Payment Buffer Days"
                id="payment_buffer_days"
                content={
                  <p>
                    Number of extra days allowed after the due date before payment is considered late.
                  </p>
                }
              >
                <i className="bx bx-info-circle bx-sm text-muted cursor-pointer"></i>
              </HoverPopup>
            </div>

            <input
              type="number"
              id="paymentBufferDays"
              className="form-control form-control-sm mt-1"
              min="0"
              step="1"
              {...register("paymentBufferDays", { valueAsNumber: true })}
              placeholder="Enter payment buffer days"
            />

            {errors.paymentBufferDays && (
              <small className="danger-text">
                {errors.paymentBufferDays.message}
              </small>
            )}
          </div>


          <div className="col-md-6">
            <div className="d-flex justify-content-start align-items-center gap-2">
              <Label htmlFor="endDate" className="form-label mb-0" required>
                End Date
              </Label>
              <HoverPopup
                title="End Date"
                id="end_date"
                content={
                  <p>
                    The date when the last payment in the recurrence occurs.
                  </p>
                }
              >
                <i className="bx bx-info-circle bx-sm text-muted cursor-pointer"></i>
              </HoverPopup>
            </div>

            <DatePicker
              name="endDate"
              control={control}
              minDate={StrikeDate}
              className="w-100 mt-1"
            />

            {errors.endDate && (
              <small className="danger-text">{errors.endDate.message}</small>
            )}
          </div>

        </div>


        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label htmlFor="notifyTo" className="form-label" required>
              Notify Employees
            </Label>

            {/* <MultiEmployeeSearchInput
                            control={control}
                            name="notifyTo"
                            projectId={watch("projectId")}
                            placeholder="Select Employees"
                            forAll={true}
                        /> */}
            <PmsEmployeeInputTag
              control={control}
              name="notifyTo"
              placeholder="Type to search users"
              projectId={watch("projectId")}
              forAll={true}
            />
            {errors.notifyTo && (
              <small className="danger-text">{errors.notifyTo.message}</small>
            )}
          </div>
        </div>

        {/* Description  */}
        <div className="row my-2 text-start">
          <div className="col-md-12">
            <Label htmlFor="description" className="form-label" required>
              Description
            </Label>
            <textarea
              id="description"
              className="form-control form-control-sm"
              {...register("description")}
              rows="2"
            ></textarea>
            {errors.description && (
              <small className="danger-text">
                {errors.description.message}
              </small>
            )}
          </div>
        </div>

        <div className="d-flex justify-content-end gap-3">
          <button
            type="reset"
            onClick={handleClose}
            className="btn btn-label-secondary btn-sm mt-3"
          >
            Cancel
          </button>
          <button type="submit" className="btn btn-primary btn-sm mt-3">
            {createPending || isPending
              ? "Please wait...."
              : requestToEdit
                ? "Update"
                : "Save as Draft"}
          </button>
        </div>
      </form>
    </div>
  );
};

export default ManageRecurringExpense;
