import React, { useState, useEffect, useCallback } from "react";
import {
  View,
  StyleSheet,
  TouchableOpacity,
  Image,
  SafeAreaView,
  ScrollView,
  ActivityIndicator,
  RefreshControl,
} from "react-native";
import { router } from "expo-router";
import { useFocusEffect } from "@react-navigation/native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { COLOR_SCALES } from "@/theme/colors";
import { title, paragraph } from "@/theme/typography";
import Text from "@/components/common/Text";
import Toast from "@/components/common/Toast";
import BottomNavigation from "@/components/common/BottomNavigation";
import Empty from "@/components/common/Empty";
import MemberRequiredBanner from "@/components/common/MemberRequiredBanner";
import { checkExerciseNotification } from "@/services/user";
import { Ionicons } from "@expo/vector-icons";
import useGuest from "@/hooks/useGuest";

const ExercisesScreen = () => {
  const { isGuest } = useGuest();
  const insets = useSafeAreaInsets();
  const [exerciseData, setExerciseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState(null);
  const [errorMessage, setErrorMessage] = useState(null);
  const [showToast, setShowToast] = useState(false);
  const [toastConfig, setToastConfig] = useState({
    type: "info",
    title: "",
    message: "",
  });
  const [timer, setTimer] = useState("00 : 00 : 00");

  const fetchExerciseData = async (isRefresh = false) => {
    if (isGuest) return;
    try {
      if (isRefresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }
      setError(null);
      setErrorMessage(null);
      const res = await checkExerciseNotification();
      console.log("Exercise check response:", JSON.stringify(res)?.substring(0, 300));
      if (res?.success && res?.data) {
        setExerciseData(res.data);
        if (!res.data.canStart && res.data.timeUntilNext) {
          updateTimer(res.data.timeUntilNext);
        }
      } else if (res?.success && res?.message) {
        // Başarılı ama veri yok, mesaj var (örn: "Egzersiz saati bulunamadı")
        setExerciseData(null);
        setErrorMessage(res.message);
      } else {
        setExerciseData(null);
      }
    } catch (e) {
      setError(e);
    } finally {
      if (isRefresh) {
        setRefreshing(false);
      } else {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    if (!isGuest) fetchExerciseData();
    else setLoading(false);
  }, [isGuest]);

  // Ekran odağa geldiğinde veriyi tazele (quiz dönüşü için)
  useFocusEffect(
    useCallback(() => {
      if (!isGuest) fetchExerciseData();
      return () => {};
    }, [isGuest])
  );

  const onRefresh = () => {
    fetchExerciseData(true);
  };

  useEffect(() => {
    let interval;
    if (exerciseData && !exerciseData.canStart && exerciseData.timeUntilNext) {
      interval = setInterval(() => {
        updateTimer(exerciseData.timeUntilNext);
      }, 1000);
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [exerciseData]);

  const updateTimer = (timeData) => {
    if (!timeData) return;
    const days = timeData.days ?? 0;
    const hours = timeData.hours ?? 0;
    const minutes = timeData.minutes ?? 0;
    const formattedTimer = `${days.toString().padStart(2, '0')} : ${hours.toString().padStart(2, '0')} : ${minutes.toString().padStart(2, '0')}`;
    setTimer(formattedTimer);
  };

  const handleBack = () => {
    router.back();
  };

  const showToastMessage = (type, title, message) => {
    setToastConfig({ type, title, message });
    setShowToast(true);
  };

  const handleStartExercise = () => {
    if (!exerciseData?.canStart) {
      showToastMessage("warning", "Uyarı", exerciseData?.reason || "Egzersiz henüz başlatılamaz");
      return;
    }
    showToastMessage(
      "info",
      "Bilgi",
      "Egzersize yönlendiriliyorsunuz..."
    );
    setTimeout(() => {
      router.push("/(tabs)/exercises/quiz?notificationId=" + exerciseData?.notification?.id);
    }, 1000);
  };

  const handleTodayButton = () => {
    if (!exerciseData?.canStart) {
      showToastMessage("warning", "Uyarı", exerciseData?.reason || "Egzersiz henüz başlatılamaz");
      return;
    }
    showToastMessage("success", "Başarılı", "Bugünkü egzersiz başlatılıyor!");
    setTimeout(() => {
      router.push("/(tabs)/exercises/quiz");
    }, 1000);
  };

  // Misafir: "Egzersizlere katılmak için üye olun" (referans görsel yapısı)
  if (isGuest) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <TouchableOpacity style={styles.backButton} onPress={handleBack}>
              <Image
                source={require("@/assets/images/icons/back-button.png")}
                style={styles.backButtonIcon}
                resizeMode="contain"
              />
            </TouchableOpacity>
            <Text style={styles.title}>Günlük Egzersizler</Text>
            <TouchableOpacity style={styles.bugunYapButton}>
              <Image
                source={require("@/assets/images/logo/logo-small.png")}
                style={styles.logo}
              />
            </TouchableOpacity>
          </View>
        </View>
        <ScrollView
          style={styles.content}
          contentContainerStyle={styles.emptyContentContainer}
          showsVerticalScrollIndicator={false}
        >
          <MemberRequiredBanner
            title="Egzersizlere katılmak için üye olmanız gerekiyor"
            description="Misafir modunda günlük egzersizlere erişemezsiniz. Üye olarak egzersizlere katılabilirsiniz."
          />
        </ScrollView>
        <BottomNavigation activeTab="exercises" />
      </SafeAreaView>
    );
  }

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={COLOR_SCALES.primary[60]} />
          <Text style={styles.loadingText}>Yükleniyor...</Text>
        </View>
      </SafeAreaView>
    );
  }

  // "Egzersiz saati bulunamadı" durumu için özel tasarım
  if (errorMessage && errorMessage.includes("Egzersiz saati bulunamadı")) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <TouchableOpacity style={styles.backButton} onPress={handleBack}>
              <Image
                source={require("@/assets/images/icons/back-button.png")}
                style={styles.backButtonIcon}
                resizeMode="contain"
              />
            </TouchableOpacity>
            <Text style={styles.title}>Günlük Egzersizler</Text>
            <TouchableOpacity style={styles.bugunYapButton}>
              <Image
                source={require("@/assets/images/logo/logo-small.png")}
                style={styles.logo}
              />
            </TouchableOpacity>
          </View>
        </View>
        <ScrollView 
          style={styles.content} 
          contentContainerStyle={styles.emptyContentContainer}
          showsVerticalScrollIndicator={false}
        >
          <Empty
            fullscreen={false}
            icon={
              <Ionicons 
                name="time-outline" 
                size={48} 
                color={COLOR_SCALES.primary[50]} 
              />
            }
            title="Egzersiz Saati Bulunamadı"
            description="Henüz bir egzersiz saati belirlenmemiş. Lütfen egzersiz saatini ayarlayın veya daha sonra tekrar deneyin."
          />
        </ScrollView>
        <BottomNavigation activeTab="exercises" />
      </SafeAreaView>
    );
  }

  // Genel hata durumu
  if (error || !exerciseData) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <TouchableOpacity style={styles.backButton} onPress={handleBack}>
              <Image
                source={require("@/assets/images/icons/back-button.png")}
                style={styles.backButtonIcon}
                resizeMode="contain"
              />
            </TouchableOpacity>
            <Text style={styles.title}>Günlük Egzersizler</Text>
            <TouchableOpacity style={styles.bugunYapButton}>
              <Image
                source={require("@/assets/images/logo/logo-small.png")}
                style={styles.logo}
              />
            </TouchableOpacity>
          </View>
        </View>
        <ScrollView 
          style={styles.content} 
          contentContainerStyle={styles.emptyContentContainer}
          showsVerticalScrollIndicator={false}
        >
          <Empty
            fullscreen={false}
            icon={
              <Ionicons 
                name="alert-circle-outline" 
                size={48} 
                color={COLOR_SCALES.helper.red} 
              />
            }
            title="Egzersiz Verisi Yüklenemedi"
            description={errorMessage || "Egzersiz verileri yüklenirken bir hata oluştu. Lütfen tekrar deneyin."}
          />
        </ScrollView>
        <BottomNavigation activeTab="exercises" />
      </SafeAreaView>
    );
  }

  const totalAnswers = exerciseData?.totalAnswers ?? 0;
  const correctAnswers = exerciseData?.correctAnswers ?? 0;
  const wrongAnswers = exerciseData?.wrongAnswers ?? 0;
  const correctPercentage = totalAnswers > 0 ? Math.round((correctAnswers / totalAnswers) * 100) : 0;
  const wrongPercentage = totalAnswers > 0 ? Math.round((wrongAnswers / totalAnswers) * 100) : 0;

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <TouchableOpacity style={styles.backButton} onPress={handleBack}>
            <Image
              source={require("@/assets/images/icons/back-button.png")}
              style={styles.backButtonIcon}
              resizeMode="contain"
            />
          </TouchableOpacity>
          <Text style={styles.title}>Günlük Egzersizler</Text>
          <TouchableOpacity style={styles.bugunYapButton}>
            <Image
              source={require("@/assets/images/logo/logo-small.png")}
              style={styles.logo}
            />
          </TouchableOpacity>
        </View>
      </View>
      <ScrollView 
        style={styles.content} 
        contentContainerStyle={[
          styles.contentContainer,
          { paddingBottom: 160 + Math.max(insets?.bottom ?? 0, 8) }
        ]}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={[COLOR_SCALES.primary[60]]}
            tintColor={COLOR_SCALES.primary[60]}
          />
        }
      >
        {/* Timer Section */}
        <View style={styles.timerContainer}>
          <View style={styles.timerCircle}>
            <View style={styles.timerProgress} />
            <View style={styles.timerTeeth} />
            <View style={styles.timerContent}>
              <Text style={styles.timerText}>{timer}</Text>
              <View style={styles.timerLabels}>
                <Text style={styles.timerLabel}>Gün</Text>
                <Text style={styles.timerLabel}>Saat</Text>
                <Text style={styles.timerLabel}>Dakika</Text>
              </View>
            </View>
          </View>
        </View>
        {/* Statistics Section */}
        <View style={styles.statsContainer}>
          <View style={styles.statItem}>
            <Text style={styles.statPercentage}>%{correctPercentage}</Text>
            <Text style={styles.statLabel}>Doğru Cevaplandı</Text>
          </View>
          <View style={styles.statDivider} />
          <View style={styles.statItem}>
            <Text style={styles.statPercentage}>%{wrongPercentage}</Text>
            <Text style={styles.statLabel}>Yanlış Cevaplandı</Text>
          </View>
        </View>
        {/* Motivational Message */}
        <View style={styles.messageContainer}>
          <Text style={styles.messageText}>
            Harika çalıştın! Yeni egzersiz zamanı seni bekliyor. Hazır olduğunda
            "Egzersize Başla" dediğinde hemen gelirimss 😊 
          </Text>
        </View>
        <View style={styles.characterContainer}>
          <Image
            source={require("@/assets/images/lokma-right.png")}
            style={styles.characterImage}
            resizeMode="contain"
          />
          <View style={styles.characterTimer}>
            <Image
              source={require("@/assets/images/clock.png")}
              style={styles.clockImage}
              resizeMode="contain"
            />
          </View>
        </View>
        {/* Start Exercise Button */}
        <TouchableOpacity
          style={styles.startButton}
          onPress={handleStartExercise}
        >
          <Text style={styles.startButtonText}>
            {exerciseData.canStart ? "Yeni Egzersize Başla" : "Egzersiz Henüz Başlatılamaz"}
          </Text>
        </TouchableOpacity>
        {/* Notification Text */}
        <View style={styles.notificationContainer}>
          <View style={styles.notificationRow}>
            <Image
              source={require("@/assets/images/icons/information.png")}
              style={styles.warningIcon}
              resizeMode="contain"
            />
            <Text style={styles.notificationText}>
              {exerciseData.canStart 
                ? "Belirlediğin saat geldiğinde bildirim alacaksın"
                : exerciseData.reason || "Bir sonraki egzersiz için bekleniyor"
              }
            </Text>
          </View>
        </View>
        {/* Bottom spacer to avoid overlap with BottomNavigation */}
        <View style={styles.bottomSpacer} />
      </ScrollView>
      <BottomNavigation activeTab="exercises" />
      {/* Toast */}
      <Toast
        visible={showToast}
        type={toastConfig.type}
        title={toastConfig.title}
        message={toastConfig.message}
        onHide={() => setShowToast(false)}
        duration={3000}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: COLOR_SCALES.colorGray[70],
    fontWeight: "500",
  },
  errorContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  emptyContentContainer: {
    flexGrow: 1,
    justifyContent: "center",
    paddingVertical: 40,
  },
  header: {
    backgroundColor: "#fff",
    paddingTop: 10,
    paddingBottom: 20,
  },
  headerContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    marginTop: 40,
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  title: {
    fontSize: 24,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "bold",
  },
  bugunYapButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  logo: {
    width: 60,
    height: 60,
    borderRadius: 30,
    borderWidth: 1,
    borderColor: "#fff",
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
    borderWidth: 1,
    borderColor: COLOR_SCALES.white[20],
    marginHorizontal: 20,
    borderRadius: 20,
  },
  contentContainer: {
    paddingBottom: 0,
  },
  timerContainer: {
    alignItems: "center",
    marginTop: 40,
  },
  timerCircle: {
    width: 200,
    height: 200,
    borderRadius: 100,
    backgroundColor: "#ccc",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
    borderWidth: 8,
    borderColor: "#fff",
  },
  timerProgress: {
    position: "absolute",
    top: -8,
    left: -8,
    right: -8,
    bottom: -8,
    borderRadius: 108,
    borderWidth: 8,
    borderColor: "#B4001A",
    borderTopColor: "#B4001A",
    borderRightColor: "#B4001A",
    borderBottomColor: "#fff",
    borderLeftColor: "#fff",
  },
  timerTeeth: {
    position: "absolute",
    top: 4,
    left: 4,
    right: 4,
    bottom: 4,
    borderRadius: 96,
    borderWidth: 1,
    borderColor: "#fff",
    borderStyle: "dashed",
    borderDasharray: [3, 4],
  },
  timerContent: {
    alignItems: "center",
  },
  timerText: {
    ...title["L/Bold"],
    color: "#B4001A",
    marginBottom: 8,
    fontSize: 24,
  },
  timerLabels: {
    flexDirection: "row",
    gap: 20,
  },
  timerLabel: {
    ...paragraph["S/Bold"],
    color: "#333",
    fontSize: 15,
  },
  statsContainer: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginTop: 30,
    paddingHorizontal: 20,
  },
  statItem: {
    alignItems: "center",
    flex: 1,
  },
  statPercentage: {
    ...title["XL/Bold"],
    color: "#151515",
    marginBottom: 4,
    fontWeight: "bold",
  },
  statLabel: {
    ...paragraph["S/Regular"],
    color: "#6D6D6D",
    textAlign: "center",
  },
  statDivider: {
    width: 1,
    backgroundColor: "#E5E5E5",
    marginHorizontal: 20,
  },
  messageContainer: {
    backgroundColor: COLOR_SCALES.white[20],
    borderRadius: 16,
    padding: 20,
    marginTop: 30,
  },
  messageText: {
    ...paragraph["S/Regular"],
    color: "#151515",
    marginBottom: 16,
  },
  characterContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  characterImage: {
    width: 60,
    height: 60,
    marginTop: 40,
    marginRight: 20,
  },
  characterTimer: {
    width: 137,
    height: 126,
    position: "relative",
  },
  characterTimerProgress: {
    position: "absolute",
    top: -3,
    left: -3,
    right: -3,
    bottom: -3,
    borderRadius: 23,
    borderWidth: 3,
    borderColor: "#B4001A",
    borderTopColor: "transparent",
    borderLeftColor: "transparent",
    transform: [{ rotate: "-45deg" }],
  },
  startButton: {
    backgroundColor: "#B4001A",
    borderRadius: 12,
    paddingVertical: 16,
    alignItems: "center",
    marginTop: 30,
    borderRadius: 24,
    backgroundColor: "#FFDCE1",
    boxShadow: "0 1px 0 0 #FFF inset, 2px 2px 0 0 #DB0020",
  },
  startButtonText: {
    ...title["M/Bold"],
    color: COLOR_SCALES.primary[80],
  },
  notificationContainer: {
    alignItems: "center",
    marginTop: 16,
  },
  notificationRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  notificationText: {
    ...paragraph["S/Regular"],
    color: "#6D6D6D",
  },
  warningIcon: {
    width: 16,
    height: 16,
  },
  bottomSpacer: {
    height: 80,
  },
  clockImage: {
    width: 160,
    height: 160,
  },
});

export default ExercisesScreen;
