'use client'

import { useState, ChangeEvent } from 'react';
import styles from '@/app/styles/login.module.scss';

interface PhoneInputProps {
	phoneState: string | undefined;
}

export default function PhoneInput({ phoneState }: PhoneInputProps) {
	const [phone, setPhone] = useState(phoneState ? phoneState : '');

	const formatPhoneNumber = (value: string, isBackspace: boolean): string => {
		if (value === '+') {
			return value;
		}

		const digitsOnly = value.replace(/\D/g, '');

		if (!digitsOnly) {
			return '';
		}

		const limitedDigits = digitsOnly.slice(0, 11);
		const countryCode = 7;
		const phoneNumber = limitedDigits.startsWith('7')
			? limitedDigits.slice(1)
			: limitedDigits;

		let formatted = `+${countryCode}`;

		if (phoneNumber.length > 0) {
			formatted += ` (${phoneNumber.slice(0, 3)}`;
		}
		if (phoneNumber.length >= 3) {
			formatted += `) ${phoneNumber.slice(3, 6)}`;
		}
		if (phoneNumber.length >= 6) {
			formatted += `-${phoneNumber.slice(6, 8)}`;
		}
		if (phoneNumber.length >= 8) {
			formatted += `-${phoneNumber.slice(8, 10)}`;
		}

		if (isBackspace) {
			const lastChar = formatted[formatted.length - 1];
			const specialChars = ['-', '(', ')', ' '];

			if (specialChars.includes(lastChar)) {
				if (lastChar === ' ' && formatted[formatted.length - 2] === ')') {
					return formatted.slice(0, -2);
				}
				return formatted.slice(0, -1);
			}
		}

		return formatted;
	};

	const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
		const input = e.target.value;
		//@ts-ignore
		const isBackspace = e.nativeEvent.inputType === 'deleteContentBackward';
		const formatted = formatPhoneNumber(input, isBackspace);
		setPhone(formatted);
	};

	return (
		<input
			type="phone"
			id="phone"
			name="phone"
			className={`${styles['form-input']}`}
			placeholder="+7 (999) 123-45-67"
			value={phone}
			onChange={handleChange}
		/>
	)
}