package com.cpm.lorealbaautomation.leavemanagement;

import static com.prolificinteractive.materialcalendarview.CalendarDay.from;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;

import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.adapter.ApprovedLeaveAdapter;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.databinding.ActivityLeaveCalenderBinding;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.spans.DotSpan;

import org.threeten.bp.LocalDate;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cpm.lorealbaautomation.R;

public class LeaveCalenderViewActivity extends AppCompatActivity implements View.OnClickListener {
    List<CalendarDay> appliedLeaves = new ArrayList<>();
    List<CalendarDay> approvedLeaves = new ArrayList<>();
    List<CalendarDay> rejectLeaves = new ArrayList<>();
    String counter_Id, username, visit_date;
    private ActivityLeaveCalenderBinding binding = null;
    Lorealba_Database db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLeaveCalenderBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        db = new Lorealba_Database(this);
        db.open();
        setSupportActionBar(binding.toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        SharedPreferences preferences = PrefHelper.getPrefs(this);
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        if (!CommonFunctions.isTablet(this)) {
            binding.toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile);
        }
        setTitle("Leave/Govt. holidays Details - " + username);
        db.open();
        appliedLeaves = db.getLeaveDetails(username, "Pending");
        approvedLeaves = db.getLeaveDetails(username, "Accept");
        rejectLeaves = db.getLeaveDetails(username, "Reject");
        // Apply decorators for Applied Leaves, Approved Leaves, and Government Holidays
        if (CommonFunctions.isTablet(this)) {
            // Get display metrics
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            // Calculate height as 50% of screen height
            int height = (int) (displayMetrics.widthPixels * 0.9);
            // Set height for MaterialCalendarView
            ViewGroup.LayoutParams layoutParams = binding.contentCalenarView.calendarView.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = height;
            binding.contentCalenarView.calendarView.setLayoutParams(layoutParams);
            binding.contentCalenarView.calendarView.requestLayout();

            binding.contentCalenarView.calendarView.setDateTextAppearance(R.style.CalendarDateText);
            binding.contentCalenarView.calendarView.setWeekDayTextAppearance(R.style.CalendarWeekDayText);
        }
        binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.applied_leave), appliedLeaves, this)); // Applied Leaves - Red
        binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.approved_leave), approvedLeaves, this)); // Approved Leaves - Green
        binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.reject_leave), rejectLeaves, this));
        // Handle the click event on the calendar
        binding.contentCalenarView.calendarView.setOnDateChangedListener((widget, date, selected) -> {
            // Call the method to show leave info for the clicked date
            showLeaveInfo(date);
        });

        binding.btnCalendarView.setOnClickListener(this);
        binding.btnTabullarView.setOnClickListener(this);
        binding.btnGovHoliday.setOnClickListener(this);
        showLeaveInfo(today());
    }

    private CalendarDay today() {
        return from(LocalDate.now());
    }

    /**
     * Show leave info for a particular date
     */
    @SuppressLint("SetTextI18n")
    private void showLeaveInfo(CalendarDay date) {
        //test("CalendarDay", date.getMonth() + "-" + date.getDay() + "-" + date.getYear());
        TLeaveRequestDetail details = null;
        if (appliedLeaves.contains(date)) {
            db.open();
            details = db.getLeaveDetails(username, getString(R.string.pending), date.getYear(), date.getMonth(), date.getDay());
        } else if (approvedLeaves.contains(date)) {
            db.open();
            details = db.getLeaveDetails(username, getString(R.string.approved), date.getYear(), date.getMonth(), date.getDay());
        } else if (rejectLeaves.contains(date)) {
            db.open();
            details = db.getLeaveDetails(username, getString(R.string.reject), date.getYear(), date.getMonth(), date.getDay());
        }
        if (details != null) {
            binding.contentCalenarView.rlLeaveDetail.setVisibility(View.VISIBLE);
            String day = String.valueOf(date.getDay()).length() == 1 ? "0" + date.getDay() : String.valueOf(date.getDay());
            String month = String.valueOf(date.getMonth()).length() == 1 ? "0" + date.getMonth() : String.valueOf(date.getMonth());
            binding.contentCalenarView.tvLeaveDate.setText(CommonFunctions.formatDate(month + "/" + day + "/" + date.getYear()));
            binding.contentCalenarView.tvLeaveType.setText(details.getLeaveSubType() != null && !details.getLeaveSubType().isEmpty() ? details.getLeaveType() + " - " + details.getLeaveSubType() : details.getLeaveType());
            if (details.getReason() != null && !details.getReason().isEmpty()) {
                binding.contentCalenarView.tvLeaveReason.setVisibility(View.VISIBLE);
                binding.contentCalenarView.tvLeaveReason.setText(details.getReason());
            } else binding.contentCalenarView.tvLeaveReason.setVisibility(View.GONE);
        } else {
            binding.contentCalenarView.rlLeaveDetail.setVisibility(View.GONE);
        }
    }


    @SuppressLint({"NonConstantResourceId", "UseCompatLoadingForDrawables"})
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.btnCalendarView) {
            binding.btnCalendarView.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            binding.btnCalendarView.setTextColor(getResources().getColor(R.color.white));
            binding.btnTabullarView.setBackground(null);
            binding.btnTabullarView.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.btnGovHoliday.setBackground(null);
            binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.contentCalenarView.parent.setVisibility(View.VISIBLE);
            binding.tabullarView.parent.setVisibility(View.GONE);

        } else if (view.getId() == R.id.btnTabullarView) {
            binding.btnTabullarView.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            binding.btnTabullarView.setTextColor(getResources().getColor(R.color.white));
            binding.btnCalendarView.setBackground(null);
            binding.btnCalendarView.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.btnGovHoliday.setBackground(null);
            binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.contentCalenarView.parent.setVisibility(View.GONE);
            binding.tabullarView.parent.setVisibility(View.VISIBLE);
            CallRecycler("TabularView");

        } else if (view.getId() == R.id.btnGovHoliday) {
            binding.btnGovHoliday.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.white));
            binding.btnCalendarView.setBackground(null);
            binding.btnCalendarView.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.btnTabullarView.setBackground(null);
            binding.btnTabullarView.setTextColor(getResources().getColor(R.color.grayfor_login));
            binding.contentCalenarView.parent.setVisibility(View.GONE);
            binding.tabullarView.parent.setVisibility(View.VISIBLE);
            CallRecycler("GovtHolidays");

        }

    }

    // Custom decorator class to mark dates with colored dots
    public static class TextAndDotDecorator implements DayViewDecorator {
        private final int color;
        private final List<CalendarDay> dates;
        Context context;

        public TextAndDotDecorator(int color, List<CalendarDay> dates, Context context) {
            this.color = color;
            this.dates = dates;
            this.context = context;
        }

        @Override
        public boolean shouldDecorate(CalendarDay day) {
            return dates.contains(day); // Only decorate the dates in this list
        }

        @Override
        public void decorate(DayViewFacade view) {
            // Add a dot below the date
            view.addSpan(new DotSpan(10f, color)); // Draw a dot with the color
            if (CommonFunctions.isTablet(context))
                view.addSpan(new RelativeSizeSpan(1f)); // 1.5x the default size
            view.addSpan(new StyleSpan(Typeface.BOLD)); // Optional: Make text bold
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            this.finish();

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        this.finish();

    }

    @SuppressLint("SetTextI18n")
    private void CallRecycler(String type) {
        db.open();
        ArrayList<TLeaveRequestDetail> list = db.getHolidaysOrLeaves(username, type);
        if (type.equals("TabularView")) {
            binding.tabullarView.tvHeader.setText(getString(R.string.applied_approved_leave_details));
        } else {
            binding.tabullarView.tvHeader.setText(getString(R.string.gov_holidays) + " Details");
        }

        if (!list.isEmpty()) {
            binding.tabullarView.tvNodata.setVisibility(View.GONE);
            binding.tabullarView.leveRecyl.setVisibility(View.VISIBLE);
            binding.tabullarView.leveRecyl.setAdapter(new ApprovedLeaveAdapter(this, type, list));
            binding.tabullarView.leveRecyl.setLayoutManager(new LinearLayoutManager(this));
        } else {
            binding.tabullarView.tvNodata.setVisibility(View.VISIBLE);
            binding.tabullarView.leveRecyl.setVisibility(View.GONE);
        }
    }
}
