#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW
#define MAX_DEVICES 7

#define CLK_PIN   18
#define DATA_PIN  23
#define CS_PIN    15
#define START_BTN_PIN  32
#define STOP_BTN_PIN  33

MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

int prepareTime = 10;
int shootingTime = 20;
int warningTime = 10;
int TT = prepareTime + shootingTime;  // initial countdown value in seconds
const unsigned int interval = 1000;   // interval of 1 second
unsigned long previousMillis = 0;
volatile int state = 0;  // Made 'state' volatile for use in ISR

void execTimer() {
  while (state == 1) {
    unsigned long currentTime = millis();
    if (currentTime - previousMillis >= interval) {
      previousMillis = currentTime;

      if (TT >= 0) {
        if (TT > shootingTime) {
          P.print(TT - shootingTime);
          // displays prepare_time 
        } else if (TT >= warningTime) {
          P.print(TT);
          // displays shooting_time
        } else if (TT > 0) {
          P.print(TT);
          // displays warning time 
        } else if (TT == 0) {
          P.print("STOP");
          state = 0;  // Assuming you want to stop the countdown when TT reaches 0
        exit(0);
        }
        TT--;
      }
    }
  }
}

void IRAM_ATTR isr() {
  if (state == 1) {
    state = 0;
  }
}

void setup(void) {
  P.begin();
  Serial.begin(115200);
  pinMode(START_BTN_PIN, INPUT_PULLUP);
  pinMode(STOP_BTN_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(STOP_BTN_PIN), isr, FALLING);
}

void loop(void) {
  P.setTextAlignment(PA_CENTER);

  if (digitalRead(START_BTN_PIN) == LOW) {
    state = 1;  // now the state is in countdown
    execTimer();
  }
}