package com.auto.clicker.autoclicker.ui.fragment.setting;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.databinding.FragmentActionBinding;

public class ActionFragment extends Fragment {
    private FragmentActionBinding binding;

    private static final int TYPE_INTERVAL = 0;
    private static final int TYPE_SWIPE_DURATION = 1;
    private static final int TYPE_REPEAT = 2;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentActionBinding.inflate(inflater, container, false);

        binding.intervalSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_INTERVAL));
        binding.unitSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_SWIPE_DURATION));

        setupRepeatMode();

        setupAdvancedMode();

        return binding.getRoot();
    }

    private void setupRepeatMode() {
        binding.repeatSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                binding.repeatInput.setVisibility(View.VISIBLE);
                binding.repeatSelectorContainer.setVisibility(View.VISIBLE);
                binding.repeatSelectedUnit.setText(getString(R.string.infinitely_unit));
                binding.etRepeatValue.setText("");
                binding.etRepeatValue.setEnabled(false);
                binding.etRepeatValue.setInputType(InputType.TYPE_NULL);
            } else {
                binding.repeatInput.setVisibility(View.GONE);
                binding.repeatSelectorContainer.setVisibility(View.GONE);
            }
        });

        if (!binding.repeatSwitch.isChecked()) {
            binding.repeatInput.setVisibility(View.GONE);
            binding.repeatSelectorContainer.setVisibility(View.GONE);
        } else {
            binding.repeatSelectedUnit.setText(getString(R.string.infinitely_unit));
            binding.etRepeatValue.setText("");
            binding.etRepeatValue.setEnabled(false);
            binding.etRepeatValue.setInputType(InputType.TYPE_NULL);
        }

        binding.repeatSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_REPEAT));
    }

    private void setupAdvancedMode() {
        binding.advancedSwitch.setChecked(true);

        binding.advancedSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                Toast.makeText(getContext(), "Anti-Detection mode is ON", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "Anti-Detection mode is OFF", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showUnitSelection(View anchorView, int type) {
        View popupView = getLayoutInflater().inflate(R.layout.dialog_unit_selection, null);
        PopupWindow popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(true);

        TextView tvMs = popupView.findViewById(R.id.tv_unit_ms);
        TextView tvSec = popupView.findViewById(R.id.tv_unit_sec);
        TextView tvMin = popupView.findViewById(R.id.tv_unit_min);
        TextView tvInfinitely = popupView.findViewById(R.id.tv_unit_infinitely);
        TextView tvDuration = popupView.findViewById(R.id.tv_unit_duration);
        TextView tvCycle = popupView.findViewById(R.id.tv_unit_cycle);


        switch (type) {
            case TYPE_INTERVAL:
                tvMs.setVisibility(View.VISIBLE);
                tvSec.setVisibility(View.VISIBLE);
                tvMin.setVisibility(View.VISIBLE);
                tvInfinitely.setVisibility(View.GONE);
                tvDuration.setVisibility(View.GONE);
                tvCycle.setVisibility(View.GONE);
                break;
            case TYPE_SWIPE_DURATION:
                tvMs.setVisibility(View.VISIBLE);
                tvSec.setVisibility(View.VISIBLE);
                tvMin.setVisibility(View.GONE);
                tvInfinitely.setVisibility(View.GONE);
                tvDuration.setVisibility(View.GONE);
                tvCycle.setVisibility(View.GONE);
                break;
            case TYPE_REPEAT:
                tvMs.setVisibility(View.GONE);
                tvSec.setVisibility(View.GONE);
                tvMin.setVisibility(View.GONE);
                tvInfinitely.setVisibility(View.VISIBLE);
                tvDuration.setVisibility(View.VISIBLE);
                tvCycle.setVisibility(View.VISIBLE);
                break;
        }

        if (type == TYPE_INTERVAL || type == TYPE_SWIPE_DURATION) {
            tvMs.setOnClickListener(v -> {
                String unitText = getString(R.string.milliseconds_unit);
                if (type == TYPE_INTERVAL) {
                    binding.intervalSelectedUnit.setText(unitText);
                    showInputValue("Interval", binding.etIntervalValue.getText().toString(), unitText);
                } else {
                    binding.tvSelectedUnit.setText(unitText);
                    showInputValue("Swipe Duration", binding.etDurationValue.getText().toString(), unitText);
                }
                popupWindow.dismiss();
            });

            tvSec.setOnClickListener(v -> {
                String unitText = getString(R.string.seconds_unit);
                if (type == TYPE_INTERVAL) {
                    binding.intervalSelectedUnit.setText(unitText);
                    showInputValue("Interval", binding.etIntervalValue.getText().toString(), unitText);
                } else {
                    binding.tvSelectedUnit.setText(unitText);
                    showInputValue("Swipe Duration", binding.etDurationValue.getText().toString(), unitText);
                }
                popupWindow.dismiss();
            });

            if (type == TYPE_INTERVAL) {
                tvMin.setOnClickListener(v -> {
                    String unitText = getString(R.string.minutes_unit);
                    binding.intervalSelectedUnit.setText(unitText);
                    popupWindow.dismiss();
                    showInputValue("Interval", binding.etIntervalValue.getText().toString(), unitText);
                });
            }
        }

        if (type == TYPE_REPEAT) {
            tvInfinitely.setOnClickListener(v -> {
                binding.repeatSelectedUnit.setText(getString(R.string.infinitely_unit));
                binding.etRepeatValue.setText("");
                binding.etRepeatValue.setEnabled(false);
                binding.etRepeatValue.setInputType(InputType.TYPE_NULL);
                popupWindow.dismiss();
                showInputValue("Repeat", binding.etRepeatValue.getText().toString(), getString(R.string.infinitely_unit));
            });

            tvDuration.setOnClickListener(v -> {
                binding.repeatSelectedUnit.setText(getString(R.string.duration_unit));
                binding.etRepeatValue.setText("");
                binding.etRepeatValue.setEnabled(true);
                binding.etRepeatValue.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME); // 设置为时间格式
                popupWindow.dismiss();
                showInputValue("Repeat", binding.etRepeatValue.getText().toString(), getString(R.string.duration_unit));
            });

            tvCycle.setOnClickListener(v -> {
                binding.repeatSelectedUnit.setText(getString(R.string.cycle_unit));
                binding.etRepeatValue.setText("");
                binding.etRepeatValue.setEnabled(true);
                binding.etRepeatValue.setInputType(InputType.TYPE_CLASS_NUMBER);
                popupWindow.dismiss();
                showInputValue("Repeat", binding.etRepeatValue.getText().toString(), getString(R.string.cycle_unit));
            });
        }

        popupWindow.showAsDropDown(anchorView);
    }

    private void showInputValue(String type, String value, String unit) {
        String message = type + " 值: " + (value.isEmpty() ? "未输入" : value) + ", 单位: " + unit;
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();

        if (type.equals("Interval")) {
            long intervalValue = value.isEmpty() ? 0 : Long.parseLong(value);
            // 根据 unit 进行单位转换或保存 Interval 值
            // 例如：if (unit.equals(getString(R.string.seconds_unit))) { ... }
        } else if (type.equals("Swipe Duration")) {
            long durationValue = value.isEmpty() ? 0 : Long.parseLong(value);
            // 根据 unit 进行单位转换或保存 Swipe Duration 值
        } else if (type.equals("Repeat")) {
            if (unit.equals(getString(R.string.infinitely_unit))) {
                // Repeat 为无限次，不需要处理输入值
            } else if (unit.equals(getString(R.string.duration_unit))) {
                // Repeat 为时长，处理时间格式的输入
                // 您需要在这里添加解析时间格式的逻辑
                String durationValue = value.isEmpty() ? "0" : value;
                // long parsedDuration = parseDurationString(durationValue); // 自定义方法解析时间
                Toast.makeText(getContext(), "Repeat Duration: " + durationValue, Toast.LENGTH_SHORT).show();
            } else if (unit.equals(getString(R.string.cycle_unit))) {
                // Repeat 为次数，处理整数输入
                int repeatCount = value.isEmpty() ? 0 : Integer.parseInt(value);
                Toast.makeText(getContext(), "Repeat Cycles: " + repeatCount, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}