package com.dinalamin.admin;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private WebView myWebView;
    private ProgressBar progressBar;
    private boolean isDesktopMode = false;
    private String mobileUserAgent;

    // ফাইল আপলোডের জন্য ভেরিয়েবল
    private ValueCallback<Uri[]> uploadMessage;
    private static final int FILE_CHOOSER_RESULT_CODE = 1;
    private static final int STORAGE_PERMISSION_CODE = 101;

    private static final String DESKTOP_USER_AGENT = 
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        // শুরুতে পারমিশন চেক
        checkStoragePermission();

        myWebView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);

        CookieManager.getInstance().setAcceptCookie(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(myWebView, true);

        WebSettings webSettings = myWebView.getSettings();
        mobileUserAgent = webSettings.getUserAgentString();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setSupportZoom(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        
        // ফাইল অ্যাক্সেস এনাবল করা
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);

        // --- WebChromeClient (ফাইল আপলোডের জন্য জরুরি) ---
        myWebView.setWebChromeClient(new WebChromeClient() {
            // Android 5.0+ এর জন্য ফাইল চুজ করা
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*"); // শুধু ছবি আপলোড করতে চাইলে
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), FILE_CHOOSER_RESULT_CODE);
                return true;
            }
        });

        // WebViewClient (লোডিং এবং পেজ নেভিগেশন)
        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);

                if (isDesktopMode) {
                    evaluateJavascriptForDesktop();
                }
            }
        });

        loadWebsite();
    }

    // --- পারমিশন চেক (Android 13 ফিক্স সহ) ---
    private void checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ (API 33) হলে READ_MEDIA_IMAGES চাইবে
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) 
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, 
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES}, STORAGE_PERMISSION_CODE);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6 থেকে 12 হলে পুরাতন পারমিশন চাইবে
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, 
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 
                        STORAGE_PERMISSION_CODE);
            }
        }
    }

    // --- ফাইল সিলেক্ট করার পর রেজাল্ট হ্যান্ডেল করা ---
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (uploadMessage == null) return;
            
            Uri[] results = null;
            if (resultCode == AppCompatActivity.RESULT_OK && data != null) {
                String dataString = data.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
            uploadMessage.onReceiveValue(results);
            uploadMessage = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permission Required for Uploads", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void evaluateJavascriptForDesktop() {
        String js = "javascript:(function() { " +
                "var meta = document.querySelector('meta[name=\"viewport\"]');" +
                "if (!meta) {" +
                "   meta = document.createElement('meta');" +
                "   meta.name = 'viewport';" +
                "   document.head.appendChild(meta);" +
                "}" +
                "meta.content = 'width=1280, initial-scale=0.1, user-scalable=yes';" +
                "})()";
        myWebView.evaluateJavascript(js, null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_desktop_mode) {
            isDesktopMode = !item.isChecked();
            item.setChecked(isDesktopMode);
            toggleMode(isDesktopMode);
            return true;
        } else if (id == R.id.action_refresh) {
            myWebView.reload();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void toggleMode(boolean enableDesktop) {
        WebSettings webSettings = myWebView.getSettings();
        if (enableDesktop) {
            webSettings.setUserAgentString(DESKTOP_USER_AGENT);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            Toast.makeText(this, "Desktop Mode ON", Toast.LENGTH_SHORT).show();
        } else {
            webSettings.setUserAgentString(mobileUserAgent);
            webSettings.setUseWideViewPort(false);
            webSettings.setLoadWithOverviewMode(false);
            Toast.makeText(this, "Mobile Mode ON", Toast.LENGTH_SHORT).show();
        }
        myWebView.reload();
    }

    private void loadWebsite() {
        myWebView.loadUrl("https://www.blogger.com");
    }

    @Override
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}