package de.winniepat.citrus.gui;

import de.winniepat.citrus.cosmetics.capes.CapeHandler;
import de.winniepat.citrus.cosmetics.wings.ClientWingManager;
import de.winniepat.citrus.cosmetics.wings.WingType;
import de.winniepat.citrus.draggui.HudConfig;
import icyllis.modernui.core.Context;
import icyllis.modernui.fragment.Fragment;
import icyllis.modernui.graphics.Color;
import icyllis.modernui.graphics.drawable.ImageDrawable;
import icyllis.modernui.graphics.drawable.ShapeDrawable;
import icyllis.modernui.util.DataSet;
import icyllis.modernui.view.Gravity;
import icyllis.modernui.view.LayoutInflater;
import icyllis.modernui.view.View;
import icyllis.modernui.view.ViewGroup;
import icyllis.modernui.widget.*;
import net.minecraft.client.MinecraftClient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.UUID;

public class CosmeticsFragment extends Fragment {
    private LinearLayout contentArea;
    private TextView contentTitle;
    private Button capesButton;
    private Button wingsButton;
    private ShapeDrawable highlighted;

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable DataSet savedInstanceState) {
        Context context = requireContext();
        HudConfig.load();

        FrameLayout wrapper = new FrameLayout(context);
        wrapper.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        LinearLayout mainLayout = new LinearLayout(context);
        mainLayout.setOrientation(LinearLayout.HORIZONTAL);
        mainLayout.setGravity(Gravity.CENTER_HORIZONTAL);

        FrameLayout.LayoutParams mainParams = new FrameLayout.LayoutParams(
                dp(1200),
                dp(800)
        );
        mainParams.gravity = Gravity.CENTER;
        mainLayout.setLayoutParams(mainParams);

        mainLayout.setPadding(dp(10), dp(10), dp(10), dp(10));
        ShapeDrawable background = new ShapeDrawable();
        background.setShape(ShapeDrawable.RECTANGLE);
        background.setColor(0x50000000);
        background.setCornerRadius(20);
        background.setStroke(dp(10), 0x305d5b5f);
        background.setCornerRadii(dp(20), 20, dp(20), 20);
        mainLayout.setBackground(background);

        LinearLayout sidebar = new LinearLayout(context);
        sidebar.setOrientation(LinearLayout.VERTICAL);
        sidebar.setPadding(dp(16), dp(16), dp(16), dp(16));
        LinearLayout.LayoutParams sidebarParams = new LinearLayout.LayoutParams(
                dp(200),
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        sidebar.setLayoutParams(sidebarParams);

        ShapeDrawable sidebarBackground = new ShapeDrawable();
        sidebarBackground.setShape(ShapeDrawable.RECTANGLE);
        sidebarBackground.setColor(0x80000000);
        sidebarBackground.setCornerRadii(10,10,10,10);
        sidebar.setBackground(sidebarBackground);

        TextView sidebarTitle = new TextView(context);
        sidebarTitle.setText("Menu");
        sidebarTitle.setTextSize(20);
        sidebarTitle.setTextColor(Color.WHITE);
        sidebarTitle.setPadding(dp(8), dp(8), dp(8), dp(16));
        sidebar.addView(sidebarTitle);

        capesButton = new Button(context);
        capesButton.setText("Capes");
        capesButton.setTextColor(Color.WHITE);
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                dp(40)
        );
        buttonParams.setMargins(0, dp(4), 0, dp(4));
        capesButton.setLayoutParams(buttonParams);
        capesButton.setOnClickListener(v -> showCapesTab());
        sidebar.addView(capesButton);

        wingsButton = new Button(context);
        wingsButton.setText("Wings");
        wingsButton.setTextColor(Color.WHITE);
        wingsButton.setOnClickListener(v -> showWingsTab());
        LinearLayout.LayoutParams wingsParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                dp(40)
        );
        wingsParams.setMargins(0, dp(4), 0, dp(4));
        wingsButton.setLayoutParams(wingsParams);
        sidebar.addView(wingsButton);

        mainLayout.addView(sidebar);

        contentArea = new LinearLayout(context);
        contentArea.setOrientation(LinearLayout.VERTICAL);
        contentArea.setLayoutParams(new LinearLayout.LayoutParams(
                0,
                ViewGroup.LayoutParams.MATCH_PARENT,
                1.0f
        ));

        mainLayout.addView(contentArea);
        wrapper.addView(mainLayout);

        showCapesTab();

        return wrapper;
    }

    private void showCapesTab() {
        System.out.println("Switching to Capes tab");
        Context context = requireContext();
        contentArea.removeAllViews();

        updateButtonStates(true);

        LinearLayout root = new LinearLayout(context);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setPadding(dp(16), dp(16), dp(16), dp(16));

        contentTitle = new TextView(context);
        contentTitle.setText("Select a Cape");
        contentTitle.setTextSize(24);
        contentTitle.setTextColor(Color.WHITE);
        root.addView(contentTitle);

        List<String> capes = CapeHandler.getAvailableCapes();
        int perRow = 3;
        int i = 0;
        LinearLayout row = null;

        for (String cape : capes) {
            if (i % perRow == 0) {
                row = new LinearLayout(context);
                row.setGravity(Gravity.CENTER_HORIZONTAL);
                row.setOrientation(LinearLayout.HORIZONTAL);
                row.setLayoutParams(new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                ));
                root.addView(row);
            }

            LinearLayout buttonContainer = new LinearLayout(context);
            buttonContainer.setOrientation(LinearLayout.VERTICAL);
            buttonContainer.setGravity(Gravity.CENTER);

            ShapeDrawable customShape = new ShapeDrawable();
            customShape.setShape(ShapeDrawable.RECTANGLE);
            customShape.setStroke(dp(4), 0x605d5b5f);
            customShape.setCornerRadii(dp(10), 10, dp(10), 10);
            buttonContainer.setBackground(customShape);

            ImageView capeImage = new ImageView(context);
            ImageDrawable imageDrawable = new ImageDrawable("citrus", "capes/" + cape + ".png");
            capeImage.setImageDrawable(imageDrawable);

            LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(
                    dp(64),
                    dp(80)
            );
            imageParams.setMargins(dp(4), dp(4), dp(4), dp(4));
            capeImage.setLayoutParams(imageParams);
            buttonContainer.addView(capeImage);

            TextView nameView = new TextView(context);
            nameView.setText(cape);
            nameView.setTextColor(Color.WHITE);
            nameView.setTextSize(12);
            nameView.setGravity(Gravity.CENTER);
            nameView.setPadding(dp(4), dp(4), dp(4), dp(4));
            buttonContainer.addView(nameView);

            buttonContainer.setOnClickListener(v -> {
                CapeHandler.setLocalPlayerCape(cape, false);
                contentTitle.setText("Equipped: " + cape);
            });

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    dp(90),
                    dp(120)
            );
            params.setMargins(dp(4), dp(4), dp(4), dp(4));
            buttonContainer.setLayoutParams(params);

            row.addView(buttonContainer);
            i++;
        }

        ScrollView scrollView = new ScrollView(context);
        FrameLayout.LayoutParams scrollParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        scrollParams.gravity = Gravity.CENTER;
        scrollView.setLayoutParams(scrollParams);

        scrollView.addView(root);
        contentArea.addView(scrollView);
    }

    private void showWingsTab() {
        System.out.println("Switching to Wings tab");
        Context context = requireContext();
        contentArea.removeAllViews();

        updateButtonStates(false);

        MinecraftClient client = MinecraftClient.getInstance();
        if (client.player == null) {
            TextView error = new TextView(context);
            error.setText("You must be in-game!");
            error.setTextColor(0xFFFF5555);
            error.setGravity(Gravity.CENTER);
            contentArea.addView(error);
            return;
        }

        UUID playerUuid = client.player.getUuid();

        LinearLayout root = new LinearLayout(context);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setPadding(dp(16), dp(16), dp(16), dp(16));

        TextView title = new TextView(context);
        title.setText("Wings Configuration");
        title.setTextSize(24);
        title.setTextColor(Color.WHITE);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        titleParams.setMargins(0, 0, 0, dp(20));
        root.addView(title, titleParams);

        LinearLayout toggleRow = new LinearLayout(context);
        toggleRow.setOrientation(LinearLayout.HORIZONTAL);
        toggleRow.setGravity(Gravity.CENTER_VERTICAL);
        LinearLayout.LayoutParams toggleParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        toggleParams.setMargins(0, 0, 0, dp(20));

        TextView toggleLabel = new TextView(context);
        toggleLabel.setText("Show Wings:");
        toggleLabel.setTextSize(16);
        toggleLabel.setTextColor(Color.WHITE);

        Switch wingsToggle = new Switch(context);
        wingsToggle.setChecked(ClientWingManager.areWingsVisible(playerUuid));
        wingsToggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked != ClientWingManager.areWingsVisible(playerUuid)) {
                ClientWingManager.toggleWings(playerUuid);
            }
        });

        toggleRow.addView(toggleLabel);
        LinearLayout.LayoutParams switchParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        switchParams.setMargins(dp(10), 0, 0, 0);
        toggleRow.addView(wingsToggle, switchParams);
        root.addView(toggleRow, toggleParams);

        TextView typeLabel = new TextView(context);
        typeLabel.setText("Wing Type:");
        typeLabel.setTextSize(18);
        typeLabel.setTextColor(Color.WHITE);
        LinearLayout.LayoutParams typeLabelParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        typeLabelParams.setMargins(0, 0, 0, dp(10));
        root.addView(typeLabel, typeLabelParams);

        String currentWingType = ClientWingManager.getActiveWings(playerUuid);

        int perRow = 3;
        int i = 0;
        LinearLayout row = null;

        for (WingType wingType : WingType.getAvailableTypes()) {
            if (i % perRow == 0) {
                row = new LinearLayout(context);
                row.setGravity(Gravity.CENTER_HORIZONTAL);
                row.setOrientation(LinearLayout.HORIZONTAL);
                row.setLayoutParams(new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                ));
                root.addView(row);
            }

            LinearLayout wingContainer = new LinearLayout(context);
            wingContainer.setOrientation(LinearLayout.VERTICAL);
            wingContainer.setGravity(Gravity.CENTER);

            boolean isSelected = wingType.getId().equals(currentWingType);
            ShapeDrawable wingShape = new ShapeDrawable();
            wingShape.setShape(ShapeDrawable.RECTANGLE);
            wingShape.setStroke(dp(4), isSelected ? 0xFF55FF55 : 0x605d5b5f);
            wingShape.setCornerRadii(dp(10), 10, dp(10), 10);
            wingContainer.setBackground(wingShape);

            ImageView wingImage = new ImageView(context);
            ImageDrawable imageDrawable = new ImageDrawable("citrus", "textures/cosmetics/" + wingType.getId() + ".png");
            wingImage.setImageDrawable(imageDrawable);

            LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(
                    dp(64),
                    dp(80)
            );
            imageParams.setMargins(dp(4), dp(4), dp(4), dp(4));
            wingImage.setLayoutParams(imageParams);
            wingContainer.addView(wingImage);

            TextView wingName = new TextView(context);
            wingName.setText(formatWingTypeName(wingType.getId()));
            wingName.setTextColor(Color.WHITE);
            wingName.setTextSize(12);
            wingName.setGravity(Gravity.CENTER);
            wingName.setPadding(dp(4), dp(4), dp(4), dp(4));
            wingContainer.addView(wingName);

            wingContainer.setOnClickListener(v -> {
                ClientWingManager.setActiveWings(playerUuid, wingType.getId());
                showWingsTab();
            });

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    dp(90),
                    dp(120)
            );
            params.setMargins(dp(4), dp(4), dp(4), dp(4));
            wingContainer.setLayoutParams(params);

            row.addView(wingContainer);
            i++;
        }

        ScrollView scrollView = new ScrollView(context);
        scrollView.addView(root);
        contentArea.addView(scrollView);
    }

    private void updateButtonStates(boolean capesActive) {
        if (capesActive) {
            capesButton.setBackground(highlighted);
            wingsButton.setBackground(null);
        } else {
            capesButton.setBackground(null);
            wingsButton.setBackground(highlighted);
        }
    }

    private String formatWingTypeName(String id) {
        String[] parts = id.split("_");
        StringBuilder formatted = new StringBuilder();
        for (String part : parts) {
            if (formatted.length() > 0) {
                formatted.append(" ");
            }
            formatted.append(part.substring(0, 1).toUpperCase())
                    .append(part.substring(1).toLowerCase());
        }
        return formatted.toString();
    }

    private int dp(int value) {
        return (int) (value * getContext().getResources().getDisplayMetrics().density);
    }
}