import { useEffect, useState, type AnchorHTMLAttributes } from "react";
import { BiCheck, BiHide, BiShow, BiX } from "react-icons/bi";

export function Link(props: AnchorHTMLAttributes<HTMLAnchorElement>) {
  let link = props.href;
  if (!link) {
    link = props.children as string;
  }
  return (
    <a {...props} href={link}>
      {link}
    </a>
  );
}

export function Switch({
  checked,
  defaultChecked = false,
  onChange,
  disabled = false,
  ariaLabel,
  className = "",
  size = "md", // "sm" | "md" | "lg"
}: {
  checked?: boolean;
  defaultChecked?: boolean;
  onChange?: (newState: boolean) => void;
  disabled?: boolean;
  ariaLabel?: string;
  className?: string;
  size?: "sm" | "md" | "lg";
}) {
  const isControlled = checked !== undefined;
  const [internalChecked, setInternalChecked] = useState(defaultChecked);
  const current = isControlled ? checked : internalChecked;

  useEffect(() => {
    if (!isControlled) return;
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setInternalChecked(checked);
  }, [checked, isControlled]);

  const sizes = {
    sm: { track: "w-9 h-5", thumb: "w-3 h-3", translate: "translate-x-4" },
    md: { track: "w-11 h-6", thumb: "w-4 h-4", translate: "translate-x-5" },
    lg: { track: "w-14 h-8", thumb: "w-6 h-6", translate: "translate-x-6" },
  };
  const s = sizes[size] || sizes.md;

  const toggle = (next?: boolean) => {
    if (disabled) return;
    const newState = typeof next === "boolean" ? next : !current;
    if (!isControlled) setInternalChecked(newState);
    onChange?.(newState);
  };

  return (
    <button
      type="button"
      role="switch"
      aria-checked={current}
      aria-label={ariaLabel}
      disabled={disabled}
      tabIndex={disabled ? -1 : 0}
      onClick={() => toggle()}
      className={[
        "inline-flex items-center p-0 focus:outline-none",
        // focus-visible: shows ring only when focused by keyboard (better UX)
        "focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-0.5 focus-visible:ring-offset-transparent",
        disabled ? "opacity-60" : "cursor-pointer",
        current ? "bg-zinc-500" : "bg-gray-300/10",
        "rounded-full transition-colors duration-150",
        s.track,
        className,
      ].join(" ")}
    >
      <span
        className={[
          "relative block rounded-full bg-white shadow transform transition-transform ease-out duration-150",
          s.thumb,
          current ? s.translate : "",
          size === "sm" ? "m-1" : "m-1",
        ].join(" ")}
      />
    </button>
  );
}

