package com.example.cuida.ui.schedule;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.example.cuida.data.AppDatabase;
import com.example.cuida.data.dao.AppointmentDao;
import com.example.cuida.data.model.Appointment;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScheduleViewModel extends AndroidViewModel {

    private final AppointmentDao appointmentDao;
    private final ExecutorService executorService;

    private final MutableLiveData<String> selectedDate = new MutableLiveData<>();
    private final MutableLiveData<String> selectedTime = new MutableLiveData<>();
    private final MutableLiveData<List<TimeSlot>> timeSlots = new MutableLiveData<>();
    private final MutableLiveData<Boolean> saveSuccess = new MutableLiveData<>();

    public ScheduleViewModel(@NonNull Application application) {
        super(application);
        AppDatabase db = AppDatabase.getDatabase(application);
        appointmentDao = db.appointmentDao();
        executorService = Executors.newSingleThreadExecutor();
        // Initial empty state or default date
    }

    public void setDate(int year, int month, int dayOfMonth) {
        // Format to dd/MM/yyyy
        String date = String.format("%02d/%02d/%04d", dayOfMonth, month + 1, year);
        selectedDate.setValue(date);
        loadTimeSlots(date);
    }

    public LiveData<String> getSelectedDate() {
        return selectedDate;
    }

    public void setTime(String time) {
        selectedTime.setValue(time);

        // Update selection state in the list
        List<TimeSlot> currentSlots = timeSlots.getValue();
        if (currentSlots != null) {
            for (TimeSlot slot : currentSlots) {
                slot.setSelected(slot.getTime().equals(time));
            }
            timeSlots.setValue(currentSlots);
        }
    }

    public LiveData<String> getSelectedTime() {
        return selectedTime;
    }

    public LiveData<List<TimeSlot>> getTimeSlots() {
        return timeSlots;
    }

    public LiveData<Boolean> getSaveSuccess() {
        return saveSuccess;
    }

    private void loadTimeSlots(String date) {
        executorService.execute(() -> {
            List<String> bookedTimes = appointmentDao.getBookedTimesForDate(date);
            List<TimeSlot> slots = generateTimeSlots(bookedTimes);
            timeSlots.postValue(slots);
        });
    }

    private List<TimeSlot> generateTimeSlots(List<String> bookedTimes) {
        List<TimeSlot> slots = new ArrayList<>();
        int startHour = 8;
        int endHour = 20;

        for (int hour = startHour; hour < endHour; hour++) {
            addSlot(slots, String.format("%02d:00", hour), bookedTimes);
            addSlot(slots, String.format("%02d:30", hour), bookedTimes);
        }
        return slots;
    }

    private void addSlot(List<TimeSlot> slots, String time, List<String> bookedTimes) {
        boolean isBooked = bookedTimes.contains(time);
        // If current selected time is now booked (e.g. concurrent), deselect it?
        // For simplicity, just check booked state.
        boolean isSelected = time.equals(selectedTime.getValue());
        slots.add(new TimeSlot(time, isBooked, isSelected));
    }

    public void confirmAppointment(String reason) {
        String date = selectedDate.getValue();
        String time = selectedTime.getValue();

        if (date != null && time != null) {
            Appointment appointment = new Appointment("Consulta Geral", date, time, reason, false);
            executorService.execute(() -> {
                appointmentDao.insert(appointment);
                saveSuccess.postValue(true);
            });
        }
    }
}
