import { FLEX } from "@/theme/mixins";
import { title } from "@/theme/typography";
import { router } from "expo-router";
import { StatusBar } from "expo-status-bar";
import React, { useEffect, useState } from "react";
import {
  Image,
  ImageBackground,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  useWindowDimensions,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { courses } from "../../../services/courses";
import { getActiveNotification } from "../../../services/notifications";
import { Toast } from "@/components/common";
import { COLOR_SCALES } from "@/theme/colors";
import DrawerMenu from "@/components/common/DrawerMenu";
import LokmaChatModal from "@/components/common/LokmaChatModal";
import useGuest from "@/hooks/useGuest";

export default function HomeScreen() {
  const { isGuest } = useGuest();
  const { height: screenHeight } = useWindowDimensions();
  
  // Ekran boyutuna göre dinamik değerler
  const isSmallScreen = screenHeight < 700;
  const bgHeight = isSmallScreen ? Math.round(screenHeight * 0.52) : 420;
  const actionButtonsTop = isSmallScreen ? Math.round(screenHeight * 0.28) : 240;
  const egitimleriMarginTop = isSmallScreen ? 20 : 20;
  const [courseList, setCourseList] = useState([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [chatModalVisible, setChatModalVisible] = useState(false);
  const [activeNotification, setActiveNotification] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastType, setToastType] = useState("info");
  const fetchCourses = async () => {
    const response = await courses();
    if (response.success) {
      setCourseList(response.data);
    } else {
      console.log(response.message);
    }
  };

  useEffect(() => {
    fetchCourses();
  }, []);

  useEffect(() => {
    if (!isGuest) {
      fetchActiveNotification();
    }
  }, [isGuest]);


  const fetchActiveNotification = async () => {
    // Misafir modunda bildirim kontrolü yapma
    if (isGuest) {
      setActiveNotification(false);
      return;
    }
    
    try {
      console.log("fetchActiveNotification");
      const res = await getActiveNotification();
      if (res?.success) {
        const hasData = res?.data != null; // data varsa göster, yoksa gösterme
        setActiveNotification(!!hasData);
        if (hasData) {
          setChatModalVisible(true);
        }
      } else {
        // Hata mesajını sadece konsola yazdır, throw etme
        console.log(res?.message ?? "Aktif bildirim alınamadı");
        setActiveNotification(false);
      }
    } catch (err) {
      // Hataları yakala ve sadece konsola yazdır
      console.log("getActiveNotification error:", err?.message);
      setActiveNotification(false);
      // Hata fırlatma, sessizce devam et
    }
  };

  const handleDrawerToggle = () => {
    setDrawerVisible(!drawerVisible);
  };

  const handleChatModalToggle = async () => {
    // Misafir modunda chat modal açma
    if (isGuest) {
      setToastMessage("Bu özelliğe erişmek için giriş yapmanız gerekmektedir.");
      setToastType("warning");
      setShowToast(true);
      return;
    }
    
    try {
      const res = await getActiveNotification();
      const hasData = !!res?.data;
      setActiveNotification(hasData);

      if (res?.success && hasData) {
        setChatModalVisible(true);
      } else {
        setToastMessage(res?.message ?? "Aktif bildiriminiz bulunmamaktadır");
        setToastType("info");
        setShowToast(true);
      }
    } catch (err) {
      setToastMessage(err?.message ?? "Aktif bildirim kontrol edilemedi");
      setToastType("warning");
      setShowToast(true);
    }
  };
  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="dark" backgroundColor="#fff" />

      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        {/* Background Image Container */}
        <ImageBackground
          source={require("@/assets/images/backgrounds/home-top-background.png")}
          style={[styles.backgroundImage, { height: bgHeight }]}
          resizeMode="cover"
        >
          {/* Header */}
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.logoContainer}
              onPress={handleDrawerToggle}
            >
              <Image
                source={require("@/assets/images/icons/menu.png")}
                style={styles.menuButton}
              />
            </TouchableOpacity>
              <TouchableOpacity style={styles.logoContainer}>
                <Image
                  source={require("@/assets/images/logo/logo-small.png")}
                  style={styles.logoSmall}
                />
              </TouchableOpacity>
          </View>

          <View style={styles.greetingContainer}>
            <Text style={styles.greeting}>
              Merhaba, ben <Text style={styles.greetingName}>LOKMA'M!</Text>
            </Text>
            <Text style={styles.assistantTitle}>
              Bugün sana nasıl yardımcı olabilirim
            </Text>
          </View>
          {/* LOKMA Assistant Section */}
          <View style={styles.section}>
            <View style={styles.assistantContainer}>
              <View style={styles.lokmaCharacter}>
                <Image
                  source={require("@/assets/images/lokma-right.png")}
                  style={styles.lokmaImage}
                  resizeMode="contain"
                />
              </View>
            </View>
          </View>
        </ImageBackground>
        {/* Action Buttons */}
        <View style={[styles.actionButtonsContainer, { top: actionButtonsTop }]}>
          <TouchableOpacity
            style={[styles.actionButton, { width: 200, right: -60 }]}
            activeOpacity={0.8}
            onPress={handleChatModalToggle}
          >
            <View style={styles.buttonContent}>
              <View style={[styles.buttonIconContainer]}>
                <Image
                  source={require("@/assets/images/icons/message-question.png")}
                  style={styles.buttonIcon}
                  resizeMode="contain"
                />
              </View>
              <Text style={styles.buttonText}>Soru cevap</Text>
              <Image
                source={require("@/assets/images/icons/right-arrows-red.png")}
                style={styles.rightIcon}
                resizeMode="contain"
              />
            </View>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.actionButton}
            onPress={() => {
              if (isGuest) {
                setToastMessage("Bu özelliğe erişmek için giriş yapmanız gerekmektedir.");
                setToastType("warning");
                setShowToast(true);
                return;
              }
              router.push("/(tabs)/exercises/planning");
            }}
            activeOpacity={0.8}
          >
            <View style={styles.buttonContent}>
              <View style={styles.buttonIconContainer}>
                <Image
                  source={require("@/assets/images/icons/note-2.png")}
                  style={styles.buttonIcon}
                  resizeMode="contain"
                />
              </View>
              <Text style={styles.buttonText}>Günlük egzersizler</Text>
              <Image
                source={require("@/assets/images/icons/right-arrows-red.png")}
                style={styles.rightIcon}
                resizeMode="contain"
              />
            </View>
          </TouchableOpacity>
        </View>

        {/* Eğitimlerim Section */}
        <View style={[styles.section, { marginTop: egitimleriMarginTop, marginBottom: 50 }]}>
          <Text style={styles.sectionTitle}>Eğitimlerim</Text>
          {courseList?.length > 0 &&
            courseList.map((course, index) => (
              <TouchableOpacity
                key={course.id || index}
                style={styles.trainingCard}
                activeOpacity={0.8}
                onPress={() => {
                  if (isGuest) {
                    setToastMessage("Bu özelliğe erişmek için giriş yapmanız gerekmektedir.");
                    setToastType("warning");
                    setShowToast(true);
                    return;
                  }
                  router.push({
                    pathname: "/courses",
                    params: { courseId: course.id },
                  });
                }}
              >
                <ImageBackground
                  source={require("@/assets/images/backgrounds/frame-background-play.png")}
                  style={styles.cardBackground}
                  resizeMode="cover"
                >
                  <View style={styles.cardContainer}>
                    {/* Main image */}
                    <View style={styles.cardImageContainer}>
                      <Image
                        source={require("@/assets/images/illustrations/frame-image.png")}
                        style={styles.frameImage}
                        resizeMode="contain"
                      />
                    </View>

                    <View style={styles.cardTitleContainer}>
                      <Text style={styles.cardTitle2}>
                        Bugün YAP Eğitimleri
                      </Text>
                      <Text style={styles.cardDescription}>
                        Gıda İsrafı Farkındalık Eğitimleri
                      </Text>
                    </View>

                    {/* Footer with stats */}
                    <View style={styles.cardFooter}>
                      <Text style={styles.statText}>
                        <Text style={styles.statLabel}>Ders Sayısı: </Text>
                        <Text style={styles.statValue}>
                          {course.totalVideos}
                        </Text>
                      </Text>
                      <Text style={styles.statTextRight}>
                        <Text style={styles.statLabel}>Ders Saati: </Text>
                        <Text style={styles.statValue}>
                          {course.totalDuration} Dk
                        </Text>
                      </Text>
                    </View>
                  </View>
                </ImageBackground>
              </TouchableOpacity>
            ))}
        </View>
      </ScrollView>
      {/* Drawer Menu */}
      <DrawerMenu
        visible={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        userData={null}
      />

    
      <LokmaChatModal
        visible={chatModalVisible}
        onClose={() => setChatModalVisible(false)}
        message="Bugün gıdanı israf ettinmi?"
        timestamp={new Date().toLocaleTimeString("tr-TR", { hour: "2-digit", minute: "2-digit" })}
      />

      <Toast
        visible={showToast}
        message={toastMessage}
        type={toastType}
        onHide={() => setShowToast(false)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  cardTitleContainer: {
    flexDirection: "column",
    justifyContent: "flex-start",
    position: "absolute",
    top: 20,
    left: 20,
    right: 20,
  },
  cardTitle2: {
    ...title["L/Medium"],
    color: COLOR_SCALES.gray[40],
    fontSize: 22,
    fontWeight: "700",
    marginBottom: 20,
  },
  cardDescription: {
    ...title["S/Regular"],
    color: "#000",
    fontSize: 18,
    fontWeight: "700",
    lineHeight: 18,
    marginTop: -10,
  },
  container: {
    ...FLEX.fill,
    backgroundColor: "#FFFFFF",
  },
  scrollView: {
    flex: 1,
  },
  backgroundImage: {
    width: "100%",
    height: 380,
    paddingBottom: 20,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    paddingHorizontal: 20,
    paddingTop: 20,
    paddingBottom: 10,
  },
  greetingContainer: {
    marginHorizontal: 20,
    marginTop: 8,
  },
  greeting: {
    ...title["XL/Bold"],
    color: "#FFF",
    fontSize: 28,
    fontWeight: "700",
    lineHeight: 34,
  },
  greetingName: {
    fontWeight: "700",
  },
  assistantTitle: {
    fontFamily: "Rubik",
    fontSize: 22,
    fontWeight: "400",
    lineHeight: 24,
    color: "#FFF",
    maxWidth: "60%",
    marginTop: 8,
  },
  logoContainer: {
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
  },
  logoSmall: {
    width: 60,
    height: 60,
    borderWidth: 1,
    borderColor: "#fff",
    borderRadius: 30,
  },
  section: {
    paddingHorizontal: 20,
    marginTop: 30,
  },
  sectionTitle: {
    ...title["L/Bold"],
    color: "#000",
    fontSize: 24,
    fontWeight: "700",
    marginBottom: 20,
  },
  trainingCard: {
    borderRadius: 20,
    overflow: "hidden",
  },
  cardBackground: {
    width: "100%",
    objectFit: "cover",
    overflow: "hidden",
    height: 285,
  },
  cardContainer: {
    padding: 20,
    flex: 1,
    justifyContent: "space-between",
  },
  cardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    marginBottom: 16,
  },
  cardTitle: {
    color: "#F1D9E2",
    fontFamily: "Rubik",
    fontSize: 14,
    fontWeight: "400",
    lineHeight: 22,
    flex: 1,
  },
  frameLogo: {
    width: 40,
    height: 40,
  },
  cardImageContainer: {
    alignItems: "flex-start",
    marginVertical: 16,
  },
  frameImage: {
    width: 140,
    height: 124,
    marginTop: 60,
  },
  cardFooter: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  statText: {
    flexDirection: "row",
  },
  statTextRight: {
    flexDirection: "row",
  },
  statLabel: {
    color: "#F1D9E2",
    fontFamily: "Rubik",
    fontSize: 12,
    fontWeight: "400",
    lineHeight: 18,
  },
  statValue: {
    color: "#FFFFFF",
    fontFamily: "Rubik",
    fontSize: 12,
    fontWeight: "700",
    lineHeight: 18,
  },
  assistantTitleContainer: {
    flexDirection: "row",
    alignItems: "center",
    paddingRight: "48%",
  },
  assistantTitle: {
    fontFamily: "Rubik",
    fontSize: 15,
    fontWeight: "400",
    lineHeight: 20,
    color: "#FFF",
    flexShrink: 1,
  },
  assistantContainer: {
    flexDirection: "row",
    alignItems: "center",
    borderRadius: 20,
    padding: 20,
  },
  lokmaCharacter: {
    position: "absolute",
    left: 0,
    bottom: -110,
  },
  lokmaImage: {
    width: 142,
    height: 140,
  },
  menuButton: {
    width: 50,
    height: 50,
    marginTop: 10,
  },
  actionButtonsContainer: {
    position: "absolute",
    top: 223,
    right: 20,
    zIndex: 10,
    width: "60%",
  },
  actionButton: {
    borderRadius: 64,
    borderWidth: 1,
    borderColor: "#000",
    backgroundColor: "#EEE",
    boxShadow: "0 1px 0 0 #FFF inset, 2px 2px 0 0 #DB0020",
    marginBottom: 24,
  },
  buttonContent: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 6,
  },
  buttonIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 25,
    backgroundColor: "#B4001A",
    alignItems: "center",
    justifyContent: "center",
    marginRight: 10,
  },
  buttonIcon: {
    width: 24,
    height: 24,
  },
  buttonText: {
    flex: 1,
    color: "#420F1B",
    fontFamily: "Rubik",
    fontSize: 14,
    fontWeight: "600",
    lineHeight: 22,
  },
  rightIcon: {
    width: 20,
    height: 20,
  },
});
