package com.example.wadi;

import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.net.Uri;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ClothingActivity extends AppCompatActivity {

    TextView detailTime,detailIngredients,detailDesc,detailJob,frcount,fronlin,
            login_email,login_password,ttime2,ftime2;
    ImageView detailImage,share,calls,favor,saver,unfavor,oon,oof;

    Button login_button;
    private static final int REQUEST_CALL_PERMISSION = 1;

    private SQLiteHandler db;
    private SessionManager session;

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

        detailTime = findViewById(R.id.detailTime);
        detailIngredients = findViewById(R.id.detailIngredients);
        detailDesc = findViewById(R.id.detailDesc);
        detailImage = findViewById(R.id.detailImage);
        detailJob= findViewById(R.id.detailJob);
        share = findViewById(R.id.share);
        calls = findViewById(R.id.sharep);
        favor = findViewById(R.id.favor);
        saver = findViewById(R.id.saver);
        unfavor = findViewById(R.id.unfavor);
        frcount = findViewById(R.id.frcount);
        oon = findViewById(R.id.online);
        oof = findViewById(R.id.ofline);
        fronlin = findViewById(R.id.fronlin);
        login_email = findViewById(R.id.login_email);
        login_password = findViewById(R.id.login_password);
        login_button = findViewById(R.id.login_button);
        ttime2 = findViewById(R.id.ttime);
        ftime2 = findViewById(R.id.ftime);

        int itemId = getIntent().getIntExtra("title", -1);
        String title = getIntent().getStringExtra("title");
        String rate = getIntent().getStringExtra("rate");
        String price = getIntent().getStringExtra("price");
        String shortdesc = getIntent().getStringExtra("shortdesc");
        String imageUrl = getIntent().getStringExtra("imageUrl");
        String uid = getIntent().getStringExtra("uid");
        String loclong = getIntent().getStringExtra("lonr");
        String loclatd = getIntent().getStringExtra("latr");
        String stutes = getIntent().getStringExtra("stur");
        String ftime = getIntent().getStringExtra("ftime");
        String ttime = getIntent().getStringExtra("ttime");
        String liker = getIntent().getStringExtra("liker");
        String uaccount = getIntent().getStringExtra("uaccount");
        String saveme = getIntent().getStringExtra("saveme");
        String shareme = getIntent().getStringExtra("shareme");
        String callme = getIntent().getStringExtra("callme");
        String myphone = getIntent().getStringExtra("myphone");
        String myphoto = getIntent().getStringExtra("myphoto");
        String isok = getIntent().getStringExtra("isok");

        ttime2.setText("الي الساعه : " + ttime);
        ftime2.setText("من الساعه : " + ftime);

        detailTime.setText(title);
        detailIngredients.setText(price);
        detailDesc.setText(shortdesc);
        detailJob.setText(rate);
        frcount.setText(getIntent().getStringExtra("liker"));




        if ("1".equals(myphone)) {
            detailIngredients.setVisibility(View.VISIBLE);
        } else {
            detailIngredients.setVisibility(View.GONE);
        }

        if ("1".equals(saveme)) {
            saver.setEnabled(true);
        } else {
            saver.setEnabled(false);
        }


        if ("1".equals(shareme)) {
            share.setEnabled(true);
        } else {
            share.setEnabled(false);
        }

        if ("1".equals(callme)) {
            calls.setEnabled(true);
        } else {
            calls.setEnabled(false);
        }



        if ("1".equals(myphoto)) {
            Glide.with(this)
                    .load(imageUrl)
                    .into(detailImage);
        } else {
            Picasso.get().load(R.drawable.logo).into(detailImage);
        }




        if ("1".equals(stutes)) {

            oon.setVisibility(View.VISIBLE);
            oof.setVisibility(View.GONE);
            fronlin.setText("متاح");

        } else {

            oof.setVisibility(View.VISIBLE);
            oon.setVisibility(View.GONE);
            fronlin.setText("غير متاح");

        }

        db = new SQLiteHandler(getApplicationContext());

        // session manager
        session = new SessionManager(getApplicationContext());

        HashMap<String, String> user = db.getUserDetails();

        String send = user.get("uid");
        String recive = getIntent().getStringExtra("uid");

        calls.setOnClickListener(v -> makePhoneCall());

        share.setOnClickListener(v -> makeShare());

        makefavCall();

        favor.setOnClickListener(v -> {
            new SaveDataTask().execute(send, recive,"save");
            //Toast.makeText(getApplicationContext(), "تمت اضافة المستخدم الي المفضلة", Toast.LENGTH_SHORT).show();
            makerefreshCall();
        });

        unfavor.setOnClickListener(v -> {
            new SaveDataTask().execute(send, recive,"unsave");
            //Toast.makeText(getApplicationContext(), "تمت ازالة المستخدم الي المفضلة", Toast.LENGTH_SHORT).show();
            makerefreshCall();
        });


        if (checkSelfPermission(Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS}, 1);
        }

        saver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String displayName = getIntent().getStringExtra("title") + " - " + getIntent().getStringExtra("rate");;      // Replace with user input if needed
                String mobileNumber = getIntent().getStringExtra("price");;   // Replace with user input if needed
                saveContact(displayName, mobileNumber);
            }
        });


        login_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = login_email.getText().toString().trim();
                String password = login_password.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    makeservice(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                                    "من فضلك تاكد من بيانات الخدمة", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });


    }


    private void makePhoneCall() {
        String phone = getIntent().getStringExtra("price"); // Replace with your number
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL_PERMISSION);
        } else {
            startActivity(intent);
        }
    }


    private void makeShare() {
        String data = "الاسم: " + getIntent().getStringExtra("title") + "\nالهاتف: " + getIntent().getStringExtra("price")
                + "\nالمهنة: " + getIntent().getStringExtra("rate")
                + "\nالعنوان: " + getIntent().getStringExtra("shortdesc");

        String message = data;

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, message);

        startActivity(Intent.createChooser(shareIntent, "Share via"));
    }


    private void saveContact(String displayName, String mobileNumber) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .build());

        // Name
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
                .build());

        // Phone
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobileNumber)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build());

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            Toast.makeText(this,   "تم حفظ الاسم والرقم في جهات الاتصال باسم " + displayName, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "حدث خطاء اثناء حفظ البيانات", Toast.LENGTH_SHORT).show();
        }
    }


    private void makefavCall() {

        db = new SQLiteHandler(getApplicationContext());

        // session manager
        session = new SessionManager(getApplicationContext());

        HashMap<String, String> user = db.getUserDetails();

        String send = user.get("uid");
        String recive = getIntent().getStringExtra("uid");
        String url = AppConfig.URL_select_fav+"?param1="+ send+"&param2="+recive;

        RequestQueue queue = Volley.newRequestQueue(this);
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        for (int i = 0; i < response.length(); i++) {
                            JSONObject obj = response.getJSONObject(i);
                            String favo = obj.getString("fav");  // Example field

                            String value = favo;

                            if (value.equals("") || value.equals("0")) {

                                favor.setVisibility(View.VISIBLE);
                                unfavor.setVisibility(View.GONE);

                            } else {

                                unfavor.setVisibility(View.VISIBLE);
                                favor.setVisibility(View.GONE);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                },
                error -> {
                    error.printStackTrace();
                });

        queue.add(jsonArrayRequest);

    }


    private void makerefreshCall() {
        recreate();
    }


    private void makeservice(final String email, final String password) {

        String url = AppConfig.URL_insert_user_serv;

        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                response -> {
                    // Handle response
                    Toast.makeText(getApplicationContext(), "تم ارسال طلبك بنجاح", Toast.LENGTH_LONG).show();
                    login_email.setText("");
                    login_password.setText("");
                },
                error -> {
                    // Handle error
                    Toast.makeText(getApplicationContext(), "لايمكن تنفيذ طلبك حاليا", Toast.LENGTH_LONG).show();
                }
        ) {
            @Override
            protected Map<String, String> getParams() {

                HashMap<String, String> user = db.getUserDetails();

                String send = user.get("uid");
                String recive = getIntent().getStringExtra("uid");

                Map<String, String> params = new HashMap<>();
                params.put("user_send", send);
                params.put("user_recive", recive);
                params.put("service_type", email);
                params.put("service_number", password);
                return params;
            }
        };

// Add to request queue
        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(postRequest);


    }



}