import { useEffect, useId, useState } from "react";
import {
  BiCheck,
  BiHide,
  BiLeftArrowAlt,
  BiRightArrowAlt,
  BiShow,
  BiX,
} from "react-icons/bi";
import { apiFormatDate, formatDate, getDateTags } from "./dengi.js";
import { AnimatePresence, motion, LayoutGroup } from "motion/react";
import trashcss from "./trash.module.css";
import { useWebHaptics } from "web-haptics/react";

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

  useEffect(() => {
    if (!isControlled) return;
    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) => {
    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 }) {
  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>
  );
}

function DatePickerButton({ next = false, date, setDate, pink = false }) {
  const { trigger } = useWebHaptics();
  return (
    <span
      className={`cursor-pointer ${
        !pink
          ? "lg:hover:*:fill-black lg:hover:bg-white"
          : "lg:hover:*:fill-white lg:hover:bg-pink-500"
      } transition *:transition-colors rounded-full`}
      onClick={() => {
        const d = new Date(date);
        d.setDate(d.getDate() + (next ? 1 : -1));
        setDate(d);
        trigger([{ duration: 15 }], { intensity: 1 });
      }}
    >
      {!next ? <BiLeftArrowAlt size={34} /> : <BiRightArrowAlt size={34} />}
    </span>
  );
}

export const DatePicker = (props) => {
  const dateTag = getDateTags(props.date);
  const { trigger } = useWebHaptics();
  const layoutGroupId = useId();

  return (
    <motion.div
      className={`flex items-center justify-between px-2 py-1 w-full bg-grain ${
        !props.pink ? "border-zinc-800/40" : "border-pink-500/20"
      } border rounded-2xl relative`}
    >
      <DatePickerButton
        date={props.date}
        setDate={props.setDate}
        pink={props.pink}
      />
      <LayoutGroup id={layoutGroupId}>
        <AnimatePresence mode="wait">
          <motion.span
            key={formatDate(props.date)}
            className={`cursor-pointer flex relative items-center z gap-1 justify-center w-[80%] lg:hover:text-black *:transition-colors transition-colors p-1 rounded-3xl text-zinc-300 ${
              !props.pink
                ? "lg:hover:bg-white lg:hover:*:text-black"
                : "lg:hover:bg-pink-500 lg:hover:*:text-white"
            } px-3 overflow-hidden `}
            variants={{
              a: { opacity: 0.3 },
              b: { opacity: 1 },
            }}
            initial="a"
            animate="b"
            transition={{ duration: 0.1 }}
            exit="a"
            layoutRoot
            layout="position"
            onClick={() => {
              if (apiFormatDate(props.date) != apiFormatDate(new Date()))
                trigger([
                  { duration: 10, intensity: 1 },
                  { delay: 40, duration: 20, intensity: 0.26 },
                  { delay: 90, duration: 20, intensity: 0.34 },
                ]);
              props.setDate(new Date());
            }}
          >
            <AnimatePresence>
              {props.indicator && (
                <motion.span
                  className={
                    "block min-w-2 min-h-2 rounded-full mx-1 transition-colors" +
                    (props.pink
                      ? " bg-pink-500 animate-pulse"
                      : " bg-zinc-300 animate-pulse")
                  }
                  variants={{
                    a: { opacity: 0 },
                    b: { opacity: 1 },
                  }}
                  initial="a"
                  animate="b"
                  exit="a"
                  layoutId="datepicker_indicator"
                  layout="position"
                />
              )}
            </AnimatePresence>
            <motion.span
              layoutId="datepicker_date"
              layout="position"
              className="font-semibold"
            >
              {formatDate(props.date)}
            </motion.span>
            {dateTag.length > 0 && (
              <>
                <motion.div
                  className="flex"
                  layoutId="datepicker_date_div"
                  layout="position"
                >
                  <span
                    className={`h-[1px] -rotate-50 ${
                      props.pink ? "bg-pink-400/50" : "bg-zinc-800"
                    } w-[20px] `}
                  />
                </motion.div>
                <motion.span
                  initial={{ opacity: 0 }}
                  transition={{ delay: 0.05 }}
                  layoutId="datepicker_date_if"
                  layout="position"
                  animate={{ opacity: 1 }}
                  className="text-zinc-600 italic"
                >
                  {dateTag}
                </motion.span>
              </>
            )}
          </motion.span>
        </AnimatePresence>
      </LayoutGroup>
      <DatePickerButton
        next
        date={props.date}
        setDate={props.setDate}
        pink={props.pink}
      />
    </motion.div>
  );
};