export function LoadingSpinner({ size }: { size: number }) {
  return (
    <svg
      aria-hidden="true"
      className="animate-spin ease-out text-zinc-600 fill-white"
      viewBox="0 0 100 101"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      width={size}
      height={size}
    >
      <path
        d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
        fill="currentColor"
      />
      <path
        d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
        fill="currentFill"
      />
    </svg>
  );
}
export function DengiEditable({
  value,
  password = false,
  disWHidden = true,
  disabled = false,
  showLoading = true,
  minLenght = 1,
  placeholder,
  onSubmit = () => {},
  onInput = () => {},
}: {
  value?: string | false;
  password?: boolean;
  disWHidden?: boolean;
  disabled?: boolean;
  placeholder?: string;
  showLoading?: boolean;
  minLenght?: number;
  onSubmit?: (
    value: string | false | undefined,
    setIdle: (v: boolean) => void
  ) => void;
  onInput?: (
    value: string | false | undefined,
    setIdle: (v: boolean) => void
  ) => void;
}) {
  const [val, setVal] = useState(value);
  const [hid, setHid] = useState(true);
  const [idle, setIdle] = useState(false);
  useEffect(() => {
    setVal(value);
  }, [value]);
  return (
    <form
      action="#"
      className="flex rounded-xl overflow-hidden max-w-50 h-8 relative"
      onSubmit={(e) => {
        if (idle) return;
        e.preventDefault();
        onSubmit(val, setIdle);
      }}
    >
      {value !== false || !showLoading ? (
        <input
          type={hid && password ? "password" : "text"}
          value={val as any}
          placeholder={placeholder}
          minLength={minLenght}
          disabled={(disWHidden && password && hid) || disabled || idle}
          className={`bg-zinc-800 ${
            val === value && !password ? "rounded-r-xl" : ""
          } pl-2 rounded-l-xl w-full py-1 transition`}
          onInput={(e) => {
            const v = (e.target as HTMLInputElement).value;
            setVal(v);
            onInput(v, setIdle);
          }}
        />
      ) : (
        <span
          className={`w-full bg-zinc-800 py-1 flex items-center justify-center`}
        >
          <LoadingSpinner size={25} />
        </span>
      )}

      {password && (
        <button
          className={`bg-zinc-600 hover:bg-zinc-700 cursor-pointer transition-colors ${
            val === value ? "rounded-r-xl" : ""
          } p-1 text-2xl `}
          onContextMenu={(e) => {
            e.preventDefault();
            if ((disWHidden && password && hid) || disabled || idle) return;
            setVal(value);
          }}
          onClick={() => {
            setHid(!hid);
          }}
        >
          {hid ? <BiShow /> : <BiHide />}
        </button>
      )}

      {val !== value && (
        <button
          disabled={idle}
          className={`bg-zinc-600 disabled:bg-zinc-900 hover:bg-zinc-700
          p-1 text-2xl rounded-r-xl transition-colors not-disabled:cursor-pointer`}
          onContextMenu={(e) => {
            e.preventDefault();
            setVal(value);
          }}
        >
          {idle ? <LoadingSpinner size={24} /> : <BiCheck />}
        </button>
      )}
    </form>
  );
}
import trashcss from "./trash.module.css";
export function TextPreloader({ width = "5rem" }) {
  return (
    <span
      className={"h-4 block bg-zinc-900 overflow-hidden rounded-full w-(--w)"}
      style={{ "--w": width } as Record<string, string>}
    >
      <span
        className={
          "block h-10 -translate-y-3 w-3 bg-zinc-300 relative blur-[7px] " +
          trashcss.anim_preloader
        }
      ></span>
    </span>
  );
}

export function DengiButton({
  onClick,
  children,
  disabled = false,
  className = "",
}: {
  onClick?: () => void;
  children?: any;
  disabled?: boolean;
  className?: string;
}) {
  return (
    <span
      role="button"
      className={
        "flex bg-black items-center justify-center border p-1 gap-2 px-2 border-white " +
        (disabled
          ? "cursor-not-allowed text-zinc-700 border-zinc-900 md:hover:border-red-950/50 "
          : "not-disabled:cursor-pointer md:not-hover:border-zinc-700 md:not-hover:text-zinc-400 text-white ") +
        "rounded-xl transition-colors h-10 min-w-10 not-md:p-2 " +
        (className ? className : "")
      }
      aria-disabled={disabled}
      onClick={disabled ? undefined : onClick}
    >
      {children}
    </span>
  );
}

const defaultDialogContent = {
  message: "?",
  yesBtn: "da",
  noBtn: "net",
  bgDissmis: true,
  yesBlocked: false,
  yesIcon: <BiCheck />,
  noIcon: <BiX />,
  noBtnStyle: "",
  yesBtnStyle: "",
};
export function DengiYesOrNoDialog({
  content = defaultDialogContent,
  show = false,
  //@ts-ignore
  onAnswer,
}) {
  return (
    <>
        {show && (
          <div
            className="fixed z-99 bg-black/50 backdrop-blur-xl top-0 left-0 w-full h-full overflow-hidden flex items-center justify-center"
            onClick={(e) => {
              if (e.target === e.currentTarget && content.bgDissmis)
                onAnswer(false);
            }}
          >
            <div
              className="flex flex-col justify-center gap-4 p-4 border bg-black border-zinc-400 rounded-2xl"
            >
              <span>{content.message}</span>
              <div className="flex gap-2 justify-stretch">
                <DengiButton
                  className={content.yesBtnStyle + " w-full"}
                  onClick={() => onAnswer(true)}
                  disabled={content.yesBlocked}
                >
                  {content.yesIcon}
                  {content.yesBtn}
                </DengiButton>
                <DengiButton
                  className={content.noBtnStyle + " w-full"}
                  onClick={() => onAnswer(false)}
                >
                  {content.noIcon}
                  {content.noBtn}
                </DengiButton>
              </div>
            </div>
          </div>
        )}
    </>
  );
}
