import { useState } from "react";
import {
  useAssignOrgToTenant,
  useOrganizationBySPRID,
  useOrganizationModal,
} from "../../hooks/useOrganization";
import Label from "../common/Label";
import { useDebounce } from "../../utils/appUtils";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { spridSchema } from "./OrganizationSchema";
import { OrgCardSkeleton } from "./OrganizationSkeleton";

// Zod schema: only allow exactly 4 digits

const OrgPickerFromSPId = ({ title, placeholder }) => {
  const { onClose, startStep, flowType, onOpen, prevStep } =
    useOrganizationModal();

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm({
    resolver: zodResolver(spridSchema),
    defaultValues: { spridSearchText: "" },
  });

  const [SPRID, setSPRID] = useState("");

  const { data, isLoading, isError, error, refetch } =
    useOrganizationBySPRID(SPRID);

  const onSubmit = (formdata) => {
    setSPRID(formdata.spridSearchText);
  };

  const handleOrg = (orgId) => {};
  const SP = watch("spridSearchText");
  return (
    <div className="d-block">
      <form
        className="d-flex flex-row gap-6 text-start align-items-center"
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="d-flex flex-row align-items-center gap-2">
          <Label className="text-secondary">Search by SPRID</Label>
          <input
            type="search"
            {...register("spridSearchText")}
            className="form-control form-control-sm w-auto"
            placeholder="Enter SPRID"
            maxLength={4}
          />
        </div>

        <button type="submit" className="btn btn-sm btn-primary">
          <i className="bx bx-sm bx-search-alt-2"></i> Search
        </button>
      </form>
      <div className="text-start danger-text">
        {" "}
        {errors.spridSearchText && (
          <p className="text-danger small mt-1">
            {errors.spridSearchText.message}
          </p>
        )}
      </div>

      {/* ---- Organization list ---- */}
      {isLoading ? (
        <OrgCardSkeleton />
      ) : data && data?.data.length > 0 ? (
        <div className="py-2 text-tiny text-center">
          <div className="d-flex flex-column gap-2 border-0 bg-none">
            {data.data.map((org) => (
              <div className="d-flex flex-row gap-2 text-start text-black ">
                <div className="mt-1">
                  <img
                    src="/public/assets/img/orgLogo.png"
                    alt="logo"
                    width={50}
                    height={50}
                  />
                </div>
                <div className="d-flex flex-column p-0 m-0 cursor-pointer">
                  <span className="fs-6 fw-semibold">{org.name}</span>
                  <div className="d-flex gap-2">
                    <small
                      className=" fw-semibold text-uppercase"
                      style={{ letterSpacing: "1px" }}
                    >
                      SPRID :{" "}
                    </small>
                    <small className="fs-6">{org.sprid}</small>
                  </div>
                  <div className="d-flex flex-row gap-2">
                    <small className="text-small fw-semibold">Address:</small>
                    <div className="d-flex text-wrap">{org.address}</div>
                  </div>
                  <div className="m-0 p-0">
                    {" "}
                    <button
                      type="submit"
                      className="btn btn-sm btn-primary"
                      onClick={() => onOpen({ startStep: 3, orgData: org })}
                    >
                      Select
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : SPRID ? (
        <div className="py-3 text-center text-secondary">
          No organization found for "{SPRID}"
        </div>
      ) : null}
      <div className="py-12 text-center text-tiny text-black">
        <small className="d-block text-secondary">
          Do not have SPRID or could not find organization ?
        </small>
        <button
          type="button"
          className="btn btn-sm btn-primary mt-3"
          onClick={() => onOpen({ startStep: 4 })}
        >
          <i className="bx bx-plus-circle me-2"></i>
          Create New Organization
        </button>
      </div>

      {/* ---- Footer buttons ---- */}
      <div className={`d-flex   text-secondary mt-3`}>
        {flowType !== "default" && (
          <button
            type="button"
            className="btn btn-xs btn-outline-secondary"
            onClick={() => onOpen({ startStep: prevStep })}
          >
            <i className="bx bx-chevron-left"></i> Back
          </button>
        )}
      </div>
    </div>
  );
};

export default OrgPickerFromSPId;
