package com.fluxup.app;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.animation.BounceInterpolator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import java.util.Calendar;
import java.util.Locale;
import java.util.ArrayList;
import java.util.List;


public class InicioFragment extends Fragment {

    private TextView tvTimer, tvProgressText;
    private FrameLayout timerBlock;
    private LinearLayout tasksContainer;
    private ProgressBar pbDailyTasks;
    private CountDownTimer countDownTimer;
    private LinearLayout progressPathContainer;
    private List<View> dayNodes = new ArrayList<>();
    private int currentDayIndex = 0; // 0-based index for the current day in the path

    private boolean isTimerRunning = false;
    private long timeLeftInMillis = 25 * 60 * 1000; // 25 minutos


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_inicio, container, false);

        tvTimer = view.findViewById(R.id.tvTimer);
        timerBlock = view.findViewById(R.id.timerBlock);
        tasksContainer = view.findViewById(R.id.tasksContainer);
        tvProgressText = view.findViewById(R.id.tvProgressText);
        pbDailyTasks = view.findViewById(R.id.pbDailyTasks);
        progressPathContainer = view.findViewById(R.id.progressPathContainer);

        initProgressPath();
        addSampleTasks();


        View btnStartFocus = view.findViewById(R.id.btnStartFocus);
        if (btnStartFocus != null) {
            btnStartFocus.setOnClickListener(v -> {
                if (!isTimerRunning) {
                    startTimer();
                    ((TextView)btnStartFocus).setText("Pausar Foco");
                } else {
                    pauseTimer();
                    ((TextView)btnStartFocus).setText("Continuar Foco");
                }
            });
        }

        view.findViewById(R.id.btnAddTasks).setOnClickListener(v -> {
            Toast.makeText(getContext(), "Adicionar tarefas: Implementação futura", Toast.LENGTH_SHORT).show();
        });

        View btnStreak = view.findViewById(R.id.btnStreak);
        if (btnStreak != null) {
            btnStreak.setOnClickListener(v -> {
                android.content.Intent intent = new android.content.Intent(getActivity(), StreakActivity.class);
                startActivity(intent);
            });
        }

        updateCountDownText();


        return view;
    }

    private void addSampleTasks() {
        if(getContext() == null) return;
        String[] sampleTasks = {
            "Estudar para intermédio",
            "Ler artigo técnico",
            "Fazer exercícios"
        };
        tasksContainer.removeAllViews();
        int completedCount = 0;
        
        for (int i = 0; i < sampleTasks.length; i++) {
            String taskLabel = sampleTasks[i];
            
            // Create a custom Duo-style card for each task
            androidx.cardview.widget.CardView card = new androidx.cardview.widget.CardView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(0, 0, 0, 16);
            card.setLayoutParams(params);
            card.setRadius(getResources().getDimension(R.dimen.radius_md));
            card.setCardElevation(2f);
            card.setContentPadding(16, 16, 16, 16);

            LinearLayout layout = new LinearLayout(getContext());
            layout.setOrientation(LinearLayout.HORIZONTAL);
            layout.setGravity(android.view.Gravity.CENTER_VERTICAL);

            CheckBox cb = new CheckBox(getContext());
            cb.setText(taskLabel);
            cb.setTextColor(getResources().getColor(R.color.text_primary));
            cb.setTextSize(16);
            
            // Simulated check for one task
            if (i == 0) {
                cb.setChecked(true);
                completedCount++;
                card.setCardBackgroundColor(getResources().getColor(R.color.background_light));
                cb.setTextColor(getResources().getColor(R.color.success_green));
            }

            layout.addView(cb);
            card.addView(layout);
            tasksContainer.addView(card);
            
            final int finalI = i;
            cb.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    cb.setTextColor(getResources().getColor(R.color.success_green));
                } else {
                    cb.setTextColor(getResources().getColor(R.color.text_primary));
                }
                updateProgress();
            });
        }
        
        updateProgress();
    }

    private void updateProgress() {
        int total = tasksContainer.getChildCount();
        int completed = 0;
        for (int i = 0; i < total; i++) {
            View child = tasksContainer.getChildAt(i);
            if (child instanceof androidx.cardview.widget.CardView) {
                CheckBox cb = (CheckBox) ((LinearLayout)((androidx.cardview.widget.CardView) child).getChildAt(0)).getChildAt(0);
                if (cb.isChecked()) completed++;
            }
        }
        
        if (tvProgressText != null) {
            tvProgressText.setText(completed + " de " + total + " concluídos");
        }
        if (pbDailyTasks != null && total > 0) {
            int progress = (completed * 100) / total;
            pbDailyTasks.setProgress(progress);
            updatePathProgress(progress);
        }
    }

    private void initProgressPath() {
        if (getContext() == null || progressPathContainer == null) return;
        
        progressPathContainer.removeAllViews();
        dayNodes.clear();
        
        String[] days = {"SEG", "TER", "QUA", "QUI", "SEX", "SÁB", "DOM"};
        String[] initials = {"S", "T", "Q", "Q", "S", "S", "D"};
        
        // Get current day of week (Calendar.MONDAY is 2, SUNDAY is 1)
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // Map to 0-6 (Mon-Sun)
        currentDayIndex = (dayOfWeek + 5) % 7;

        for (int i = 0; i < 7; i++) {
            View node = LayoutInflater.from(getContext()).inflate(R.layout.item_day_node, progressPathContainer, false);
            
            View topConnector = node.findViewById(R.id.topConnector);
            View bottomConnector = node.findViewById(R.id.bottomConnector);
            View nodeCircle = node.findViewById(R.id.nodeCircle);
            TextView nodeDayInitial = node.findViewById(R.id.nodeDayInitial);
            TextView nodeDayLabel = node.findViewById(R.id.nodeDayLabel);
            ProgressBar nodeProgress = node.findViewById(R.id.nodeProgress);

            nodeDayLabel.setText(days[i]);
            nodeDayInitial.setText(initials[i]);

            // Hide connectors at ends
            if (i == 0) topConnector.setVisibility(View.INVISIBLE);
            if (i == 6) bottomConnector.setVisibility(View.INVISIBLE);

            // Style based on state
            if (i < currentDayIndex) {
                // Past day - Assume completed for demo
                nodeCircle.setBackgroundResource(R.drawable.node_circle_bg);
                nodeCircle.getBackground().setTint(getResources().getColor(R.color.success_green));
                nodeDayInitial.setTextColor(getResources().getColor(R.color.white));
                nodeProgress.setVisibility(View.GONE);
            } else if (i == currentDayIndex) {
                // Today
                nodeCircle.setBackgroundResource(R.drawable.node_circle_bg);
                nodeCircle.getBackground().setTint(getResources().getColor(R.color.primary_purple));
                nodeDayInitial.setTextColor(getResources().getColor(R.color.white));
                nodeDayLabel.setTextColor(getResources().getColor(R.color.primary_purple));
                nodeProgress.setVisibility(View.VISIBLE);
            } else {
                // Future
                node.setAlpha(0.4f);
                nodeProgress.setVisibility(View.GONE);
            }

            dayNodes.add(node);
            progressPathContainer.addView(node);
        }
    }

    private void updatePathProgress(int progress) {
        if (currentDayIndex >= dayNodes.size()) return;
        
        View todayNode = dayNodes.get(currentDayIndex);
        ProgressBar nodeProgress = todayNode.findViewById(R.id.nodeProgress);
        View nodeCircle = todayNode.findViewById(R.id.nodeCircle);
        TextView nodeDayInitial = todayNode.findViewById(R.id.nodeDayInitial);

        if (nodeProgress != null) {
            nodeProgress.setProgress(progress);
        }

        if (progress == 100) {
            // Task completion animation
            nodeCircle.getBackground().setTint(getResources().getColor(R.color.success_green));
            triggerSuccessAnimation(todayNode);
        } else {
            nodeCircle.getBackground().setTint(getResources().getColor(R.color.primary_purple));
        }
    }

    private void triggerSuccessAnimation(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.2f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.2f, 1f);
        
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(500);
        animatorSet.setInterpolator(new BounceInterpolator());
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.start();
        
        Toast.makeText(getContext(), "Dia Completado! 🎉", Toast.LENGTH_SHORT).show();
    }


    private void startTimer() {
        countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                isTimerRunning = false;
                if(getContext() != null) Toast.makeText(getContext(), "Foco concluído! +50 XP", Toast.LENGTH_LONG).show();
            }
        }.start();

        isTimerRunning = true;
    }

    private void pauseTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        isTimerRunning = false;
    }


    private void updateCountDownText() {
        int minutes = (int) (timeLeftInMillis / 1000) / 60;
        int seconds = (int) (timeLeftInMillis / 1000) % 60;

        String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        if(tvTimer != null) tvTimer.setText(timeLeftFormatted);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        pauseTimer(); // Parar o timer se a view for destruída
    }
}
