import { FLEX } from "@/theme/mixins";
import { router } from "expo-router";
import { StatusBar } from "expo-status-bar";
import React, { useEffect, useState } from "react";
import {
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { getAllExams } from "../../../services/user";
import MemberRequiredBanner from "@/components/common/MemberRequiredBanner";
import useGuest from "@/hooks/useGuest";

export default function LearningScreen() {
  const { isGuest } = useGuest();

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

  const [exams, setExams] = useState([]);
  const [toastMessage, setToastMessage] = useState(null);
  const [showToast, setShowToast] = useState(false);

  const ExamListele = async () => {
    if (isGuest) return;
    try {
      const res = await getAllExams();
      if (res?.success) {

        const baseData =
          res?.data?.map((course, courseIndex) => {
            const exam = course?.exams?.[0];
            const courseStatusRaw = (course?.status ?? "").toString().toLowerCase();
            const isExamCompleted = exam?.status?.isExamCompleted === true;
            const isNotPurchased = courseStatusRaw === "satın alınmadı";
            const statusLabel = isExamCompleted
              ? "Tamamlandı"
              : isNotPurchased
              ? "Satın alınmadı"
              : "Bekleniyor";
            const statusColor = isExamCompleted
              ? "#00C853" // green
              : isNotPurchased
              ? "#E50012" // red
              : "#FFA500"; // yellow
            return {
              id: exam?.id,
              title: exam?.title,
              description: exam?.description,
              status: statusLabel,
              statusLower: statusLabel.toLowerCase(),
              statusColor,
              questionCount: exam?.questionCount ?? exam?.maxAttempts ?? 0,
              iconColor: courseIndex % 2 === 0 ? "#E50012" : "#FFA500",
              iconImage:
                courseIndex % 2 === 0
                  ? require("@/assets/images/icons/book/odd.png")
                  : require("@/assets/images/icons/question/odd.png"),
              questionIcon:
                courseIndex % 2 === 0
                  ? require("@/assets/images/icons/question/odd.png")
                  : require("@/assets/images/icons/question/even.png"),
              canTakeExam: exam?.status?.canTakeExam,
              reason: exam?.status?.reason,
              duration: exam?.duration,
              passingScore: exam?.passingScore,
              courseId: exam?.courseId ?? course?.courseId ?? course?.id,
              lessonId: exam?.lessonId ?? exam?.lesson?.id ?? course?.lessonId ?? course?.lesson?.id,
              courseTitle: course?.courseTitle,
              isCourseCompleted: course?.isCourseCompleted === true,
            };
          }) || [];

        const firstPending = baseData.find((x) => x?.statusLower === "bekleniyor");
        const firstPendingId = firstPending?.id ?? null;

        const formattedData = baseData.map((item) => {
          const isPurchased = item?.statusLower !== "satın alınmadı";
          const isCompleted = item?.statusLower === "tamamlandı";
          const isPending = item?.statusLower === "bekleniyor";
          const isFirstPending = isPending && item?.id === firstPendingId;
          const isDisabled = isCompleted || !isPurchased || (isPending && !isFirstPending);
          return { ...item, isDisabled, isFirstPending };
        });

        setExams(formattedData);
      }
    } catch (error) {
      // Error handling
    }
  };

  useEffect(() => {
    ExamListele();
  }, [isGuest]);

  const handleStartTest = (testId) => {
    if (isGuest) return;
    const test = exams?.find((exam) => exam?.id === testId);
    if (test?.isDisabled) return;
    router.push({
      pathname: "/quiz/[id]",
      params: { id: testId, courseId: test?.courseId, lessonId: test?.lessonId },
    });
  };

  const testData = [
    {
      id: 1,
      title: "Ön Test",
      description: "10 soruluk kısa ön test. Hemen bilginizi ölçün!",
      status: "Bekleniyor",
      statusColor: "#E50012",
      questionCount: 10,
      iconColor: "#E50012",
      iconImage: require("@/assets/images/icons/book/odd.png"),
      questionIcon: require("@/assets/images/icons/question/odd.png"),
    },
    {
      id: 2,
      title: "Ön Test",
      description: "10 soruluk kısa ön test. Hemen bilginizi ölçün!",
      status: "Bekleniyor",
      statusColor: "#FFA500",
      questionCount: 10,
      iconColor: "#FFA500",
      iconImage: require("@/assets/images/icons/book/even.png"),
      questionIcon: require("@/assets/images/icons/question/even.png"),
    },
  ];

  if (isGuest) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar style="dark" backgroundColor="#F5F5F5" />
        <View style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <Image
              source={require("@/assets/images/icons/back-button.png")}
              style={styles.backButtonIcon}
              resizeMode="contain"
            />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>Katılım Belge Sınavları</Text>
          <View style={styles.headerSpacer} />
        </View>
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
        >
          <View style={styles.illustrationContainer}>
            <Image
              source={require("@/assets/images/lokma-2.png")}
              style={styles.illustration}
              resizeMode="contain"
            />
          </View>
          <MemberRequiredBanner
            title="Sınavlara katılmak için üye olmanız gerekiyor"
            description="Misafir modunda belge sınavlarına erişemezsiniz. Üye olarak sınavlara katılabilirsiniz."
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="dark" backgroundColor="#F5F5F5" />
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
          <Image
            source={require("@/assets/images/icons/back-button.png")}
            style={styles.backButtonIcon}
            resizeMode="contain"
          />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Katılım Belge Sınavları</Text>
        <View style={styles.headerSpacer} />
      </View>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Illustration Section */}
        <View style={styles.illustrationContainer}>
          <Image
            source={require("@/assets/images/lokma-2.png")}
            style={styles.illustration}
            resizeMode="contain"
          />
        </View>
        {/* Test Cards */}
        <View style={styles.testsContainer}>
          {exams?.map((test) => (
            <View
              key={test.id}
              style={[
                styles.testCard,
                { backgroundColor: "white" },
                test?.isDisabled && styles.disabledCard,
                test?.statusLower === "tamamlandı" && styles.completedCard,
              ]}
            >
              {/* Test Icon */}
              <View
                style={[styles.testIcon, { backgroundColor: test.iconColor }]}
              >
                <Image
                  source={test.iconImage}
                  style={styles.testIconImage}
                  resizeMode="contain"
                />
              </View>

              {/* Test Content */}
              <View style={styles.testContent}>
                <View style={styles.testHeader}>
                  <Text style={styles.testTitle}>{test.title}</Text>
                  <View style={styles.statusContainer}>
                    <Text style={styles.statusLabel}>Durum: </Text>
                    <View style={[styles.statusDot, { backgroundColor: test.statusColor }]} />
                    <Text
                      style={[styles.statusText, { color: test.statusColor }]}
                    >
                      {test.status}
                    </Text>
                  </View>
                </View>

                <Text style={styles.testDescription}>{test.description}</Text>

                {/* Test Info */}
                <View style={styles.testInfo}>
                  <View style={styles.infoItem}>
                    <Image
                      source={test.questionIcon}
                      style={styles.infoIcon}
                      resizeMode="contain"
                    />
                    <Text style={styles.infoText}>
                      Soru Sayısı: {test.questionCount}
                    </Text>
                  </View>

                  <View style={styles.infoItem}>
                    <Image
                      source={
                        test.id === 1
                          ? require("@/assets/images/icons/teacher/odd.png")
                          : require("@/assets/images/icons/teacher/even.png")
                      }
                      style={styles.infoIcon}
                      resizeMode="contain"
                    />
                    <Text style={styles.infoText}>
                      Başarıyla tamamlayana verilir
                    </Text>
                  </View>
                </View>

                {/* Start Test Button */}
                <View style={styles.buttonContainer}>
                  <TouchableOpacity
                    style={[
                      styles.testButton,
                      (test?.isDisabled || test?.statusLower === "satın alınmadı") && styles.testButtonDisabled,
                      test?.statusLower === "tamamlandı" && styles.testButtonCompleted,
                    ]}
                    onPress={() => handleStartTest(test.id)}
                    activeOpacity={0.8}
                    disabled={test?.isDisabled === true}
                  >
                    <Text style={styles.testButtonText}>
                      {test?.statusLower === "satın alınmadı"
                        ? "Satın alınmadı"
                        : test?.statusLower === "tamamlandı"
                        ? "Tamamlandı"
                        : "Teste Başla"}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>

              {test?.statusLower === "tamamlandı" && (
                <View style={styles.completedBadge}>
                  <Text style={styles.completedBadgeText}>Tamamlandı</Text>
                </View>
              )}
            </View>
          ))}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#F5F5F5",
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingTop: 10,
    paddingBottom: 20,
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: "#000",
    flex: 1,
    textAlign: "center",
    marginHorizontal: 20,
  },
  headerSpacer: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 100,
  },
  illustrationContainer: {
    paddingHorizontal: 20,
    marginBottom: 30,
    alignItems: "center",
  },
  illustration: {
    width: "100%",
    height: 176,
  },
  testsContainer: {
    paddingHorizontal: 20,
    gap: 20,
  },
  testCard: {
    borderRadius: 20,
    padding: 20,
    flexDirection: "row",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  disabledCard: {
    opacity: 0.85,
  },
  completedCard: {
    backgroundColor: "#F0FFF4",
    borderWidth: 1,
    borderColor: "#00C853",
  },
  testIcon: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 16,
  },
  testIconImage: {
    width: 32,
    height: 32,
  },
  testContent: {
    flex: 1,
  },
  testHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    marginBottom: 8,
  },
  testTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: "#333",
    flex: 1,
  },
  statusContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  statusLabel: {
    fontSize: 12,
    color: "#666",
  },
  statusIcon: {
    width: 8,
    height: 8,
    marginHorizontal: 4,
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginHorizontal: 4,
  },
  statusText: {
    fontSize: 12,
    fontWeight: "600",
  },
  testDescription: {
    fontSize: 14,
    color: "#666",
    lineHeight: 20,
    marginBottom: 16,
  },
  testInfo: {
    marginBottom: 16,
  },
  infoItem: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 8,
  },
  infoIcon: {
    width: 16,
    height: 16,
    marginRight: 8,
  },
  infoText: {
    fontSize: 12,
    color: "#666",
  },
  buttonContainer: {
    alignItems: "flex-start",
  },
  testButton: {
    backgroundColor: "#FF0025",
    paddingVertical: 8,
    paddingHorizontal: 24,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: "#420F1B",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  testButtonDisabled: {
    backgroundColor: "#BDBDBD",
    borderColor: "#9E9E9E",
    shadowColor: "#9E9E9E",
  },
  testButtonCompleted: {
    backgroundColor: "#00C853",
    borderColor: "#008F3A",
    shadowColor: "#00C853",
  },
  testButtonText: {
    color: "#FFFFFF",
    fontSize: 14,
    fontWeight: "700",
    fontFamily: "Rubik",
    lineHeight: 20,
  },
  completedBadge: {
    position: "absolute",
    top: 12,
    right: 12,
    backgroundColor: "#00C853",
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
  },
  completedBadgeText: {
    color: "#FFFFFF",
    fontSize: 12,
    fontWeight: "700",
  },
});
