import { COLOR_SCALES } from "@/theme/colors";
import { FLEX } from "@/theme/mixins";
import { router, useLocalSearchParams } from "expo-router";
import { StatusBar } from "expo-status-bar";
import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import Toast from "@/components/common/Toast";
import useToast from "@/hooks/useToast";
import { courseDetail } from "../../services/courses";

export default function LessonsScreen() {
  const { courseId, lessonId, lessonTitle, isBuy: isBuyParam } = useLocalSearchParams();
  const [videos, setVideos] = useState([]);
  const [lessonInfo, setLessonInfo] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const { toast, showToast, hideToast } = useToast();
  const isBuy = Number(isBuyParam ?? 0);

  useEffect(() => {
    const fetchLesson = async () => {
      try {
        setIsLoading(true);
        const response = await courseDetail(courseId);
        if (response.success) {
          const lesson = response.data?.Lessons?.find(
            (l) => String(l.id) === String(lessonId)
          );
          if (lesson) {
            setLessonInfo(lesson);
            const sortedVideos = [...(lesson.Videos ?? [])].sort(
              (a, b) => a.order - b.order
            );
            setVideos(sortedVideos);
          }
        }
      } catch (error) {
        showToast({
          type: "error",
          title: "Hata",
          message: error?.message || "Videolar yüklenirken bir hata oluştu",
        });
      } finally {
        setIsLoading(false);
      }
    };
    if (courseId && lessonId) fetchLesson();
  }, [courseId, lessonId]);

  const handleVideoPress = (video) => {
    if (isBuy !== 1) {
      showToast({
        type: "warning",
        title: "Paket Gerekli",
        message: "Paket alımı yapmanız gerekmektedir",
      });
      return;
    }
    router.push({
      pathname: "/courses/[id]",
      params: {
        id: video.id,
        videoUrl: video.videoUrl,
        title: video.title,
        description: video.description,
      },
    });
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={COLOR_SCALES.primary[50]} />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="dark" backgroundColor="#fff" />

      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={() => router.back()}>
          <Image
            source={require("@/assets/images/icons/back-button.png")}
            style={styles.backIcon}
            resizeMode="contain"
          />
        </TouchableOpacity>
        <Text style={styles.headerTitle} numberOfLines={1}>
          {lessonInfo?.title ?? lessonTitle ?? "Videolar"}
        </Text>
        <Text style={styles.counter}>{videos.length} Video</Text>
      </View>

      {/* Description */}
      {lessonInfo?.description ? (
        <View style={styles.descContainer}>
          <Text style={styles.descText}>{lessonInfo.description}</Text>
        </View>
      ) : null}

      <ScrollView
        style={styles.scroll}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        {videos.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>Bu derse ait video bulunamadı</Text>
          </View>
        ) : (
          videos.map((video, index) => (
            <TouchableOpacity
              key={video.id}
              style={[
                styles.videoCard,
                isBuy !== 1 && styles.videoCardLocked,
              ]}
              activeOpacity={0.8}
              onPress={() => handleVideoPress(video)}
            >
              {/* Order badge */}
              <View style={styles.orderBadge}>
                <Text style={styles.orderText}>{index + 1}</Text>
              </View>

              {/* Thumbnail placeholder */}
              <View style={styles.thumbnail}>
                <View style={styles.playIconWrapper}>
                  <View style={styles.playTriangle} />
                </View>
              </View>

              {/* Info */}
              <View style={styles.videoInfo}>
                <Text style={styles.videoTitle} numberOfLines={2}>
                  {video.title}
                </Text>
                {video.description ? (
                  <Text style={styles.videoDesc} numberOfLines={1}>
                    {video.description}
                  </Text>
                ) : null}
                <View style={styles.durationRow}>
                  <Image
                    source={require("@/assets/images/clock-icon.png")}
                    style={styles.clockIcon}
                    resizeMode="contain"
                  />
                  <Text style={styles.durationText}>{video.duration ?? 0} Dk</Text>
                </View>
              </View>

              {/* Lock icon if not purchased */}
              {isBuy !== 1 && (
                <View style={styles.lockBadge}>
                  <Text style={styles.lockIcon}>🔒</Text>
                </View>
              )}
            </TouchableOpacity>
          ))
        )}
      </ScrollView>

      <Toast
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#fff",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff",
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingTop: 12,
    paddingBottom: 12,
    borderBottomWidth: 1,
    borderBottomColor: "#F0F0F0",
  },
  backButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "#2C1810",
    alignItems: "center",
    justifyContent: "center",
  },
  backIcon: {
    width: 20,
    height: 20,
  },
  headerTitle: {
    flex: 1,
    color: "#1C1C1E",
    fontSize: 17,
    fontWeight: "700",
    marginHorizontal: 12,
  },
  counter: {
    color: "#8E8E93",
    fontSize: 13,
    fontWeight: "500",
  },
  descContainer: {
    paddingHorizontal: 20,
    paddingVertical: 12,
    backgroundColor: "#FAFAFA",
  },
  descText: {
    color: "#555",
    fontSize: 14,
    lineHeight: 20,
  },
  scroll: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: 20,
    paddingTop: 16,
    paddingBottom: 40,
    gap: 12,
  },
  videoCard: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#FAFAFA",
    borderRadius: 16,
    padding: 12,
    borderWidth: 1,
    borderColor: "#EFEFEF",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.06,
    shadowRadius: 4,
    elevation: 2,
  },
  videoCardLocked: {
    opacity: 0.6,
  },
  orderBadge: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: COLOR_SCALES.primary[60],
    alignItems: "center",
    justifyContent: "center",
    marginRight: 10,
  },
  orderText: {
    color: "#fff",
    fontSize: 13,
    fontWeight: "700",
  },
  thumbnail: {
    width: 64,
    height: 64,
    borderRadius: 12,
    backgroundColor: "#2C1810",
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  playIconWrapper: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: "rgba(255,255,255,0.15)",
    alignItems: "center",
    justifyContent: "center",
  },
  playTriangle: {
    width: 0,
    height: 0,
    borderTopWidth: 7,
    borderBottomWidth: 7,
    borderLeftWidth: 12,
    borderTopColor: "transparent",
    borderBottomColor: "transparent",
    borderLeftColor: "#fff",
    marginLeft: 3,
  },
  videoInfo: {
    flex: 1,
  },
  videoTitle: {
    color: "#1C1C1E",
    fontSize: 15,
    fontWeight: "600",
    lineHeight: 20,
    marginBottom: 4,
  },
  videoDesc: {
    color: "#8E8E93",
    fontSize: 12,
    lineHeight: 16,
    marginBottom: 6,
  },
  durationRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 4,
  },
  clockIcon: {
    width: 14,
    height: 14,
  },
  durationText: {
    color: "#8E8E93",
    fontSize: 12,
    fontWeight: "500",
  },
  lockBadge: {
    marginLeft: 8,
  },
  lockIcon: {
    fontSize: 18,
  },
  emptyContainer: {
    flex: 1,
    alignItems: "center",
    paddingTop: 60,
  },
  emptyText: {
    color: "#8E8E93",
    fontSize: 15,
  },
});
