'use client'

import { useState, ChangeEvent, useEffect } from 'react';
import { InputMask, format } from '@react-input/mask';
import styles from '@/app/styles/module/login.module.scss';

interface BankCardProps {
	bankCardState: string | undefined;
	validateHandler: (e: ChangeEvent<HTMLInputElement>) => void;
	clearCondition?: string | undefined | null;
	disabled: boolean;
	isValid: boolean | undefined;
}

export default function BankCardInput({ bankCardState, validateHandler, disabled, isValid }: BankCardProps) {
	const [bankCard, setBankCard] = useState<string | undefined>('');

	useEffect(() => {
		if (bankCardState) {
			if (disabled) {
				setBankCard(format(bankCardState.slice(-4), {
					mask: "**** **** **** ____",
					replacement: { _: /\d/ }
				}));
			} else {
				setBankCard(format(bankCardState, {
					mask: "____ ____ ____ ____",
					replacement: { _: /\d/ }
				}));
			}

		}
	}, [bankCardState, disabled]);

	return (
		<InputMask
			type="phone"
			id="bankCard"
			name="bankCard"
			className={`${styles['form-input']} ${isValid ? styles['valid-card'] : ''}`}
			mask="____ ____ ____ ____"
			replacement={{ _: /\d/ }}
			value={bankCard}
			disabled={disabled}
			onChange={(e) => {
				setBankCard(e.target.value);
				validateHandler(e);
			}}
			placeholder="1234 1234 1234 1234"
		/>
	)
}