package com.amazon.ads.apidemo.fragments;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amazon.ads.apidemo.HttpStatusCode;
import com.amazon.ads.apidemo.R;
import com.amazon.ads.apidemo.utils.L;
import com.amazon.ads.ema.api.model.ApiResponse;
import com.amazon.ads.ema.api.model.TimezoneInfo;
import com.amazon.ads.ema.api.model.TimezoneListResult;

import java.util.ArrayList;
import java.util.List;

/**
 * Fragment for timezone configuration
 */
public class TimezoneFragment extends BaseFragment {
    private ScrollView mScrollView;
    private TextView mTvCurrentTimezone;
    private TextView mTvSelectedTimezoneInfo;
    private Spinner mSpinnerTimezone;
    private Button mBtnRefresh;
    private Button mBtnSetTimezone;

    private final List<TimezoneInfo> mTimezoneList = new ArrayList<>();
    private TimezoneInfo mSelectedTimezone;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_timezone, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initializeBase();

        // Initialize views
        mScrollView = view.findViewById(R.id.scroll_view_timezone);
        mTvCurrentTimezone = view.findViewById(R.id.tv_current_timezone);
        mTvSelectedTimezoneInfo = view.findViewById(R.id.tv_selected_timezone_info);
        mSpinnerTimezone = view.findViewById(R.id.spinner_timezone);
        mBtnRefresh = view.findViewById(R.id.btn_refresh_timezone);
        mBtnSetTimezone = view.findViewById(R.id.btn_set_timezone);

        // Set click listeners
        mBtnRefresh.setOnClickListener(v -> refreshTimezoneList());
        mBtnSetTimezone.setOnClickListener(v -> confirmAndSetTimezone());

        // Setup spinner selection listener
        mSpinnerTimezone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0 && position < mTimezoneList.size()) {
                    mSelectedTimezone = mTimezoneList.get(position);
                    updateSelectedTimezoneInfo();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                mSelectedTimezone = null;
                mTvSelectedTimezoneInfo.setText("");
            }
        });

        // Setup keyboard shortcuts
        setupKeyboardShortcuts(view);

        // Load timezone list on start
        refreshTimezoneList();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getView() != null) {
            getView().requestFocus();
        }
    }

    private void setupKeyboardShortcuts(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_UP:
                    if (mScrollView != null) {
                        mScrollView.smoothScrollBy(0, -200);
                        return true;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (mScrollView != null) {
                        mScrollView.smoothScrollBy(0, 200);
                        return true;
                    }
                    break;
                }
            }
            return false;
        });
    }

    /**
     * Public method to trigger refresh from MainActivity
     */
    public void triggerRefresh() {
        L.i("TimezoneFragment triggerRefresh() called from MainActivity");
        showButtonPressEffect(mBtnRefresh);
        refreshTimezoneList();
    }

    /**
     * Public method to trigger set timezone from MainActivity
     */
    public void triggerSetTimezone() {
        L.i("TimezoneFragment triggerSetTimezone() called from MainActivity");
        showButtonPressEffect(mBtnSetTimezone);
        confirmAndSetTimezone();
    }

    private void refreshTimezoneList() {
        if (!checkConnection())
            return;

        updateLastApiCall("Loading timezone list...");
        mTvCurrentTimezone.setText("Loading...");

        new Thread(() -> {
            TimezoneListResult result = mApiClient.getTimezoneList();
            mHandler.post(() -> {
                if (result.code == HttpStatusCode.OK_200) {
                    mTimezoneList.clear();
                    if (result.timezones != null) {
                        mTimezoneList.addAll(result.timezones);
                    }

                    // Update current timezone display
                    String currentTz = result.currentTimezoneId != null ? result.currentTimezoneId : "Unknown";
                    mTvCurrentTimezone.setText(currentTz);

                    // Update spinner
                    updateSpinner(result.currentTimezoneId);

                    updateLastApiCall("Loaded " + mTimezoneList.size() + " timezones");
                    Toast.makeText(getContext(), "Loaded " + mTimezoneList.size() + " timezones", Toast.LENGTH_SHORT).show();
                } else {
                    showError("Failed to load timezones", result.message);
                    mTvCurrentTimezone.setText("Error loading");
                }
            });
        }).start();
    }

    private void updateSpinner(String currentTimezoneId) {
        List<String> displayNames = new ArrayList<>();
        int currentIndex = 0;

        for (int i = 0; i < mTimezoneList.size(); i++) {
            TimezoneInfo tz = mTimezoneList.get(i);
            String displayText = tz.gmtOffset + " - " + tz.id;
            displayNames.add(displayText);

            if (tz.id.equals(currentTimezoneId)) {
                currentIndex = i;
            }
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, displayNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerTimezone.setAdapter(adapter);

        // Select current timezone
        if (!mTimezoneList.isEmpty()) {
            mSpinnerTimezone.setSelection(currentIndex);
        }
    }

    private void updateSelectedTimezoneInfo() {
        if (mSelectedTimezone != null) {
            String info = String.format("ID: %s\nDisplay Name: %s\nShort Name: %s\nOffset: %s", mSelectedTimezone.id, mSelectedTimezone.displayName,
                    mSelectedTimezone.shortName, mSelectedTimezone.gmtOffset);
            mTvSelectedTimezoneInfo.setText(info);
        }
    }

    private void confirmAndSetTimezone() {
        if (!checkConnection())
            return;

        if (mSelectedTimezone == null) {
            Toast.makeText(getContext(), "Please select a timezone first", Toast.LENGTH_SHORT).show();
            return;
        }

        String message = String.format("Set timezone to:\n\n%s\n(%s)\n\nThis will disable automatic timezone detection.", mSelectedTimezone.id,
                mSelectedTimezone.gmtOffset);

        new AlertDialog.Builder(getContext()).setTitle("Confirm Timezone Change").setMessage(message)
                .setPositiveButton("Set", (dialog, which) -> performSetTimezone()).setNegativeButton("Cancel", null).show();
    }

    private void performSetTimezone() {
        updateLastApiCall("Setting timezone to " + mSelectedTimezone.id + "...");

        final String timezoneId = mSelectedTimezone.id;

        new Thread(() -> {
            ApiResponse response = mApiClient.setTimezone(timezoneId);
            mHandler.post(() -> {
                if (response.code == HttpStatusCode.OK_200) {
                    Toast.makeText(getContext(), "Timezone set to " + timezoneId, Toast.LENGTH_LONG).show();
                    updateLastApiCall("Timezone set to " + timezoneId);
                    mTvCurrentTimezone.setText(timezoneId);
                } else {
                    showError("Failed to set timezone", response.message);
                }
            });
        }).start();
    }
}
