package Balaji.panel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

public class RemoteUpdater {

    // ═══════════════════════════════════════════════════
    // YOUR SERVER URL
    // ═══════════════════════════════════════════════════
    private static final String SERVER_URL =
            "https://balajimods.vipsite.in/test/api.php";

    public static void sync(
            Context context,
            String licenseKey,
            Activity activity
    ) {
        new Thread(() -> {
            try {
                // 1. FETCH UPDATE & USER SETTINGS
                String deviceID = android.provider.Settings.Secure.getString(
                        context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID
                );
                String deviceName = android.os.Build.MANUFACTURER
                        + " "
                        + android.os.Build.MODEL;

                URL url = new URL(
                        SERVER_URL
                                + "?key=" + licenseKey
                                + "&action=login"
                                + "&deviceID=" + deviceID
                                + "&device_name=" + Uri.encode(deviceName)
                );
                HttpURLConnection conn =
                        (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(10000);

                if (conn.getResponseCode() == 200) {
                    String body = readAll(conn.getInputStream());
                    JSONObject response = new JSONObject(body);

                    if (response.getBoolean("success")) {
                        JSONObject appUpdate =
                                response.getJSONObject("app_update");

                        int remoteVersion = appUpdate.getInt("version_code");
                        int forceUpdate = appUpdate.getInt("force_update");
                        String message = appUpdate.getString("message");
                        String link = appUpdate.getString("link");

                        // If Admin turned on Force Update
                        // AND provided a message and link
                        if (forceUpdate == 1
                                && !message.isEmpty()
                                && !link.isEmpty()) {
                            new Handler(Looper.getMainLooper()).post(() -> {
                                showFloatingUpdateBar(activity, message, link);
                            });
                        }
                    }
                }

                // 2. SYNC FILES (Existing Logic)
                URL manifestUrl = new URL(
                        SERVER_URL
                                + "?action=manifest"
                                + "&key=" + licenseKey
                );
                HttpURLConnection manifestConn =
                        (HttpURLConnection) manifestUrl.openConnection();
                manifestConn.setConnectTimeout(10000);

                if (manifestConn.getResponseCode() == 200) {
                    String body = readAll(manifestConn.getInputStream());
                    JSONObject json = new JSONObject(body);

                    File configFile = new File(
                            context.getFilesDir(),
                            "remote_config.json"
                    );
                    FileOutputStream fos = new FileOutputStream(configFile);
                    fos.write(
                            json.getJSONObject("ui_config")
                                    .toString()
                                    .getBytes()
                    );
                    fos.close();

                    File targetDir = new File(
                            context.getFilesDir(),
                            "remote_payloads"
                    );
                    if (!targetDir.exists()) {
                        targetDir.mkdirs();
                    }

                    JSONObject files = json.getJSONObject("files");
                    for (int i = 0; i < files.names().length(); i++) {
                        String filename = files.names().getString(i);
                        String remoteHash = files.getString(filename);
                        File localFile = new File(targetDir, filename);

                        if (!remoteHash.equals(getMD5(localFile))) {
                            String dlUrl = SERVER_URL
                                    + "?action=download"
                                    + "&file=" + filename
                                    + "&key=" + licenseKey;
                            downloadFile(dlUrl, localFile);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e("RemoteUpdater", "Sync failed", e);
            }
        }).start();
    }

    // ==========================================
    // READ A WHOLE RESPONSE INTO A STRING
    // ==========================================
    private static String readAll(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is)
        );
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }

    // ==========================================
    // FLOATING UPDATE BAR UI (Red Bar at Top)
    // ==========================================
    private static void showFloatingUpdateBar(
            Activity activity,
            String text,
            String url
    ) {
        if (activity == null || activity.isFinishing()) {
            return;
        }

        FrameLayout overlay = new FrameLayout(activity);
        FrameLayout.LayoutParams overlayParams =
                new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                );
        overlayParams.gravity = Gravity.TOP;
        // Margins to make it float nicely
        overlayParams.setMargins(30, 60, 30, 0);
        overlay.setLayoutParams(overlayParams);

        LinearLayout bar = new LinearLayout(activity);
        bar.setOrientation(LinearLayout.HORIZONTAL);
        bar.setGravity(Gravity.CENTER_VERTICAL);
        bar.setPadding(25, 25, 25, 25);

        GradientDrawable shape = new GradientDrawable(
                GradientDrawable.Orientation.LEFT_RIGHT,
                new int[]{
                        Color.parseColor("#FF0000"),
                        Color.parseColor("#B30000")
                }
        );
        // Rounded floating bar
        shape.setCornerRadius(25f);
        bar.setBackground(shape);

        TextView textView = new TextView(activity);
        textView.setText(text);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(16);
        textView.setPadding(10, 0, 10, 0);
        textView.setLayoutParams(
                new LinearLayout.LayoutParams(
                        0,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        1f
                )
        );
        bar.addView(textView);

        Button btn = new Button(activity);
        btn.setText("UPDATE");
        btn.setTextColor(Color.RED);
        btn.setBackgroundColor(Color.WHITE);
        btn.setOnClickListener(v -> {
            try {
                Intent intent = new Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse(url)
                );
                activity.startActivity(intent);
            } catch (Exception e) {
                Log.e("RemoteUpdater", "Cannot open URL", e);
            }
        });
        bar.addView(btn);

        overlay.addView(bar);
        ViewGroup root = (ViewGroup) activity
                .getWindow()
                .getDecorView()
                .findViewById(android.R.id.content);
        root.addView(overlay);
    }

    // ==========================================
    // DOWNLOAD A FILE TO DISK
    // ==========================================
    private static void downloadFile(
            String urlStr,
            File target
    ) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            FileOutputStream out = new FileOutputStream(target);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
        }
    }

    // ==========================================
    // MD5 OF A LOCAL FILE
    // ==========================================
    private static String getMD5(File file) {
        if (!file.exists()) {
            return "";
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                md.update(buffer, 0, len);
            }
            fis.close();

            StringBuilder sb = new StringBuilder();
            for (byte b : md.digest()) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }
}
