import InputMask from "@mona-health/react-input-mask";
import clsx from "clsx";
import { useState } from "react";
import ChevronDownIcon from "../icons/ChevronDownIcon";
import Button from "./Button";
import { useClickAway } from "@uidotdev/usehooks";

interface CountryCode {
  code: string;
  mask: string;
  flag: string;
}

const COUNTRY_CODES: CountryCode[] = [
  { code: "+974", mask: "9999 9999", flag: "🇶🇦" },
  { code: "+971", mask: "99 999 9999", flag: "🇦🇪" },
  { code: "+1", mask: "999 999 99 99", flag: "🇺🇸" },
  { code: "+44", mask: "9999 999999", flag: "🇬🇧" },
  { code: "+7", mask: "999 999 99 99", flag: "🇷🇺" },
];

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label: string;
  mask?: string;
  isError?: boolean;
  errorMessage?: string;
  isTextArea?: boolean;
  maxLength?: number;
}

function Input({
  label,
  isError,
  errorMessage,
  id,
  mask,
  isTextArea = false,
  maxLength,
  type,
  ...props
}: InputProps) {
  const [textValue, setTextValue] = useState("");
  const [selectedCountry, setSelectedCountry] = useState(0);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);

  const ref = useClickAway<HTMLDivElement>(() => setIsDropdownOpen(false));

  const isPhoneInput = type === "tel";
  const currentMask = isPhoneInput ? COUNTRY_CODES[selectedCountry].mask : mask;

  return (
    <div className="2xl:space-y-[0.833vw] space-y-3 w-full">
      <label htmlFor={id} className="text-m select-none">
        {label}
      </label>
      <div className="2xl:space-y-[0.556vw] space-y-2">
        {isTextArea ? (
          <div className="relative">
            <textarea
              id={id}
              value={textValue}
              onChange={(e) => setTextValue(e.target.value)}
              maxLength={maxLength}
              className={clsx(
                "bg-[#F0EDE6] text-m resize-none w-full 2xl:aspect-[672/178] md:aspect-[72/17] aspect-[328/133] transition-[box-shadow] outline-none placeholder:text-m placeholder:text-opacity-60 2xl:rounded-[0.833vw] rounded-xl 2xl:px-[1.389vw] 2xl:ring-[0.069vw] ring-transparent ring-1 px-5 2xl:py-[1.111vw] py-4 focus:ring-[#F47F52]",
                isError && "ring-[#E12E25]"
              )}
              {...(props as React.TextareaHTMLAttributes<HTMLTextAreaElement>)}
            />
            {maxLength && (
              <span className="absolute 2xl:bottom-[0.833vw] bottom-3 2xl:right-[1.111vw] right-4 caption font-medium opacity-60 pointer-events-none">
                {textValue.length}/{maxLength}
              </span>
            )}
          </div>
        ) : isPhoneInput ? (
          <div
            className={clsx(
              "flex items-center bg-[#F0EDE6] 2xl:rounded-[0.833vw] rounded-xl 2xl:ring-[0.069vw] ring-1 ring-transparent transition-[box-shadow] 2xl:py-[0.278vw] py-1 2xl:pr-[1.389vw] pr-5 2xl:pl-[0.278vw] pl-1 focus-within:ring-[#F47F52]",
              isError && "ring-[#E12E25]"
            )}
          >
            <div className="relative">
              <Button
                variant="primary"
                type="button"
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                className="flex items-center 2xl:gap-[0.417vw] gap-1.5 2xl:px-[0.833vw] px-3 2xl:py-[0.833vw] py-3 hover:bg-black hover:bg-opacity-5 2xl:rounded-[0.833vw] rounded-xl transition-colors"
              >
                {COUNTRY_CODES[selectedCountry].code}
                <div className="2xl:size-[1.111vw] size-4">
                  <ChevronDownIcon />
                </div>
              </Button>
              {isDropdownOpen && (
                <div
                  ref={ref}
                  className="absolute top-full left-0 mt-1 bg-[#F0EDE6] 2xl:rounded-[0.833vw] rounded-xl shadow-lg z-20 2xl:p-[0.278vw] p-1 2xl:space-y-[0.278vw] space-y-1 min-w-[120px]"
                >
                  {COUNTRY_CODES.map((country, index) => (
                    <Button
                      key={country.code}
                      variant="primary"
                      type="button"
                      onClick={() => {
                        setSelectedCountry(index);
                        setIsDropdownOpen(false);
                      }}
                      className={clsx(
                        "w-full flex items-center 2xl:gap-[0.556vw] gap-2 2xl:px-[0.833vw] px-3 2xl:py-[0.556vw] py-2 hover:bg-black hover:bg-opacity-5 transition-colors text-left button-m",
                        index === selectedCountry && "bg-black bg-opacity-5"
                      )}
                    >
                      <span>{country.flag}</span>
                      <span>{country.code}</span>
                    </Button>
                  ))}
                </div>
              )}
            </div>
            <InputMask
              mask={currentMask}
              {...props}
              id={id}
              alwaysShowMask
              placeholder={currentMask}
              className="bg-transparent text-m flex-1 placeholder:text-m outline-none placeholder:text-opacity-60"
            />
          </div>
        ) : (
          <InputMask mask={currentMask}>
            <input
              {...props}
              type={type}
              id={id}
              className={clsx(
                "bg-[#F0EDE6] text-m w-full placeholder:text-m outline-none transition-[box-shadow] placeholder:text-opacity-60 2xl:rounded-[0.833vw] rounded-xl 2xl:px-[1.389vw] 2xl:ring-[0.069vw] ring-1 px-5 2xl:py-[1.007vw] ring-transparent py-[14.5px] focus:!ring-[#F47F52]",
                isError && "ring-[#E12E25]"
              )}
            />
          </InputMask>
        )}
        {isError && (
          <p className="text-[#E12E25] text-[10px] font-medium leading-[110%]">
            {errorMessage}
          </p>
        )}
      </div>
    </div>
  );
}

export default Input;
