import { useEffect, useState } from "react";
import { useRoute, useNavigation } from "@react-navigation/native";

import { View } from "@/components/shared/Themed";
import styled from "@emotion/native";
import TimerContent from "@/components/useCases/timer/view/TimerContent";
import FinishContent from "@/components/useCases/timer/view/FinishContent";
import { TimerBgColor } from "@/components/useCases/timer/business/type";
import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake";
import { loadUserSettings } from "@/components/shared/business/AsyncStorage";
import BackgroundTimer from "react-native-background-timer";
import { useAudio } from "@/components/useCases/timer/business/useAudio";
import { useNotification } from "@/components/useCases/timer/business/useNotifications";
import { useTimerContext } from "@/app/store/TimerContext";

interface TimerProps {
  reps: number;
  restTime: number;
  workTime: number;
}

export default function Timer() {
  const navigation = useNavigation();
  const route = useRoute();
  const { timerState } = useTimerContext();

  const [currentRep, setCurrentRep] = useState<number>(0);
  const [timeLeft, setTimeLeft] = useState<number>(0);
  const [isWorkPhase, setIsWorkPhase] = useState<boolean>(true);
  const [isRunning, setIsRunning] = useState<boolean>(false);
  const [isFinish, setIsFinish] = useState<boolean>(false);
  const [isPreparationPhase, setIsPreparationPhase] = useState<boolean>(false);
  const [soundEnabled, setSoundEnabled] = useState<boolean>(true);
  const { playSound } = useAudio(
    require("../assets/audios/boxingBell.mp3"),
    soundEnabled,
  );
  const { updateNotification, cancelNotification } = useNotification(
    "123456789",
    {
      channelId: "timer-channel",
      channelName: "Timer Notification",
      channelDescription: "Notifications pour le timer",
    },
  );

  useEffect(() => {
    const init = async () => {
      try {
        const soundEnabledLocal = await loadUserSettings("soundEnabled");
        setSoundEnabled(Boolean(Number(soundEnabledLocal)));

        handleStart();
        await activateKeepAwakeAsync();
      } catch (error) {
        throw new Error("Error loading user settings");
      }
    };

    init();
  }, []);

  // when the user exits the screen, desactivate the keepAwake
  useEffect(() => {
    const unsubscribe = navigation.addListener("beforeRemove", (_) => {
      deactivateKeepAwake();
    });

    return unsubscribe;
  }, [navigation]);

  useEffect(() => {
    let timerId: number | null = null;

    if (isRunning && timeLeft > 0) {
      timerId = BackgroundTimer.setInterval(() => {
        const newTime = timeLeft - 1;
        setTimeLeft(newTime);

        let phaseText = "Repos";
        if (isPreparationPhase) {
          phaseText = "Préparation";
        } else if (isWorkPhase) {
          phaseText = "Travail";
        }

        updateNotification(
          "Timer en cours",
          `Phase: ${phaseText}, Temps restant: ${newTime}s`,
        );
      }, 1000);
    } else if (isRunning && timeLeft === 0) {
      if (isPreparationPhase) {
        startFirstRep();
      } else {
        nextRep();
      }
    }

    return () => {
      if (timerId !== null) {
        BackgroundTimer.clearInterval(timerId);
      }
    };
  }, [isRunning, timeLeft, isPreparationPhase]);

  const handleStart = () => {
    // Démarrer avec la phase de préparation si elle est configurée
    if (timerState.preparationTime > 0) {
      setIsPreparationPhase(true);
      setCurrentRep(0);
      setTimeLeft(timerState.preparationTime);
    } else {
      setIsPreparationPhase(false);
      setCurrentRep(1);
      setIsWorkPhase(true);
      setTimeLeft(timerState.workTime);
    }

    setIsRunning(true);
    setIsFinish(false);

    const phaseText = timerState.preparationTime > 0 ? "Préparation" : "Travail";
    updateNotification(
      "Timer en cours",
      `Phase: ${phaseText}, Temps restant: ${timeLeft}s`,
    );
  };

  const startFirstRep = () => {
    playSound();
    setIsPreparationPhase(false);
    setCurrentRep(1);
    setIsWorkPhase(true);
    setTimeLeft(timerState.workTime);
  };

  const handleReset = () => {
    setCurrentRep(0);
    setIsWorkPhase(true);
    setIsPreparationPhase(false);
    setTimeLeft(timerState.workTime);
    setIsRunning(false);
    setIsFinish(false);
    cancelNotification();
  };

  const nextRep = () => {
    if (currentRep < timerState.reps) {
      if (isWorkPhase) {
        playSound();
        setIsWorkPhase(false);
        setTimeLeft(timerState.restTime);
      } else {
        playSound();
        setIsWorkPhase(true);
        setTimeLeft(timerState.workTime);
        setCurrentRep((prevRep) => prevRep + 1);
      }
    } else {
      playSound();
      setIsFinish(true);
      setIsRunning(false);
      cancelNotification();
    }
  };

  const previousRep = () => {
    if (isWorkPhase) {
      if (currentRep > 1) {
        setIsWorkPhase(false);
        setTimeLeft(timerState.restTime);
        setCurrentRep((prevRep) => prevRep - 1);
      }
    } else {
      setIsWorkPhase(true);
      setTimeLeft(timerState.workTime);
    }
  };

  const handleContinue = () => {
    setIsRunning(true);
  };

  const handleStop = () => {
    setIsRunning(false);
  };

  const renderBgColor: () => TimerBgColor = () => {
    if (isFinish) return "black";
    if (isPreparationPhase) return "grey";
    if (isWorkPhase) return "pink";

    return "blue";
  };

  return (
    <Container bgColor={renderBgColor()}>
      {isFinish && <FinishContent handleStart={handleStart} handleReset={handleReset} />}

      {!isFinish && (
        <TimerContent
          isWorkPhase={isWorkPhase}
          isPreparationPhase={isPreparationPhase}
          timeLeft={timeLeft}
          reps={timerState.reps}
          bgColor={renderBgColor()}
          currentRep={currentRep}
          isRunning={isRunning}
          nextRep={nextRep}
          previousRep={previousRep}
          handleReset={handleReset}
          handleStop={handleStop}
          handleContinue={handleContinue}
        />
      )}
    </Container>
  );
}

const Container = styled(View)<{ bgColor: TimerBgColor }>(
  ({ theme, bgColor }) => ({
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: theme.colors.fixed[bgColor],
  }),
);
