import React, { useEffect } from "react";
import { FormProvider, useForm } from "react-hook-form";
import {
  useCreateOrganization,
  useOrganization,
  useOrganizationModal,
  useUpdateOrganization,
} from "../../hooks/useOrganization";
import {
  defaultOrganizationValues,
  organizationSchema,
} from "./OrganizationSchema";
import Label from "../common/Label";
import { useGlobalServices } from "../../hooks/masterHook/useMaster";
import { zodResolver } from "@hookform/resolvers/zod";
import SelectMultiple from "../common/SelectMultiple";

const ManagOrg = () => {
  const { data: service, isLoading } = useGlobalServices();
  const { flowType, orgData, startStep, onOpen, onClose, prevStep } =
    useOrganizationModal();
  const {
    data: organization,
    isLoading: organizationLoading,
    isError,
    error,
  } = useOrganization(orgData?.id);

  const method = useForm({
    resolver: zodResolver(organizationSchema),
    defaultValues: defaultOrganizationValues,
  });

  const {
    handleSubmit,
    register,
    reset,
    formState: { errors },
  } = method;

  // Create & Update mutations
  const { mutate: createOrganization, isPending: isCreating } =
    useCreateOrganization(() => {
      reset(defaultOrganizationValues);
      onOpen({ startStep: 1 });
      onClose();
    });

  const { mutate: updateOrganization, isPending: isUpdating } =
    useUpdateOrganization(() => {
      reset(defaultOrganizationValues);
      onOpen({ startStep: 1 });
      onClose();
    });
  // Prefill form if editing
  useEffect(() => {
    if (organization) {
      reset({
        name: organization.name || "",
        contactPerson: organization.contactPerson || "",
        contactNumber: organization.contactNumber || "",
        email: organization.email || "",
        serviceIds: organization.services?.map((s) => s.id) || [],
        address: organization.address || "",
      });
    }
  }, [organization, reset, service?.data]);

  const onSubmit = (formData) => {
    let payload = { ...formData };
    if (organization?.id) {
      updateOrganization({
        orgId: organization.id,
        payload: { ...payload, id: organization.id },
      });
    } else {
      createOrganization(payload);
    }
  };
  const handleBack = () => {
    if (flowType === "edit") {
      onClose();
      return;
    }

    if (flowType === "assign") {
      if (prevStep === 1) {
        onOpen({ startStep: 1 });
      } else {
        onOpen({ startStep: prevStep ?? 2 });
      }
      return;
    }
    onOpen({ startStep: 2 });
  };
  return (
    <FormProvider {...method}>
      <form className="form" onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-1 text-start">
          <Label htmlFor="name" required>
            Organization Name
          </Label>
          <input
            className="form-control form-control-sm"
            {...register("name")}
          />
          {errors.name && (
            <span className="danger-text">{errors.name.message}</span>
          )}
        </div>

        <div className="mb-1 text-start">
          <Label htmlFor="contactPerson" required>
            Contact Person
          </Label>
          <input
            className="form-control form-control-sm"
            {...register("contactPerson")}
          />
          {errors.contactPerson && (
            <span className="danger-text">{errors.contactPerson.message}</span>
          )}
        </div>

        <div className="mb-1 text-start">
          <Label htmlFor="contactNumber" required>
            Contact Number
          </Label>
          <input
            className="form-control form-control-sm"
            {...register("contactNumber")}
          />
          {errors.contactNumber && (
            <span className="danger-text">{errors.contactNumber.message}</span>
          )}
        </div>

        <div className="mb-1 text-start">
          <Label htmlFor="email" required>
            Email Address
          </Label>
          <input
            className="form-control form-control-sm"
            {...register("email")}
          />
          {errors.email && (
            <span className="danger-text">{errors.email.message}</span>
          )}
        </div>

        <div className="mb-1 text-start">
          <SelectMultiple
            name="serviceIds"
            label="Select Service"
            options={service?.data}
            labelKey="name"
            valueKey="id"
            IsLoading={isLoading}
          />
          {errors.serviceIds && (
            <span className="danger-text">{errors.serviceIds.message}</span>
          )}
        </div>

        <div className="mb-1 text-start">
          <Label htmlFor="address" required>
            Address
          </Label>
          <textarea
            className="form-control form-control-sm"
            {...register("address")}
            rows={2}
          />
          {errors.address && (
            <span className="danger-text">{errors.address.message}</span>
          )}
        </div>

        <div className="d-flex justify-content-between gap-2 my-2">
          <button
            type="button"
            className="btn btn-sm btn-outline-secondary"
            onClick={handleBack}
          >
            {flowType === "edit" ? (
              "Close"
            ) : (
              <>
                <i className="bx bx-chevron-left"></i>Back
              </>
            )}
          </button>
          <div>
            <button
              type="submit"
              className="btn btn-sm btn-primary"
              disabled={isCreating || isUpdating || isLoading}
            >
              {isCreating || isUpdating
                ? "Please Wait..."
                : orgData
                ? "Update"
                : "Submit"}
            </button>
          </div>
        </div>
      </form>
    </FormProvider>
  );
};

export default ManagOrg;
