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';

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

    useSetHeaderTitle('계좌성명조회 신청');
    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("계좌성명 조회 조회신청 요청 파라미터 : ", reuqestParams);

        accountHolderSearchRequest(reuqestParams)
            .then((response) => {
                if (response.status) {
                    console.log("계좌성명 조회 조회 신청 성공 응답: ", response.status)
                    snackBar("계좌성명 조회 신청을 성공하였습니다.")
                    navigate(PATHS.additionalService.accountHolderSearch.list);
                } else {
                    const errorMessage = response.error?.message || '계좌성명 조회 신청이 실패하였습니다.';
                    snackBar(`[실패] ${errorMessage}`);
                }
            })
            .catch((error) => {
                console.error("계좌성명 조회 조회 신청 실패: ", error)
                const errorMessage = error?.response?.data?.error?.message ||
                    error?.message ||
                    '계좌성명 조회 신청 중 오류가 발생했습니다.';
                snackBar(`[실패] ${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">가맹점</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">은행</div>
                                    <div className="billing-field">
                                        <select value={formData.bankCode} onChange={(e) => handleInputChange('bankCode', e.target.value)}>
                                            <option value="">선택하세요</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">계좌번호</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()}
                            >신청</button>
                        </div>
                    </div>
                </div>
            </main>
        </>
    )
}