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

import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.auto.clicker.autoclicker.databinding.FragmentUISizeBinding;
import com.auto.clicker.autoclicker.service.ForegroundService;
import com.auto.clicker.autoclicker.view.FloatingViewManager;

public class UISizeFragment extends Fragment {
    private static final String TAG = "UISizeFragment";

    private FragmentUISizeBinding binding;
    private FloatingViewManager floatingViewManager;

    private static final int MIN_POINT_SIZE = 50;
    private static final int MAX_POINT_SIZE = 200;

    private static final int MIN_CONTROL_BAR_WIDTH_DP = 20;
    private static final int MAX_CONTROL_BAR_WIDTH_DP = 80;

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

        ForegroundService service = ForegroundService.getInstance();
        if (service != null) {
            floatingViewManager = service.getFloatingViewManager();
        }

        if (floatingViewManager != null) {
            setupPointSizeControl();
            setupControlBarSizeControl();
        } else {
            Toast.makeText(getContext(), "自动化服务未运行，UI大小设置功能不可用。", Toast.LENGTH_LONG).show();
            disableAllControlUI();
        }

        return binding.getRoot();
    }

    private void setupPointSizeControl() {
        binding.pointSeekbar.setMax(MAX_POINT_SIZE - MIN_POINT_SIZE);

        int currentPointSize = floatingViewManager.getTouchPointSize();

        currentPointSize = Math.max(MIN_POINT_SIZE, Math.min(MAX_POINT_SIZE, currentPointSize));
        binding.pointSeekbar.setProgress(currentPointSize - MIN_POINT_SIZE);

        updatePointSizeUI(currentPointSize);

        binding.pointSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int newSize = progress + MIN_POINT_SIZE;
                updatePointSizeUI(newSize);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int finalSize = seekBar.getProgress() + MIN_POINT_SIZE;
                floatingViewManager.setTouchPointSize(finalSize);
                Log.d(TAG, "触摸点大小设置为: " + finalSize + "px");
                Toast.makeText(getContext(), "触摸点大小已更新", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupControlBarSizeControl() {
        int minControlBarWidthPx = dpToPx(MIN_CONTROL_BAR_WIDTH_DP);
        int maxControlBarWidthPx = dpToPx(MAX_CONTROL_BAR_WIDTH_DP);

        binding.barSeekbar.setMax(maxControlBarWidthPx - minControlBarWidthPx);

        int currentBarWidthPx = floatingViewManager.getControlBarWidth();

        currentBarWidthPx = Math.max(minControlBarWidthPx, Math.min(maxControlBarWidthPx, currentBarWidthPx));
        binding.barSeekbar.setProgress(currentBarWidthPx - minControlBarWidthPx);

        binding.currentBarSizeText.setText(String.valueOf(pxToDp(currentBarWidthPx)) + "dp");

        binding.barSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int newWidthPx = progress + minControlBarWidthPx;
                binding.currentBarSizeText.setText(String.valueOf(pxToDp(newWidthPx)) + "dp");
                updateControlBarPreview(newWidthPx);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int finalWidthPx = seekBar.getProgress() + minControlBarWidthPx;
                floatingViewManager.setControlBarSize(finalWidthPx);
                Log.d(TAG, "控制栏大小设置为: " + pxToDp(finalWidthPx) + "dp (" + finalWidthPx + "px)");
                Toast.makeText(getContext(), "控制栏大小已更新", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int dpToPx(int dp) {
        if (getContext() == null) return dp;
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
    }

    private int pxToDp(int px) {
        if (getContext() == null) return px;
        return (int) (px / getContext().getResources().getDisplayMetrics().density);
    }

    private void updatePointSizeUI(int size) {
        binding.currentPointSizeText.setText(String.valueOf(size) + "px");

        ViewGroup.LayoutParams params = binding.ringPreview.getLayoutParams();
        params.width = size;
        params.height = size;
        binding.ringPreview.setLayoutParams(params);

        float textSize = (float) size / (MAX_POINT_SIZE / 19f);
        binding.ringText.setTextSize(textSize);
    }

    private void updateControlBarPreview(int width) {
        ViewGroup.LayoutParams params = binding.controlBar.getLayoutParams();
        params.width = width;

        params.height = (int) (width * (249f / 37f));
        binding.controlBar.setLayoutParams(params);
    }

    private void disableAllControlUI() {
        disablePointSizeControlUI();
        binding.barSeekbar.setEnabled(false);
        binding.barSizeContainer.setAlpha(0.5f);
    }

    private void disablePointSizeControlUI() {
        binding.pointSeekbar.setEnabled(false);
        binding.currentPointSizeText.setText("N/A");
        binding.ringPreview.setVisibility(View.GONE);
        binding.ringText.setVisibility(View.GONE);
        binding.pointSizeContainer.setAlpha(0.5f);
    }

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