export function DengiButton({
  onClick,
  children,
  disabled = false,
  className = "",
}) {
  const { trigger } = useWebHaptics();

  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
          ? null
          : () => {
              onClick();
              trigger([
                {
                  duration: 40,
                  intensity: 0.8,
                },
              ]);
            }
      }
    >
      {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,
  onAnswer,
}) {
  const { trigger } = useWebHaptics();
  useEffect(() => {
    if (show) {
      trigger([
        {
          duration: 40,
          intensity: 0.8,
        },
        {
          delay: 15,
          duration: 170,
          intensity: 0.9,
        },
      ]);
    }
  }, [show]);
  return (
    <>
      <AnimatePresence>
        {show && (
          <motion.div
            variants={{ on: { opacity: 1 }, off: { opacity: 0 } }}
            initial="off"
            animate="on"
            exit="off"
            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);
                trigger([{ duration: 40, intensity: 1 }]);
              }
            }}
          >
            <motion.div
              variants={{
                on: { filter: "blur(0px)", scale: 1, y: 0, opacity: 1 },
                off: { filter: "blur(2px) ", scale: 0.7, y: 10, opacity: 0 },
              }}
              initial="off"
              animate="on"
              exit="off"
              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>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

export function DengiEditable({
  value,
  password = false,
  disWHidden = true,
  disabled = false,
  showLoading = true,
  minLenght = 1,
  // eslint-disable-next-line no-unused-vars
  onSubmit = ({ value, setIdle }) => {},
  // eslint-disable-next-line no-unused-vars
  onInput = ({ value, setIdle }) => {},
  pink = false,
}) {
  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({ value: val, setIdle });
      }}
    >
      {value !== false || !showLoading ? (
        <input
          type={hid && password ? "password" : "text"}
          value={val}
          minLength={minLenght}
          disabled={(disWHidden && password && hid) || disabled || idle}
          className={`${pink ? "bg-pink-700/20" : "bg-zinc-800"} ${
            val === value && !password ? "rounded-r-xl" : ""
          } pl-2 rounded-l-xl w-full py-1 transition`}
          onInput={(e) => {
            setVal(e.target.value);
            onInput({ value: e.target.value, setIdle });
          }}
        />
      ) : (
        <span
          className={`w-full ${
            pink ? "bg-pink-700/20" : "bg-zinc-800"
          } py-1 w-full flex items-center justify-center`}
        >
          <LoadingSpinner size={25} />
        </span>
      )}

      {password && (
        <button
          className={`${
            pink
              ? "bg-pink-400 hover:bg-pink-600"
              : "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>
      )}

      <AnimatePresence mode="popLayout">
        {val !== value && (
          <motion.button
            initial={{ opacity: 0, translateX: 10 }}
            animate={{ opacity: 1, translateX: 0 }}
            exit={{ opacity: 0 }}
            disabled={idle}
            className={`${
              pink
                ? "bg-pink-400 disabled:bg-pink-900/50 hover:bg-pink-600"
                : "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 />}
          </motion.button>
        )}
      </AnimatePresence>
    </form>
  );
}

export function TextPreloader({ width = "5rem" }) {
  return (
    <span
      className={"h-4 block bg-zinc-900 overflow-hidden rounded-full w-(--w)"}
      style={{ "--w": width }}
    >
      <span
        className={
          "block h-10 -translate-y-3 w-3 bg-zinc-300 relative blur-[7px] " +
          trashcss.anim_preloader
        }
      ></span>
    </span>
  );
}
