package com.example.doitnow;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.NumberPicker;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.gridlayout.widget.GridLayout;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.example.doitnow.Adapter.kebiaoManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class ScheduleFragment extends Fragment {
    private View tv;
    private FrameLayout popupOverlay;
    private List<Lesson> kebiaodata = new ArrayList<>();
    private static List<TextView> alltext = new ArrayList<>();
    private kebiaoManager km;
    private Date currentWeekDate;

    public static Date firstSunday(Date startdate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startdate);
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            calendar.add(Calendar.DATE, -1);
        }
        return calendar.getTime();
    }

    public void changeweekclick(View view) {
        Button clickedButton = (Button) view;
        String buttonText = clickedButton.getText().toString();
        int weeknum = Integer.parseInt(buttonText.replaceAll("\\D+", ""));
        try {
            currentWeekDate = km.getweekdate(weeknum);
            displaylesson(currentWeekDate);
        } catch (ParseException ignored) {
        }
        popupOverlay.setVisibility(View.GONE);
    }

    public void setdatetext(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        SimpleDateFormat sdf = new SimpleDateFormat("M-d");
        for (int i = 115; i <= 121; i++) {
            int resID = getResources().getIdentifier("textView" + i, "id", requireContext().getPackageName());
            TextView textView = tv.findViewById(resID);
            if (textView != null) {
                textView.setText(sdf.format(calendar.getTime()));
                calendar.add(Calendar.DATE, 1);
            }
        }
    }

    public void displaylesson(Date date) {
        GridLayout gridLayout = tv.findViewById(R.id.timetable_container);
        gridLayout.removeAllViews();

        // 设置顶部周次按钮文本
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        String weekdate = sdf.format(date);
        int weeknum = km.getweeknum(weekdate);
        Button bt1 = tv.findViewById(R.id.button3);
        bt1.setText("第" + weeknum + "周");
        bt1.setVisibility(View.VISIBLE);
        setdatetext(date);

        // 读取课程
        try {
            kebiaodata = km.lessoninweek(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // ✅ 创建 13×7 的空白课表格子
        TextView[][] allCells = new TextView[13][7];
        for (int row = 0; row < 13; row++) {
            for (int col = 0; col < 7; col++) {
                TextView cell = new TextView(requireContext());
                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.rowSpec = GridLayout.spec(row, 1, 1f);
                params.columnSpec = GridLayout.spec(col, 1, 1);
                params.width = 0;
                params.height = 0;
                params.setMargins(6, 6, 6, 6);
                cell.setLayoutParams(params);
                cell.setBackgroundColor(Color.WHITE); // 默认空白
                cell.setGravity(Gravity.CENTER);
                cell.setText("");
                cell.setTextSize(12);
                gridLayout.addView(cell);
                allCells[row][col] = cell;
            }
        }

        // ✅ 添加课程信息
        for (Lesson lesson : kebiaodata) {
            int row = lesson.fromClass - 1;
            int rowSpan = lesson.endClass - lesson.fromClass + 1;
            int col = lesson.day;

            if (row >= 0 && row + rowSpan <= 13 && col >= 0 && col < 7) {
                TextView cell = allCells[row][col];
                String text = lesson.name;
                if (!Objects.equals(lesson.classroom, "null")) {
                    text += "\n" + lesson.classroom;
                }
                cell.setText(text);
                cell.setTextColor(Color.WHITE);
                cell.setBackgroundColor(Color.parseColor("#B388FF"));
                cell.setGravity(Gravity.CENTER);

                GridLayout.LayoutParams params = (GridLayout.LayoutParams) cell.getLayoutParams();
                params.rowSpec = GridLayout.spec(row, rowSpan, 1f);
                cell.setLayoutParams(params);

                // 隐藏合并下方单元格
                for (int i = 1; i < rowSpan; i++) {
                    allCells[row + i][col].setVisibility(View.GONE);
                }
            }
        }

        // ✅ 更新日期范围显示
        TextView dateSummary = tv.findViewById(R.id.date_summary);
        SimpleDateFormat rangeFormat = new SimpleDateFormat("yyyy/M/d");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        String start = rangeFormat.format(cal.getTime());
        cal.add(Calendar.DATE, 6);
        String end = rangeFormat.format(cal.getTime());
        dateSummary.setText(start + " ~ " + end);
    }



    public void showWeekPickerDialog(Button weekButton) {
        final NumberPicker picker = new NumberPicker(requireContext());
        picker.setMinValue(1);
        picker.setMaxValue(20);
        picker.setValue(km.getweeknum(new SimpleDateFormat("yyyy-M-d").format(currentWeekDate)));

        new AlertDialog.Builder(requireContext())
                .setTitle("选择周次")
                .setView(picker)
                .setPositiveButton("确定", (dialog, which) -> {
                    int week = picker.getValue();
                    try {
                        currentWeekDate = km.getweekdate(week);
                        displaylesson(currentWeekDate);
                    } catch (ParseException ignored) {}
                })
                .setNegativeButton("取消", null)
                .show();
    }

    public void weekclick(View view) {
        Button weekButton = view.findViewById(R.id.button3);
        showWeekPickerDialog(weekButton);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        km = new kebiaoManager(requireContext());

        return inflater.inflate(R.layout.fragment_schedule, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv = view;

        Button button = view.findViewById(R.id.button3);
        button.setOnClickListener(this::weekclick);

        popupOverlay = view.findViewById(R.id.frameLayout2);
        popupOverlay.setVisibility(View.GONE);
        popupOverlay.setOnClickListener(v -> popupOverlay.setVisibility(View.GONE));

        GridLayout gridLayout = view.findViewById(R.id.timetable_container);
        gridLayout.removeAllViews();
        alltext.clear();

        for (int row = 0; row < 13; row++) {
            for (int col = 0; col < 7; col++) {
                TextView cell = new TextView(requireContext());
                GridLayout.LayoutParams param = new GridLayout.LayoutParams();
                param.width = 0;
                param.height = 0;
                param.rowSpec = GridLayout.spec(row, 1f);
                param.columnSpec = GridLayout.spec(col, 1f);

                param.setMargins(6, 6, 6, 6);  // 上、左、下、右 各 6dp 间距

                cell.setLayoutParams(param);
                cell.setTextSize(12);
                cell.setText("");
                cell.setBackgroundColor(Color.WHITE);
                cell.setGravity(Gravity.CENTER);
                gridLayout.addView(cell);
                alltext.add(cell);
            }
        }

        for (int i = 9; i <= 24; i++) {
            int resID = getResources().getIdentifier("button" + i, "id", requireContext().getPackageName());
            Button bt = view.findViewById(resID);
            if (bt != null) {
                bt.setOnClickListener(this::changeweekclick);
            }
        }

        currentWeekDate = firstSunday(new Date());
        displaylesson(currentWeekDate);
    }

}
