package com.sultan.plantdatabse;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.airbnb.lottie.LottieAnimationView;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class WebViewActivity extends AppCompatActivity implements View.OnClickListener {

    private LottieAnimationView lottieAnimationView;
    private WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        Button scanAgainButton = findViewById(R.id.scanAgain);
        Button btnHome = findViewById(R.id.btnHome);
        lottieAnimationView = findViewById(R.id.lottieAnimationView);
        webView = findViewById(R.id.webView);

        // Retrieve the URL from the intent
        String url = getIntent().getStringExtra("url");

        // Load the URL in the WebView
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new CustomWebViewClient());

        // Set click listeners
        scanAgainButton.setOnClickListener(this);
        btnHome.setOnClickListener(this);

        // Load the URL in the WebView
        if (url != null) {
            webView.loadUrl(url);
        } else {
            // Handle invalid URL
            Toast.makeText(this, "Invalid URL", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private class CustomWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // Show the Lottie animation when the page starts loading
            lottieAnimationView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // Hide the Lottie animation when the page finishes loading
            lottieAnimationView.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            // Handle different types of errors
            if (error.getErrorCode() == -2) {
                // Network error (no internet connection)
                showCustomErrorPage("file:///android_asset/network_error.html");
            } else if (error.getErrorCode() == 404) {
                // 404 error (page not found)
                showCustomErrorPage("file:///android_asset/error_404.html");
            } else {
                // Other errors
                showCustomErrorPage("file:///android_asset/error_generic.html");
            }
        }

        private void showCustomErrorPage(String errorPageUrl) {
            // Load the custom error page in the WebView
            webView.loadUrl(errorPageUrl);
            // Hide the Lottie animation
            lottieAnimationView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onBackPressed() {
        WebView webView = findViewById(R.id.webView);
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.scanAgain) {
            initiateScan();
        } else if (v.getId() == R.id.btnHome) {
            navigateToMainActivity();
        }
        // Add conditions for other buttons if needed
    }

    private void initiateScan() {
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setPrompt(getString(R.string.scan_qr));
        intentIntegrator.setOrientationLocked(true);
        intentIntegrator.setCaptureActivity(CustomScannerActivity.class);
        intentIntegrator.initiateScan();
    }

    private void navigateToMainActivity() {
        Intent mainActivityIntent = new Intent(this, MainActivity.class);
        startActivity(mainActivityIntent);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        // Get the Vibrator service
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        // if the intentResult is null, toast a message as "cancelled"
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show();
                if (vibrator != null) {
                    vibrator.vibrate(100);
                }
            } else {
                // if the intentResult is not null, extract the dynamic part from the URL
                String scannedContent = intentResult.getContents();

                // Extract the dynamic part after "&" and display it in messageText
                String dynamicPart = extractDynamicPart(scannedContent);

                // Construct the full URL by appending the dynamic part to the base URL
                String fullUrl = "https://bhalumni.in/view/plant-database/entry/" + dynamicPart;

                // Open the WebView activity with the constructed URL
                openWebViewActivity(fullUrl);

                // Vibrate for 200 milliseconds on successful read
                if (vibrator != null) {
                    vibrator.vibrate(200);
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    // Custom method to extract the dynamic part after "&" in the URL
    private String extractDynamicPart(String url) {
        int index = url.lastIndexOf("&");
        if (index != -1 && index < url.length() - 1) {
            return url.substring(index + 1);
        }
        return "";
    }

    // Custom method to open WebView activity with the specified URL
    private void openWebViewActivity(String url) {
        Intent webViewIntent = new Intent(this, WebViewActivity.class);
        webViewIntent.putExtra("url", url);
        startActivity(webViewIntent);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}