"use client";

import { PhoneInput as InternationalPhoneInput } from "react-international-phone";
import "react-international-phone/style.css";
import type { Control, FieldValues, Path } from "react-hook-form";
import { Controller } from "react-hook-form";

interface PhoneValue {
  dialCode: string;
  number: string;
}

interface PhoneInputProps<T extends FieldValues> {
  label?: string;
  name: Path<T>;
  control: Control<T>;
  error?: string;
  placeholder?: string;
}

export default function CustomPhoneInput<T extends FieldValues>({
  label,
  name,
  control,
  error,
  placeholder = "Enter Your Phone Number",
}: PhoneInputProps<T>) {
  return (
    <div className="flex flex-col gap-1">
      {label && (
        <label className="text-sm font-medium text-heading">{label}</label>
      )}

      <Controller
        name={name}
        control={control}
        render={({ field }) => (
          <InternationalPhoneInput
            defaultCountry="in"
            value={
              field.value ? `${field.value.dialCode}${field.value.number}` : ""
            }
            onChange={(phone, meta) => {
              field.onChange({
                dialCode: `+${meta.country.dialCode}`,
                number: phone.replace(`+${meta.country.dialCode}`, ""),
              });
            }}
            placeholder={placeholder}
            className="custom-phone-input"
            inputClassName={`
              custom-phone-number-input
              ${error ? "border-red-400" : ""}
            `}
          />
        )}
      />

      {error && <span className="text-xs text-danger">{error}</span>}
    </div>
  );
}
