import React, { useEffect, useState } from "react";
import Label from "../common/Label";
import { Controller, useForm } from "react-hook-form";
import {
  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 { useCurrencies, useProjectName } from "../../hooks/useProjects";
import {
  useCreateRecurringExpense,
  usePayee,
  useRecurringExpenseDetail,
  useUpdateRecurringExpense,
} from "../../hooks/useExpense";
import InputSuggestions from "../common/InputSuggestion";
import MultiEmployeeSearchInput from "../common/MultiEmployeeSearchInput";

function ManageRecurringExpense({ closeModal, requestToEdit = null }) {
  const {
    data,
    isLoading,
    isError,
    error: requestError,
  } = useRecurringExpenseDetail(requestToEdit);

  //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: PaymentRequestUpdate, isPending } = useUpdatePaymentRequest(() =>
  //     handleClose()
  // );

  useEffect(() => {
    if (requestToEdit && data) {
      reset({
        title: data.title || "",
        description: data.description || "",
        payee: data.payee || "",
        notifyTo: data.notifyTo || "",
        currencyId: data.currency.id || "",
        amount: data.amount || "",
        strikeDate: data.strikeDate?.slice(0, 10) || "",
        projectId: data.project.id || "",
        paymentBufferDays: data.paymentBufferDays || "",
        numberOfIteration: data.numberOfIteration || "",
        expenseCategoryId: data.expenseCategory.id || "",
        statusId: data.statusId || "",
        frequency: data.frequency || "",
        isVariable: data.isVariable || false,
      });
    }
  }, [data, reset]);

  // console.log("Veer",data)

  const onSubmit = (fromdata) => {
    let payload = {
      ...fromdata,
      // strikeDate: localToUtc(fromdata.strikeDate),
      strikeDate: fromdata.strikeDate
        ? new Date(fromdata.strikeDate).toISOString()
        : null,
    };
    if (requestToEdit) {
      const editPayload = { ...payload, id: data.id };
      PaymentRequestUpdate({ id: data.id, payload: editPayload });
    } else {
      CreateRecurringExpense(payload);
    }
    console.log("Kartik", 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">
            <Label htmlFor="isVariable" className="form-label" required>
              Payment Type
            </Label>

            <Controller
              name="isVariable"
              control={control}
              defaultValue={defaultRecurringExpense.isVariable ?? false}
              render={({ field }) => (
                <div className="d-flex align-items-center gap-3">
                  <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">
            <Label htmlFor="frequency" className="form-label" required>
              Frequency
            </Label>
            <select
              id="frequency"
              className="form-select form-select-sm"
              {...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>}

              {!currencyLoading &&
                !currencyError &&
                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 Number of Iteration */}
        <div className="row my-2 text-start">
          <div className="col-md-6">
            <Label htmlFor="paymentBufferDays" className="form-label" required>
              Payment Buffer Days
            </Label>
            <input
              type="number"
              id="paymentBufferDays"
              className="form-control form-control-sm"
              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">
            <Label htmlFor="numberOfIteration" className="form-label" required>
              Number of Iteration
            </Label>
            <input
              type="number"
              id="numberOfIteration"
              className="form-control form-control-sm"
              min="1"
              step="1"
              {...register("numberOfIteration", { valueAsNumber: true })}
              placeholder="Enter number of iterations"
            />
            {errors.numberOfIteration && (
              <small className="danger-text">
                {errors.numberOfIteration.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}
            />
          </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">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}

export default ManageRecurringExpense;
