import React, { useEffect, useState } from "react";
import { useFormContext, Controller } from "react-hook-form";
import Label from "../common/Label";
import DatePicker from "../common/DatePicker";
import { useCreateTenant, useIndustries } from "../../hooks/useTenant";
import { LogoUpload } from "./LogoUpload";
import { orgSize, reference } from "../../utils/constants";
import moment from "moment";
import { useGlobalServices } from "../../hooks/masterHook/useMaster";
import SelectMultiple from "../common/SelectMultiple";

const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
  const { data, isError, isLoading: industryLoading } = useIndustries();
  const [logoPreview, setLogoPreview] = useState(null);
  const [logoName, setLogoName] = useState("");
  const { data: services, isLoading: serviceLoading } = useGlobalServices();
  const {
    register,
    control,
    setValue,
    getValues,
    trigger,
    formState: { errors },
  } = useFormContext();

  const {
    mutate: CreateTenant,
    isError: tenantError,
    error,
    isPending,
  } = useCreateTenant(() => {
    debugger
    onNext()
  });

  const handleNext = async () => {
    const valid = await trigger([
      "organizationName",
      "officeNumber",
      "domainName",
      "description",
      "onBoardingDate",
      "organizationSize",
      "taxId",
      "industryId",
      "reference",
      "logoImage",
      "serviceIds",
    ]);

    if (valid) {
      const data = getValues();
      // onSubmitTenant(data);
      // onNext();
      const tenantPayload = { ...data, onBoardingDate: moment.utc(data.onBoardingDate, "DD-MM-YYYY").toISOString() }
      CreateTenant(tenantPayload);
    }
  };

  useEffect(() => {
    const logoImage = getValues("logoImage");
    if (logoImage) {
      setLogoPreview(logoImage);
      setLogoName("Uploaded Logo");
    }
  }, [getValues]);


  return (
    <div className="row g-2 text-start">
      <div className="col-sm-6">
        <Label htmlFor="organizationName" required>
          Organization Name
        </Label>

        <input
          id="organizationName"
          className={`form-control form-control-sm `}
          {...register("organizationName")}
        />
        {errors.organizationName && (
          <div className="danger-text">{errors.organizationName.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="officeNumber" >
          Office Number
        </Label>
        <input
          id="officeNumber"
          className={`form-control form-control-sm `}
          {...register("officeNumber")}
        />
        {errors.officeNumber && (
          <div className="danger-text">{errors.officeNumber.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="domainName" >
          Domain Name
        </Label>
        <input
          id="domainName"
          className={`form-control form-control-sm `}
          {...register("domainName")}
        />
        {errors.domainName && (
          <div className="danger-text">{errors.domainName.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="taxId" >
          Tax ID
        </Label>
        <input
          id="taxId"
          className={`form-control form-control-sm `}
          {...register("taxId")}
        />
        {errors.taxId && (
          <div className="danger-text">{errors.taxId.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="onBoardingDate" required>
          Onboarding Date
        </Label>
        <DatePicker
          name="onBoardingDate"
          control={control}
          placeholder="DD-MM-YYYY"
          maxDate={new Date()}
          className={`w-100 ${errors.onBoardingDate ? "is-invalid" : ""}`}
        />
        {errors.onBoardingDate && (
          <div className="invalid-feedback">
            {errors.onBoardingDate.message}
          </div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="organizationSize" required>
          Organization Size
        </Label>

        <select
          id="organizationSize"
          className="form-select shadow-none border py-1 px-2"
          style={{ fontSize: "0.875rem" }} // Bootstrap's small text size
          {...register("organizationSize", { required: "Organization size is required" })}
        >
          {orgSize.map((org) => (
            <option key={org.val} value={org.val}>
              {org.name}
            </option>
          ))}
        </select>

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


      <div className="col-sm-6">
        <Label htmlFor="industryId" required>
          Industry
        </Label>
        <select
          id="industryId"
          className="form-select shadow-none border py-1 px-2 small"
          {...register("industryId")}
        >
          {industryLoading ? (
            <option value="">Loading...</option>
          ) : (
            data?.map((indu) => (
              <option key={indu.id} value={indu.id}>
                {indu.name}
              </option>
            ))
          )}
        </select>
        {errors.industryId && (
          <div className="danger-text">{errors.industryId.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <Label htmlFor="reference" required>Reference</Label>
        <select
          id="reference"
          className="form-select shadow-none border py-1 px-2 small"
          {...register("reference")}
        >
          {reference.map((org) => (
            <option key={org.val} value={org.val}>
              {org.name}
            </option>
          ))}
        </select>
        {errors.reference && (
          <div className="danger-text">{errors.reference.message}</div>
        )}
      </div>

      <div className="col-sm-6">
        <SelectMultiple
          name="serviceIds"
          label="Services"
          options={services?.data}
          isLoading={serviceLoading}
          labelKey="name"
          valueKey="id"
        />
        {errors.serviceIds && (
          <div className="danger-text">{errors.serviceIds.message}</div>
        )}
      </div>


      <div className="col-sm-12">
        <Label htmlFor="description">Description</Label>
        <textarea
          id="description"
          rows={3}
          className={`form-control form-control-sm `}
          {...register("description")}
        />
        {errors.description && (
          <div className="danger-text">{errors.description.message}</div>
        )}
      </div>

      <div className="col-sm-12">
        <Label htmlFor="logImage">Logo Image</Label>

        <LogoUpload
          preview={logoPreview}
          setPreview={setLogoPreview}
          fileName={logoName}
          setFileName={setLogoName}
        />
      </div>

      <div className="d-flex justify-content-end mt-3">
        <button
          type="button"
          className="btn btn-sm btn-secondary me-3"
          onClick={onPrev}
          disabled={isPending}
        >
          Back
        </button>
        <button
          type="button"
          className="btn btn-sm btn-primary"
          onClick={handleNext}
          disabled={isPending}
        >
          {isPending ? "Please Wait..." : "Submit and Next"}
        </button>
      </div>
    </div>
  );
};

export default OrganizationInfo;
