package com.key.vibekeyboard.inputmethod.theme;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.util.Xml;

import androidx.core.content.ContextCompat;

import com.key.vibekeyboard.R;
import com.key.vibekeyboard.utils.FileUtils;
import com.key.vibekeyboard.utils.PathRepository;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

public class KeyboardThemeManager {

    private Drawable actionBackgroundDrawable;
    private Drawable normalBackgroundDrawable;
    private Drawable shiftIconDrawable;
    private Drawable shiftLockIconDrawable;
    private Drawable deleteIconDrawable;
    private Drawable returnIconDrawable;
    private Drawable backgroundDrawable;

    private int normalKeyColor;
    private int actionKeyColor;

    private static final String COLOR_NORMAL_KEY_TEXT = "key_text_color_normal";
    private static final String COLOR_ACTION_KEY_TEXT = "key_text_color_functional";

    private static final int DEFAULT_SHIFT_ICON = android.R.drawable.stat_sys_upload;
    private static final int DEFAULT_SHIFT_LOCK_ICON = android.R.drawable.stat_sys_upload;
    private static final int DEFAULT_DELETE_ICON = android.R.drawable.ic_input_delete;
    private static final int DEFAULT_RETURN_ICON = android.R.drawable.screen_background_light_transparent;
    private static final int DEFAULT_BACKGROUND_COLOR = R.color.black;

    public KeyboardThemeManager(Context context) {
        shiftIconDrawable = ContextCompat.getDrawable(context, DEFAULT_SHIFT_ICON);
        shiftLockIconDrawable = ContextCompat.getDrawable(context, DEFAULT_SHIFT_LOCK_ICON);
        deleteIconDrawable = ContextCompat.getDrawable(context, DEFAULT_DELETE_ICON);
        returnIconDrawable = ContextCompat.getDrawable(context, DEFAULT_RETURN_ICON);
        backgroundDrawable = ContextCompat.getDrawable(context, DEFAULT_BACKGROUND_COLOR);
        normalKeyColor = ContextCompat.getColor(context, R.color.white);
        actionKeyColor = normalKeyColor;
    }

    public Drawable getBackgroundDrawable() {
        return backgroundDrawable;
    }

    public Drawable getActionBackgroundDrawable() {
        return actionBackgroundDrawable;
    }

    public Drawable getNormalBackgroundDrawable() {
        return normalBackgroundDrawable;
    }

    public Drawable getDeleteIconDrawable() {
        return deleteIconDrawable;
    }

    public Drawable getShiftIconDrawable() {
        return shiftIconDrawable;
    }

    public Drawable getReturnIconDrawable() {
        return returnIconDrawable;
    }

    public Drawable getShiftLockIconDrawable() {
        return shiftLockIconDrawable;
    }

    public int getNormalKeyColor() {
        return normalKeyColor;
    }

    public int getActionKeyColor() {
        return actionKeyColor;
    }

    public void updateBackground(Context con) {
        String resDirPath = getWallpaperPath(con);
        if (!resDirPath.isEmpty()) {
            updateKeyColors(resDirPath);
            backgroundDrawable = getKeyboardBackground(con, resDirPath);
            returnIconDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.RETURN_ICON);
            normalBackgroundDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.NORMAL_KEY_BACKGROUND);
            actionBackgroundDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.ACTION_KEY_BACKGROUND);
            deleteIconDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.DELETE_ICON);
            shiftIconDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.SHIFT_ICON);
            shiftLockIconDrawable = getDrawableForKeyBackground(con, resDirPath, PathRepository.SHIFT_LOCK_ICON);
        }
    }

    private Drawable getKeyboardBackground(Context context, String resourceDirectoryPath) {
        String filePath = resourceDirectoryPath + "/drawable-xxhdpi-v4/keyboard_background.jpg";
        return loadDrawableFromFile(context, filePath);
    }

    private Drawable getDrawableForKeyBackground(Context context, String resourceDirectoryPath, String drawableName) {
        String drawablePath = "/drawable-xhdpi-v4/" + drawableName;
        return loadDrawableFromFile(context, resourceDirectoryPath + drawablePath);
    }

    private void updateKeyColors(String resDirPath) {
        String colorXmlPath = resDirPath + "/colors.xml";
        File colorXmlFile = new File(colorXmlPath);

        if (!colorXmlFile.exists()) {
            Log.w("updateKeyColors", "File not found: " + colorXmlPath);
            return;
        }

        try {
            XmlPullParser parser = Xml.newPullParser();
            String fileContent = FileUtils.readFileAsString(colorXmlFile);
            parser.setInput(new StringReader(fileContent));

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {
                    String tagName = parser.getName();
                    if ("color".equals(tagName) || "item".equals(tagName)) {
                        String attributeName = parser.getAttributeValue(null, "name");
                        String colorValue = parser.nextText();
                        if (colorValue != null && !colorValue.trim().isEmpty()) {
                            if (COLOR_NORMAL_KEY_TEXT.equals(attributeName)) {
                                normalKeyColor = Color.parseColor(colorValue);
                            } else if (COLOR_ACTION_KEY_TEXT.equals(attributeName)) {
                                actionKeyColor = Color.parseColor(colorValue);
                            }
                        } else {
                            Log.w("updateKeyColors", "Invalid color value for: " + attributeName);
                        }
                    }
                }
                eventType = parser.next();
            }
        } catch (XmlPullParserException | IOException e) {
            Log.e("updateKeyColors", "Error parsing colors XML", e);
        }
    }

    private Drawable loadDrawableFromFile(Context context, String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            return new BitmapDrawable(context.getResources(), BitmapFactory.decodeFile(filePath));
        }
        return null;
    }

    private String getWallpaperPath(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("keyboard_info", Context.MODE_PRIVATE);
        String path = prefs.getString("wallpaper_path", "");
        if (path.isEmpty()) {
            Log.w("KeyboardThemeManager", "Wallpaper path is empty.");
        }
        return path;
    }
}
