import { useMemo, useState } from "react";
import {
  useActionOnExpense,
  useActionOnPaymentRequest,
  usePaymentRequestDetail,
} from "../../hooks/useExpense";
import {
  formatCurrency,
  formatFigure,
  getColorNameFromHex,
  getIconByFileType,
  localToUtc,
} from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Avatar from "../common/Avatar";
import DatePicker from "../common/DatePicker";
import EmployeeSearchInput from "../common/EmployeeSearchInput";
import Error from "../common/Error";
import {
  defaultActionValues,
  ExpenseActionScheam,
} from "../Expenses/ExpenseSchema";
import { ExpenseDetailsSkeleton } from "../Expenses/ExpenseSkeleton";
import ExpenseStatusLogs from "../Expenses/ExpenseStatusLogs";
import { useSelector } from "react-redux";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { usePaymentRequestContext } from "../../pages/PaymentRequest/PaymentRequestPage";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import {
  EXPENSE_REJECTEDBY,
  PROCESS_EXPENSE,
  REVIEW_EXPENSE,
} from "../../utils/constants";
import Label from "../common/Label";

const ViewPaymentRequest = ({ requestId }) => {
  const { data, isLoading, isError, error, isFetching } =
    usePaymentRequestDetail(requestId);
  const [IsPaymentProcess, setIsPaymentProcess] = useState(false);
  const [clickedStatusId, setClickedStatusId] = useState(null);

  const IsReview = useHasUserPermission(REVIEW_EXPENSE);
  const [imageLoaded, setImageLoaded] = useState({});
  const { setDocumentView, setModalSize, setVieRequest, setIsExpenseGenerate } =
    usePaymentRequestContext();
  const ActionSchema =
    ExpenseActionScheam(IsPaymentProcess, data?.createdAt) ?? z.object({});
  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setValue,
    reset,
    control,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(ActionSchema),
    defaultValues: defaultActionValues,
  });

  const userPermissions = useSelector(
    (state) => state?.globalVariables?.loginUser?.featurePermissions || []
  );
  const CurrentUser = useSelector(
    (state) => state?.globalVariables?.loginUser?.employeeInfo
  );

  const nextStatusWithPermission = useMemo(() => {
    if (!Array.isArray(data?.nextStatus)) return [];

    return data.nextStatus.filter((status) => {
      const permissionIds = Array.isArray(status?.permissionIds)
        ? status.permissionIds
        : [];

      if (permissionIds.length === 0) return true;
      if (permissionIds.includes(PROCESS_EXPENSE)) {
        setIsPaymentProcess(true);
      }
      return permissionIds.some((id) => userPermissions.includes(id));
    });
  }, [data, userPermissions]);

  const isRejectedRequest = useMemo(() => {
    return EXPENSE_REJECTEDBY.includes(data?.status?.id);
  }, [data]);

  const isCreatedBy = useMemo(() => {
    return data?.createdBy?.id === CurrentUser?.id;
  }, [data, CurrentUser]);

  const { mutate: MakeAction, isPending } = useActionOnPaymentRequest(() => {
    setClickedStatusId(null);
    reset();
  });

  const onSubmit = (formData) => {
    const Payload = {
      ...formData,
      paidAt: localToUtc(formData.reimburseDate),
      paymentRequestId: data.id,
      comment: formData.comment,
    };
    MakeAction(Payload);
  };

  if (isLoading) return <ExpenseDetailsSkeleton />;
  if (isError) return <Error error={error} />;
  const handleImageLoad = (id) => {
    setImageLoaded((prev) => ({ ...prev, [id]: true }));
  };
  const handleExpense = () => {
    setIsExpenseGenerate({ IsOpen: true, requestId: requestId });
    setVieRequest({ IsOpen: true, requestId: requestId });
  };
  return (
    <form
      className="container px-3 py-2 py-md-0"
      onSubmit={handleSubmit(onSubmit)}
    >
      <div className="col-12 mb-2 text-center ">
        <h5 className="fw-semibold m-0">Payment Request Details</h5>
        <hr />
      </div>
      <div className="row mb-1">
        <div className="col-12 col-sm-6 col-md-8">
          <div className="row">
            <div className="col-12 text-start fw-semibold mb-2">
              {data?.paymentRequestUID}
            </div>
            <div className="col-md-6 mb-3">
              <div className="d-block d-md-flex align-items-center">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Project Name:
                </label>
                <div className="text-muted">{data?.project?.name || "—"}</div>
              </div>
            </div>

            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Due Date :
                </label>
                <div className="text-muted">
                  {formatUTCToLocalTime(data?.dueDate)}
                </div>
              </div>
            </div>
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Expense Category :
                </label>
                <div className="text-muted">{data?.expenseCategory?.name}</div>
              </div>
            </div>

            {/* Row 2 */}
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Supplier :
                </label>
                <div className="text-muted">{data?.payee}</div>
              </div>
            </div>
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Amount :
                </label>
                <div className="text-muted">
                  {formatFigure(data?.amount, {
                    type: "currency",
                    currency: data?.currency?.currencyCode,
                  })}
                </div>
              </div>
            </div>

            {/* Row 3 */}
            {/* <div className="col-md-6 mb-3">
          <div className="d-flex">
            <label
              className="form-label me-2 mb-0 fw-semibold text-start"
              style={{ minWidth: "130px" }}
            >
              Payment Mode :
            </label>
            <div className="text-muted">{data?.paymentMode?.name}</div>
          </div>
         </div> */}
            {data?.gstNumber && (
              <div className="col-md-6 mb-3">
                <div className="d-flex">
                  <label
                    className="form-label me-2 mb-0 fw-semibold text-start"
                    style={{ minWidth: "130px" }}
                  >
                    GST Number :
                  </label>
                  <div className="text-muted">{data?.gstNumber}</div>
                </div>
              </div>
            )}

            {/* Row 4 */}
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Status :
                </label>
                <span
                  className={`badge bg-label-${
                    getColorNameFromHex(data?.expenseStatus?.color) ||
                    "secondary"
                  }`}
                >
                  {data?.expenseStatus?.name}
                </span>
              </div>
            </div>
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Pre-Approved :
                </label>
                <div className="text-muted">
                  {data?.preApproved ? "Yes" : "No"}
                </div>
              </div>
            </div>

            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Project :
                </label>
                <div className="text-muted">{data?.project?.name}</div>
              </div>
            </div>
            <div className="col-md-6 mb-3">
              <div className="d-flex">
                <label
                  className="form-label me-2 mb-0 fw-semibold text-start"
                  style={{ minWidth: "130px" }}
                >
                  Created At :
                </label>
                <div className="text-muted">
                  {formatUTCToLocalTime(data?.createdAt, true)}
                </div>
              </div>
            </div>

            {/* Row 6 */}
            {data?.createdBy && (
              <div className="col-md-6 text-start">
                <div className="d-flex align-items-center">
                  <label
                    className="form-label me-2 mb-0 fw-semibold"
                    style={{ minWidth: "130px" }}
                  >
                    Created By :
                  </label>
                  <div className="d-flex align-items-center">
                    <Avatar
                      size="xs"
                      classAvatar="m-0"
                      firstName={data?.createdBy?.firstName}
                      lastName={data?.createdBy?.lastName}
                    />
                    <span className="text-muted">
                      {`${data?.createdBy?.firstName ?? ""} ${
                        data?.createdBy?.lastName ?? ""
                      }`.trim() || "N/A"}
                    </span>
                  </div>
                </div>
              </div>
            )}
            {data?.paidBy && (
              <div className="col-md-6 text-start">
                <div className="d-flex align-items-center">
                  <label
                    className="form-label me-2 mb-0 fw-semibold"
                    style={{ minWidth: "130px" }}
                  >
                    Paid By :
                  </label>
                  <div className="d-flex align-items-center ">
                    <Avatar
                      size="xs"
                      classAvatar="m-0"
                      firstName={data?.paidBy?.firstName}
                      lastName={data?.paidBy?.lastName}
                    />
                    <span className="text-muted">
                      {`${data?.paidBy?.firstName ?? ""} ${
                        data?.paidBy?.lastName ?? ""
                      }`.trim() || "N/A"}
                    </span>
                  </div>
                </div>
              </div>
            )}

            <div className="text-start my-1">
              <label className="fw-semibold form-label">Description : </label>
              <div className="text-muted">{data?.description}</div>
            </div>
            <div className="col-6 text-start">
              <label className="form-label me-2 mb-2 fw-semibold">
                Attachment :
              </label>

              <div className="d-flex flex-wrap gap-2">
                {data?.attachments?.length > 0 ? (
                  <FilelistView
                    files={data?.attachments}
                    viewFile={setDocumentView}
                  />
                ) : (
                  <p className="m-0 text-secondary">No Attachment</p>
                )}
              </div>
            </div>

            {data?.paidTransactionId && (
              <div className="row text-start mt-2">
                <div className="col-md-6 mb-sm-0 mb-2">
                  <label className="form-label me-2 mb-0 fw-semibold">
                    Transaction ID :
                  </label>
                  {data?.paidTransactionId}
                </div>
                <div className="col-md-6 ">
                  <label className="form-label me-2 mb-0 fw-semibold">
                    Transaction Date :
                  </label>
                  {formatUTCToLocalTime(data?.paidAt)}
                </div>

                {data?.paidBy && (
                  <>
                    <div className="col-md-6  d-flex align-items-center">
                      <label className="form-label me-2 mb-0 fw-semibold">
                        Paid By :
                      </label>
                      <Avatar
                        size="xs"
                        classAvatar="m-0 me-1"
                        firstName={data?.paidBy?.firstName}
                        lastName={data?.paidBy?.lastName}
                      />
                      <span className="text-muted">
                        {`${data?.paidBy?.firstName} ${data?.paidBy?.lastName}`.trim()}
                      </span>
                    </div>
                  </>
                )}
              </div>
            )}

            {Array.isArray(data?.nextStatus) && data?.nextStatus.length > 0 ? (
              <>
                {IsPaymentProcess && nextStatusWithPermission?.length > 0 && (
                  <div className="row">
                    <div className="col-12 col-md-6 text-start">
                      <label className="form-label">Transaction Id </label>
                      <input
                        type="text"
                        className="form-control form-control-sm"
                        {...register("paidTransactionId")}
                      />
                      {errors.paidTransactionId && (
                        <small className="danger-text">
                          {errors.paidTransactionId.message}
                        </small>
                      )}
                    </div>
                    <div className="col-12 col-md-6 text-start mb-1">
                      <label className="form-label">Transaction Date </label>
                      <DatePicker
                        name="paidAt"
                        control={control}
                        minDate={data?.createdAt}
                        maxDate={new Date()}
                      />
                      {errors.paidAt && (
                        <small className="danger-text">
                          {errors.paidAt.message}
                        </small>
                      )}
                    </div>
                    <div className="col-12 col-md-6 text-start">
                      <label className="form-label">Paid By </label>
                      <EmployeeSearchInput
                        control={control}
                        name="paidById"
                        projectId={null}
                      />
                    </div>
                    <div className="col-12 col-md-6 text-start mb-1">
                      <Label className="form-label">TDS Percentage</Label>
                      <input
                        type="text"
                        className="form-control form-control-sm"
                        {...register("tdsPercentage")}
                      />
                      {errors.tdsPercentage && (
                        <small className="danger-text">
                          {errors.tdsPercentage.message}
                        </small>
                      )}
                    </div>
                    <div className="col-12 col-md-6 text-start mb-1">
                      <Label className="form-label" required>
                        Base Amount
                      </Label>
                      <input
                        type="text"
                        className="form-control form-control-sm"
                        {...register("baseAmount")}
                      />
                      {errors.baseAmount && (
                        <small className="danger-text">
                          {errors.baseAmount.message}
                        </small>
                      )}
                    </div>
                    <div className="col-12 col-md-6 text-start mb-1">
                      <Label className="form-label" required>
                        Tax Amount
                      </Label>
                      <input
                        type="text"
                        className="form-control form-control-sm"
                        {...register("taxAmount")}
                      />
                      {errors.taxAmount && (
                        <small className="danger-text">
                          {errors.taxAmount.message}
                        </small>
                      )}
                    </div>
                  </div>
                )}
                <div className="col-12 mb-3 text-start">
                  {((nextStatusWithPermission.length > 0 &&
                    !isRejectedRequest) ||
                    (isRejectedRequest && isCreatedBy)) && (
                    <>
                      <Label className="form-label me-2 mb-0" required>
                        Comment
                      </Label>
                      <textarea
                        className="form-control form-control-sm"
                        {...register("comment")}
                        rows="2"
                      />
                      {errors.comment && (
                        <small className="danger-text">
                          {errors.comment.message}
                        </small>
                      )}
                    </>
                  )}

                  {nextStatusWithPermission?.length > 0 &&
                    (!isRejectedRequest || isCreatedBy) && (
                      <div className="text-end flex-wrap gap-2 my-2 mt-3">
                        {nextStatusWithPermission?.map((status, index) => (
                          <button
                            key={status.id || index}
                            type="button"
                            onClick={() => {
                              setClickedStatusId(status.id);
                              setValue("statusId", status.id);
                              handleSubmit(onSubmit)();
                            }}
                            disabled={isPending || isFetching}
                            className="btn btn-primary btn-sm cursor-pointer mx-2 border-0"
                          >
                            {isPending && clickedStatusId === status.id
                              ? "Please Wait..."
                              : status.displayName || status.name}
                          </button>
                        ))}
                      </div>
                    )}
                </div>
              </>
            ) : !data?.isExpenseCreated ? (
              <div className="text-end flex-wrap gap-2 my-2 mt-3">
                <button
                  className="btn btn-sm btn-primary"
                  onClick={handleExpense}
                >
                  Make Expense
                </button>
              </div>
            ) : (
              <></>
            )}
          </div>
        </div>
        <div className=" col-sm-12  my-md-0 border-top border-md-none col-md-5">
          <div className="d-flex mb-2 py-1">
            <i className="bx bx-time-five me-2 "></i>{" "}
            <p className="fw-medium">TimeLine</p>
          </div>
          <PaymentStat data={data} />
        </div>
      </div>
    </form>
  );
};
export default ViewPaymentRequest;
