"use client";

import React, { useRef, useState } from "react";
import Link from "next/link";
import PhoneInput, { CountryData } from "react-phone-input-2";
import {
  Controller,
  useFormContext,
  FieldValues,
  RegisterOptions,
} from "react-hook-form";
import { Eye, EyeOff } from "lucide-react";
import "react-phone-input-2/lib/style.css";

interface Option {
  label: string;
  value: string | number;
}

interface InputProps extends React.HTMLAttributes<
  HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
> {
  label?: string;
  type?: string;
  placeholder?: string;
  name: string;
  required?: boolean;
  className?: string;
  validationRules?: RegisterOptions;
  toggle?: boolean;
  options?: Option[];
  rows?: number;
  labelClassName?: string;
  showTogglePassword?: boolean;
  setCountryCode?: any;
  disabled?: boolean;
}

const Input: React.FC<InputProps> = ({
  label,
  type = "text",
  placeholder,
  name,
  required = false,
  className = "",
  validationRules = {},
  toggle = false,
  options = [],
  rows = 3,
  setCountryCode,
  labelClassName = "text-neutrals800",
  showTogglePassword = true,
  ...props
}) => {
  const phoneInputRef = useRef<HTMLInputElement | null>(null);
  const {
    control,
    formState: { errors },
  } = useFormContext<FieldValues>();
  const baseInputClass =
    "w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:placeholder:text-neutrals500 dark:bg-background dark:border-darkborder dark:text-neutrals300 dark:focus:border-primary400 disabled:bg-neutrals100 disabled:text-gray-400 disabled:border-gray-200 disabled:cursor-not-allowed dark:disabled:bg-neutrals800";
  const [showPassword, setShowPassword] = useState(false);

  return (
    <div className={className}>
      {label && (
        <label
          htmlFor={name}
          className={`block text-sm font-medium mb-1 dark:text-neutrals400 ${labelClassName}`}
        >
          {label} {required && <span className="text-sm text-red-500">*</span>}
        </label>
      )}

      {type === "password" ? (
        <div className="relative overflow-hidden">
          <Controller
            name={name}
            control={control}
            rules={validationRules}
            defaultValue=""
            render={({ field }) => (
              <input
                {...field}
                type={showPassword ? "text" : "password"}
                value={field.value ?? ""}
                placeholder={placeholder}
                autoComplete="off"
                className={`${errors[name] ? "border-red-800" : "border-faqborder"}${className} ${baseInputClass}`}
                {...props}
              />
            )}
          />
          <button
            type="button"
            aria-label="Toggle password visibility"
            onClick={() => setShowPassword((prev) => !prev)}
            className="w-11 h-11 min-w-[44px] min-h-[44px] absolute -right-4 top-1/2 -translate-y-1/2 text-neutrals500 hover:text-neutrals700 dark:hover:text-neutrals200 rtl:left-2 rtl:right-auto"
          >
            {showPassword ? (
              <EyeOff className="w-5 h-5" />
            ) : (
              <Eye className="w-5 h-5" />
            )}
          </button>
        </div>
      ) : type === "country_code_phone" ? (
        <Controller
          name={name}
          control={control}
          rules={validationRules}
          defaultValue=""
          render={({ field, fieldState: { error } }) => (
            <>
              <PhoneInput
                country="sa"
                value={field.value}
                onChange={(value: string, country: CountryData) => {
                  field.onChange(value);
                  const countryCode = "+" + country.dialCode;
                  setCountryCode(countryCode);
                  setTimeout(() => {
                    phoneInputRef.current?.focus();
                  }, 0);
                }}
                enableSearch
                inputProps={{
                  name: "phone",
                  ref: phoneInputRef,
                }}
                containerClass="relative w-full rounded-lg bg-white text-neutrals400 leading-5 px-2 py-1 pe-9 country-number-drop border border-neutrals100 dark:bg-background dark:border dark:border-darkborder"
                inputClass={`!w-full !pl-10 !pr-4 !py-3 !text-base !text-gray-500 !rounded-lg !border-none focus:!outline-none ${
                  error ? "!border-red-500" : ""
                }`}
                buttonClass="!absolute !left-1 !top-[14px] !-translate-y-1/2 !bg-white !border-none !p-0 !m-0 !z-10"
                dropdownClass="!z-50 !bg-white !shadow-lg !rounded-md !text-sm max-h-60 overflow-y-auto"
                searchPlaceholder="Search..."
              />
            </>
          )}
        />
      ) : type === "textarea" ? (
        <Controller
          name={name}
          control={control}
          rules={validationRules}
          defaultValue=""
          render={({ field }) => (
            <textarea
              {...field}
              value={field.value ?? ""}
              placeholder={placeholder}
              className={`${errors[name] ? "border-red-800" : "border-faqborder"}${className} ${baseInputClass}`}
              rows={rows}
              {...props}
            />
          )}
        />
      ) : (
        <Controller
          name={name}
          control={control}
          rules={validationRules}
          defaultValue=""
          render={({ field }) => (
            <input
              {...field}
              type={type}
              value={field.value ?? ""}
              placeholder={placeholder}
              className={`${errors[name] ? "border-red-800 dark:border-red-500" : "border-faqborder"}${className} ${baseInputClass}`}
              {...props}
              autoComplete="off"
            />
          )}
        />
      )}
      {errors?.[name] && (
        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
          {(errors[name] as { message?: string })?.message}
        </p>
      )}
    </div>
  );
};

export default Input;
