'use client';

import React, { useState } from 'react';
import { TextField, InputAdornment } from '@mui/material';

function formatPhoneNumber(phoneNumber: string): string {
    const digits = phoneNumber.replace(/\D/g, '');

    const truncated = digits.slice(0, 9);

    let formatted = '';

    if (truncated.length > 0) {
        formatted = truncated.slice(0, 2);
    }
    if (truncated.length > 2) {
        formatted += ' ' + truncated.slice(2, 5);
    }
    if (truncated.length > 5) {
        formatted += ' ' + truncated.slice(5, 7);
    }
    if (truncated.length > 7) {
        formatted += ' ' + truncated.slice(7, 9);
    }

    return formatted;
}

interface IProps {
    value?: string;
    setValue?: (value: string) => void;
    element_id?: string;
    isError: boolean;
}

export default function PhoneInput({ value, setValue, isError, element_id }: IProps) {
    const [phoneNumber, setPhoneNumber] = useState('');

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (setValue) setValue(formatPhoneNumber(e.target.value));
        else setPhoneNumber(formatPhoneNumber(e.target.value));
    };

    return (
        <TextField
            id={element_id}
            error={isError}
            label='Telefon raqam'
            value={value || phoneNumber}
            onChange={handleChange}
            fullWidth={true}
            placeholder='99 123 45 67'
            InputProps={{
                startAdornment: <InputAdornment position='start'>+998</InputAdornment>,
            }}
        />
    );
}
