package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogDonationBinding;
import com.unibuy.smartdevice.ui.recycler.RecyclerDonationListAdpter;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.ToastHandlerMain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class InvoiceDonationDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        INVOICE_SUCCESSFUL(4),
        INVOICE_FAILED(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        CHANGE_CHECKOUT(8),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<? extends DialogAbstract> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                if (MyApp.getInstance().getBuyList().size() <= 0) {
                    dialogCancel();
                } else {
                    Option option = optionMap.get(commandCode);

                    switch (option) {
                        case TOAST:
                            super.execute(context, commandCode, message);
                            break;
                        case COUNTDOWN_CANCEL:
                            cancelOnThreadCountdown();
                            break;
                        case SET_COUNTDOWN_TEXT:
                            setButtonCancelText(Integer.valueOf(message));
                            break;
                        case INVOICE_SUCCESSFUL:
                            break;
                        case INVOICE_FAILED:
                            break;
                        case CHANGE_DISPATCH:
                            changeDispatch();
                            break;
                        case CHANGE_BUY:
                            changeBuy();
                            break;
                        case CHANGE_CHECKOUT:
                            changeCheckout();
                            break;
                    }
                }
            }
        };
    }

    private DialogDonationBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private LinkedHashMap<String, String> donationMap;
    private List<String> organizationNames;
    private RecyclerDonationListAdpter donationAdapter;

    public InvoiceDonationDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogDonationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        donationMap = new LinkedHashMap<>();
        intiDonationMap();

        binding.buttonFinish.setOnClickListener(v -> changeOk());
        binding.buttonCancel.setOnClickListener(v -> changeBuy());
        
        // 隱藏切換 Tab 按鈕（由 InvoiceTypeDialog 統一管理入口）
        binding.buttonCustomerIdentifier.setVisibility(View.GONE);
        binding.buttonDonation.setVisibility(View.GONE);
        binding.buttonInputVehicle.setVisibility(View.GONE);

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

        setupDonationSpinner();
    }

    private void updateButtonState(com.google.android.material.button.MaterialButton selectedButton) {
        binding.buttonInputVehicle.setChecked(selectedButton.getId() == R.id.buttonInputVehicle);
        binding.buttonDonation.setChecked(selectedButton.getId() == R.id.buttonDonation);
        binding.buttonCustomerIdentifier.setChecked(selectedButton.getId() == R.id.buttonCustomerIdentifier);
    }

    public void intiDonationMap(){
        donationMap.put("社團法人嘉義市腦性麻痺協會", "2855669");
        donationMap.put("社團法人桃園市唐氏症家長協會", "520321");
        donationMap.put("社團法人中華民國自閉症總會", "1577");
        donationMap.put("社團法人臺北市蒲公英聽語協會", "71521");
        donationMap.put("社團法人桃園市失智症關懷協會", "8185");
        donationMap.put("財團法人台灣痲瘋救濟基金會", "1954");
        donationMap.put("社團法人中華小腦萎縮症病友協會", "9972");
        donationMap.put("社團法人高雄市唐氏症歡喜協會", "7717299");
        donationMap.put("社團法人屏東縣腦性麻痺服務協會", "115");
        donationMap.put("社團法人台南市智障者福利家長協進會", "2070");
        donationMap.put("財團法人台灣肯納自閉症基金會", "1018");
        donationMap.put("社團法人高雄市腦性麻痺服務協會", "29636");
        donationMap.put("社團法人高雄市自閉症協進會", "8585885");
        donationMap.put("社團法人臺灣自閉兒家庭關懷協會", "338518");
        donationMap.put("社團法人臺東縣自閉症協進會", "3685");
        donationMap.put("社團法人中華民國外傷性腦損傷照顧者關懷協會", "5841");
        donationMap.put("財團法人天主教靈醫會私立聖嘉民啟智中心", "57880");
        donationMap.put("社團法人新竹市智障福利協進會", "6684");
        donationMap.put("社團法人屏東縣自閉症協進會", "7351024");
        donationMap.put("社團法人台北市自閉症家長協會", "772");
        donationMap.put("社團法人屏東縣啟智協進會", "159");
        donationMap.put("社團法人花蓮縣自閉症協會", "8588");
        donationMap.put("澎湖縣私立財團法人天主教澎湖教區附設惠民啟智中心", "9261790");
        donationMap.put("財團法人新竹市私立天主教仁愛啟智中心", "227");
        donationMap.put("社團法人中華民國唐氏症關愛者協會", "88321");
        donationMap.put("財團法人天主教會台中教區附設南投縣私立復活啟智中心", "7717");
        donationMap.put("財團法人喜憨兒社會福利基金會", "88432");
        donationMap.put("社團法人花蓮縣智障福利協進會", "7756");
        donationMap.put("社團法人雲林縣啟智協會", "1311");
        donationMap.put("社團法人新竹縣智障福利協進會", "3170");
        donationMap.put("社團法人台南市腦性麻痺之友協會", "815");
        donationMap.put("社團法人台南市癲癇之友協會", "2350253");
        donationMap.put("新北市自閉症服務協進會", "7688");
        donationMap.put("社團法人台中市?智協進會", "450");
        donationMap.put("社團法人台中市自閉症教育協進會", "1127");
        donationMap.put("財團法人中華民國自閉症基金會", "402");
        donationMap.put("社團法人台灣流浪貓狗關懷協會", "9958");
        donationMap.put("社團法人台灣愛貓協會", "921314");
        donationMap.put("社團法人台灣幸褔狗流浪中途協會", "856203");
        donationMap.put("社團法人新北市流浪貓狗再生保護協會", "8866");
        donationMap.put("社團法人台灣流浪動物希望協會", "119");
        donationMap.put("社團法人高雄市幸福狗尾巴友善動物協會", "6848");
        donationMap.put("社團法人臺南市貓狗流浪終點協會", "5866");
        donationMap.put("社團法人台灣黑糖流浪動物救援協會", "958");
        donationMap.put("社團法人台灣動物輔助活動及治療協會", "916");
        donationMap.put("社團法人台灣友善動物協會", "9305");
        donationMap.put("社團法人中華民國反棄養寵物協會", "11289");
        donationMap.put("社團法人台灣流浪貓關懷協會", "71706");
        donationMap.put("社團法人台灣浪愛不流浪關懷動物協會", "9458");
        donationMap.put("台灣米樂流浪動物中途協會", "9925");
        donationMap.put("社團法人中華民國寵物友善協會", "52982");
        donationMap.put("社團法人台灣愛兔協會", "5822");
        donationMap.put("社團法人台灣拾貓生命教育創新協會", "880222");
        donationMap.put("社團法人台灣防止虐待動物協會", "1772");
        donationMap.put("社團法人好好善待動物協會", "6666666");
        donationMap.put("社團法人臺北市毛小孩幸福聯盟協會", "99891");
        donationMap.put("社團法人台南市流浪動物愛護協會", "17966");
        donationMap.put("中華民國流浪動物花園協會", "528");
        donationMap.put("台灣流浪兔保護協會", "17922");
        donationMap.put("社團法人台北市愛兔協會", "5222");
        donationMap.put("社團法人臺灣照顧生命協會", "589");
        donationMap.put("新竹市保護動物協會", "860713");
        donationMap.put("社團法人中華民國動物福利環保協進會", "529529");
        donationMap.put("財團法人中華民國兒童癌症基金會", "88888");
        donationMap.put("中華民國癌病腫瘤患者扶助協會", "6088");
        donationMap.put("財團法人臺灣癌症基金會", "1799");
    }

    private void setupDonationSpinner() {
        organizationNames = new ArrayList<>(donationMap.keySet());

        donationAdapter = new RecyclerDonationListAdpter(organizationNames, (name, position) -> {
            closeDialogCountdown.setCountdown(40);
        });
        
        binding.recyclerViewCharity.setAdapter(donationAdapter);

        // 隨機預選一個捐贈機構
        int randomIndex = new Random().nextInt(organizationNames.size());
        donationAdapter.setSelectedPosition(randomIndex);
        binding.recyclerViewCharity.scrollToPosition(randomIndex);
    }

    public void changeInvoiceBarcode() {
        closeDialogCountdown.shutdown();
        new InvoiceBarcodeDialog(getCtx(), getSrcHandlerMain()).show();
        cancel();
    }

    public void changeCustomerIdentifier() {
        closeDialogCountdown.shutdown();
        new InvoiceCustomerIdentifierDialog(getCtx(), getSrcHandlerMain()).show();
        cancel();
    }

    public void changeDispatch() {
        closeDialogCountdown.shutdown();
        DispatchDialog dispatchDialog = new DispatchDialog(getContext(), getSrcHandlerMain());
        dispatchDialog.show();
        cancel();
    }

    public void changeOk() {
        int selectedPosition = donationAdapter.getSelectedPosition();
        if (selectedPosition < 0) {
            Toast.makeText(getCtx(), getCtx().getString(R.string.select_charity), Toast.LENGTH_SHORT).show();
            return;
        }
        String selectedName = organizationNames.get(selectedPosition);
        String loveCode = donationMap.get(selectedName);
        MyApp.getInstance().getInvoiceData().setLoveCode(loveCode);
        MyApp.getInstance().getReportFlowInfoData().setInvoiceInfo("loveCode:" + loveCode);
        Toast.makeText(getCtx(), getCtx().getString(R.string.choose) + "：" + selectedName, Toast.LENGTH_SHORT).show();
        changeCheckout();
    }

    public void changeBuy() {
        closeDialogCountdown.shutdown();
        new InvoiceTypeDialog(getContext(), getSrcHandlerMain()).show();
        cancel();
    }

    public void changeCheckout() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        switch (flowType) {
            case 1:
                changeDialog(CheckoutNfcCardDialog.class);
                break;
            case 2:
                changeDialog(CheckoutNfcRechargeDialog.class);
                break;
            case 3:
                changeDialog(CheckoutEsunPayDialog.class);
                break;
            case 10:
                changeDialog(CheckoutNfcPhoneDialog.class);
                break;
            case 9:
                changeDialog(cashDialogClass());
                break;
            case 30:
                changeDialog(CheckoutTapPayDialog.class);
                break;
            case 70:
                changeDialog(CheckoutLinePayDialog.class);
                break;
        }
        cancel();
    }

    public void dialogCancel() {
        closeDialogCountdown.shutdown();
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void cancelOnThreadCountdown() {
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getCtx().getString(R.string.back_to_invoice) + "(" + countdown + ")");
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
            handlerMain.start(getClass().getSimpleName(), CashPayDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(getSrcCountdown()));
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }
}
