import { useState, useEffect } from 'react';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
    useSetHeaderTitle,
    useSetHeaderType,
    useSetFooterMode,
    useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useExtensionAccountHolderSearchRequestMutation } from '@/entities/additional-service/api/account-holder-search/use-extension-account-holder-search-reqeust-mutation';
import { ExtensionAccountHolderSearchRequestParams } from '@/entities/additional-service/model/account-holder-search/types';
import { useStore } from '@/shared/model/store';
import { NumericFormat } from 'react-number-format';
import { snackBar } from '@/shared/lib';
import { useTranslation } from 'react-i18next';

export const AccountHolderSearchRequestPage = () => {
    const { navigate } = useNavigate();
    const { t } = useTranslation();
    const userMid = useStore.getState().UserStore.mid;
    const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
    const bankList = useStore.getState().CommonStore.bankList

    useSetHeaderTitle(t('additionalService.services.accountHolderSearch') + ' ' + t('common.request'));
    useSetHeaderType(HeaderType.LeftArrow);
    useSetFooterMode(false);
    useSetOnBack(() => {
        navigate(PATHS.additionalService.accountHolderSearch.list);
    });

    const { mutateAsync: accountHolderSearchRequest } = useExtensionAccountHolderSearchRequestMutation();

    const [formData, setFormData] = useState({
        mid: '',
        bankCode: '',
        accountNo: ''
    })

    // MID 초기값 설정
    useEffect(() => {
        if (!formData.mid && midOptionsWithoutGids.length > 0) {
            // userMid가 옵션에 있으면 userMid 사용, 없으면 첫 번째 옵션 사용
            const midItem = midOptionsWithoutGids.filter((value) => value.value === userMid);
            const initialMid = (midItem.length > 0) ? userMid : midOptionsWithoutGids[0]?.value || '';
            if (initialMid) {
                setFormData({ ...formData, mid: initialMid });
            }
        }
    }, [midOptionsWithoutGids, userMid]);

    const handleInputChange = (field: string, value: string) => {
        setFormData({ ...formData, [field]: value });
    };

    const onClickToRequest = () => {
        const reuqestParams: ExtensionAccountHolderSearchRequestParams = {
            mid: formData.mid,
            bankCode: formData.bankCode,
            accountNo: formData.accountNo
        }

        console.log("Account holder search request params: ", reuqestParams);

        accountHolderSearchRequest(reuqestParams)
            .then((response) => {
                if (response.status) {
                    console.log("Account holder search request success: ", response.status)
                    snackBar(t('common.requestSuccess'))
                    navigate(PATHS.additionalService.accountHolderSearch.list);
                } else {
                    const errorMessage = response.error?.message || t('common.requestFailed');
                    snackBar(`[${t('common.failed')}] ${errorMessage}`);
                }
            })
            .catch((error) => {
                console.error("Account holder search request failed: ", error)
                const errorMessage = error?.response?.data?.error?.message ||
                    error?.message ||
                    t('common.errorOccurred');
                snackBar(`[${t('common.failed')}] ${errorMessage}`);
            })
    };

    const isFormValid = () => {
        return (
            formData.mid.trim() !== '' &&
            formData.bankCode.trim() !== '' &&
            formData.accountNo.trim() !== ''
        )
    }

    return (
        <>
            <main>
                <div className="tab-content">
                    <div className="tab-pane sub active">
                        <div className="option-list">
                            <div className="billing-form gap-16">
                                <div className="billing-row">
                                    <div className="billing-label">{t('filter.merchant')}</div>
                                    <div className="billing-field">
                                        <select value={formData.mid} onChange={(e) => handleInputChange('mid', e.target.value)}>
                                            {
                                                midOptionsWithoutGids.map((value) => (
                                                    <option
                                                        key={value.value}
                                                        value={value.value}
                                                    >{value.name}</option>
                                                ))
                                            }
                                        </select>
                                    </div>
                                </div>

                                <div className="billing-row">
                                    <div className="billing-label">{t('transaction.fields.bank')}</div>
                                    <div className="billing-field">
                                        <select value={formData.bankCode} onChange={(e) => handleInputChange('bankCode', e.target.value)}>
                                            <option value="">{t('common.select')}</option>
                                            {
                                                bankList
                                                    .filter((bank) => bank.code1 !== '****')
                                                    .map((bank) => (
                                                        <option
                                                            key={bank.code1}
                                                            value={bank.code1}
                                                        >{bank.desc1}</option>
                                                    ))
                                            }
                                        </select>
                                    </div>
                                </div>

                                <div className="billing-row">
                                    <div className="billing-label">{t('transaction.fields.accountNo')}</div>
                                    <div className="billing-field">
                                        <NumericFormat
                                            value={formData.accountNo}
                                            valueIsNumericString
                                            allowNegative={false}
                                            decimalScale={0}
                                            isAllowed={(values) => {
                                                const { value } = values;
                                                return !value || value.length <= 14;
                                            }}
                                            onValueChange={(values) => {
                                                setFormData({ ...formData, accountNo: values.value });
                                            }}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="apply-row">
                            <button
                                className="btn-50 btn-blue flex-1"
                                disabled={!isFormValid()}
                                onClick={() => onClickToRequest()}
                            >{t('common.request')}</button>
                        </div>
                    </div>
                </div>
            </main>
        </>
    )
}