import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router, useLocalSearchParams } from 'expo-router';
import React from 'react';
import { Alert, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAuth } from '@/contexts/AuthContext';
import { useColors } from '@/hooks/useColors';
import { COURSES, CREATORS, formatCount, formatPrice } from '@/data/mockData';

export default function CourseDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { user, enrollCourse } = useAuth();

  const course = COURSES.find((c) => c.id === id);
  const creator = course ? CREATORS.find((c) => c.id === course.creatorId) : null;
  const isEnrolled = !!(user?.enrolledCourseIds.includes(id ?? ''));

  const topPad = Platform.OS === 'web' ? 67 : insets.top;
  const bottomPad = Platform.OS === 'web' ? 34 : insets.bottom;

  if (!course) {
    return (
      <View style={[s.screen, { backgroundColor: colors.background, justifyContent: 'center', alignItems: 'center' }]}>
        <Text style={{ color: colors.foreground, fontFamily: 'Poppins_500Medium' }}>Course not found</Text>
      </View>
    );
  }

  const handleEnroll = () => {
    if (isEnrolled) return;
    Alert.alert(
      'Enroll in Course',
      `${course.title}\n\nPrice: ${formatPrice(course.price)}\n\nProceed to enroll?`,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'Enroll Now', onPress: () => enrollCourse(course.id) },
      ]
    );
  };

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <ScrollView contentContainerStyle={[s.scroll, { paddingBottom: bottomPad + 100 }]} showsVerticalScrollIndicator={false}>
        <LinearGradient
          colors={course.gradientColors}
          style={[s.hero, { paddingTop: topPad + 16 }]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <TouchableOpacity onPress={() => router.back()} style={s.backBtn}>
            <View style={s.backBtnBg}>
              <Ionicons name="arrow-back" size={20} color="#fff" />
            </View>
          </TouchableOpacity>
          <View style={s.heroContent}>
            <Ionicons name="play-circle" size={64} color="rgba(255,255,255,0.8)" />
            <View style={[s.levelTag]}>
              <Text style={s.levelTagText}>{course.level}</Text>
            </View>
          </View>
        </LinearGradient>

        <View style={s.body}>
          <Text style={[s.title, { color: colors.foreground }]}>{course.title}</Text>

          <TouchableOpacity
            onPress={() => creator && router.push(`/creator/${creator.id}` as any)}
            style={[s.creatorRow, { backgroundColor: colors.card, borderColor: colors.border }]}
          >
            <View style={[s.creatorAvatar, { backgroundColor: creator?.avatarColor ?? colors.primary }]}>
              <Text style={s.creatorAvatarText}>{creator?.avatarInitials ?? '?'}</Text>
            </View>
            <View style={s.creatorInfo}>
              <Text style={[s.creatorName, { color: colors.foreground }]}>{creator?.name}</Text>
              <Text style={[s.creatorSpec, { color: colors.mutedForeground }]}>{creator?.specialty}</Text>
            </View>
            {creator?.isVerified && <Ionicons name="checkmark-circle" size={18} color={colors.primary} />}
            <Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
          </TouchableOpacity>

          <View style={s.statsRow}>
            <View style={s.statItem}>
              <Ionicons name="star" size={16} color="#FFD700" />
              <Text style={[s.statVal, { color: colors.foreground }]}>{course.rating}</Text>
              <Text style={[s.statSub, { color: colors.mutedForeground }]}>({formatCount(course.ratingCount)})</Text>
            </View>
            <View style={s.statDot} />
            <View style={s.statItem}>
              <Ionicons name="people-outline" size={16} color={colors.mutedForeground} />
              <Text style={[s.statVal, { color: colors.foreground }]}>{formatCount(course.enrolledCount)}</Text>
              <Text style={[s.statSub, { color: colors.mutedForeground }]}>enrolled</Text>
            </View>
            <View style={s.statDot} />
            <View style={s.statItem}>
              <Ionicons name="time-outline" size={16} color={colors.mutedForeground} />
              <Text style={[s.statVal, { color: colors.foreground }]}>{course.totalDuration}</Text>
            </View>
          </View>

          <Text style={[s.sectionLabel, { color: colors.foreground }]}>About this course</Text>
          <Text style={[s.desc, { color: colors.mutedForeground }]}>{course.description}</Text>

          <Text style={[s.sectionLabel, { color: colors.foreground }]}>Skills you'll gain</Text>
          <View style={s.skillsRow}>
            {course.skills.map((skill) => (
              <View key={skill} style={[s.skillChip, { backgroundColor: colors.card, borderColor: colors.border }]}>
                <Text style={[s.skillText, { color: colors.foreground }]}>{skill}</Text>
              </View>
            ))}
          </View>

          <Text style={[s.sectionLabel, { color: colors.foreground }]}>Course Curriculum</Text>
          <Text style={[s.lessonsCount, { color: colors.mutedForeground }]}>{course.lessons.length} lessons</Text>

          {course.lessons.map((lesson, i) => (
            <View key={lesson.id} style={[s.lessonRow, { borderColor: colors.border, backgroundColor: colors.card }]}>
              <View style={[s.lessonNum, { backgroundColor: lesson.isPreview ? colors.primary + '22' : colors.secondary }]}>
                <Text style={[s.lessonNumText, { color: lesson.isPreview ? colors.primary : colors.mutedForeground }]}>{i + 1}</Text>
              </View>
              <View style={s.lessonInfo}>
                <Text style={[s.lessonTitle, { color: colors.foreground }]} numberOfLines={1}>{lesson.title}</Text>
                <Text style={[s.lessonDur, { color: colors.mutedForeground }]}>{lesson.duration}</Text>
              </View>
              {lesson.isPreview ? (
                <View style={[s.previewBadge, { backgroundColor: colors.primary + '22', borderColor: colors.primary + '55' }]}>
                  <Text style={[s.previewText, { color: colors.primary }]}>Preview</Text>
                </View>
              ) : (
                <Ionicons name={isEnrolled ? 'play-circle-outline' : 'lock-closed-outline'} size={18} color={colors.mutedForeground} />
              )}
            </View>
          ))}
        </View>
      </ScrollView>

      <View style={[s.footer, { paddingBottom: bottomPad + 12, backgroundColor: colors.background, borderTopColor: colors.border }]}>
        {!isEnrolled ? (
          <View style={s.footerContent}>
            <View>
              <Text style={[s.footerPrice, { color: colors.primary }]}>{formatPrice(course.price)}</Text>
              {course.originalPrice && (
                <Text style={[s.footerOriginal, { color: colors.mutedForeground }]}>{formatPrice(course.originalPrice)}</Text>
              )}
            </View>
            <TouchableOpacity onPress={handleEnroll} style={[s.enrollBtn, { backgroundColor: colors.primary }]} activeOpacity={0.85}>
              <Text style={s.enrollBtnText}>Enroll Now</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <TouchableOpacity style={[s.continueBtn, { backgroundColor: colors.primary }]} activeOpacity={0.85}>
            <Ionicons name="play" size={18} color="#fff" />
            <Text style={s.continueBtnText}>Continue Learning</Text>
          </TouchableOpacity>
        )}
      </View>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  scroll: {},
  hero: { height: 220, justifyContent: 'flex-end', paddingHorizontal: 16, paddingBottom: 20 },
  backBtn: { position: 'absolute', top: 0, left: 16 },
  backBtnBg: { width: 38, height: 38, borderRadius: 19, backgroundColor: 'rgba(0,0,0,0.35)', alignItems: 'center', justifyContent: 'center' },
  heroContent: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' },
  levelTag: { backgroundColor: 'rgba(0,0,0,0.4)', paddingHorizontal: 10, paddingVertical: 5, borderRadius: 8 },
  levelTagText: { color: '#fff', fontSize: 12, fontFamily: 'Poppins_600SemiBold' },
  body: { padding: 16, gap: 6 },
  title: { fontSize: 20, fontFamily: 'Poppins_700Bold', lineHeight: 28, marginBottom: 6 },
  creatorRow: {
    flexDirection: 'row', alignItems: 'center', gap: 10,
    borderRadius: 14, borderWidth: 1, padding: 12, marginBottom: 8,
  },
  creatorAvatar: { width: 44, height: 44, borderRadius: 22, alignItems: 'center', justifyContent: 'center' },
  creatorAvatarText: { color: '#fff', fontSize: 14, fontFamily: 'Poppins_700Bold' },
  creatorInfo: { flex: 1 },
  creatorName: { fontSize: 14, fontFamily: 'Poppins_600SemiBold' },
  creatorSpec: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  statsRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, gap: 8, marginBottom: 6 },
  statItem: { flexDirection: 'row', alignItems: 'center', gap: 4 },
  statVal: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  statSub: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  statDot: { width: 4, height: 4, borderRadius: 2, backgroundColor: '#555' },
  sectionLabel: { fontSize: 16, fontFamily: 'Poppins_700Bold', marginTop: 10, marginBottom: 6 },
  desc: { fontSize: 14, fontFamily: 'Poppins_400Regular', lineHeight: 21 },
  skillsRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 4 },
  skillChip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 20, borderWidth: 1 },
  skillText: { fontSize: 12, fontFamily: 'Poppins_500Medium' },
  lessonsCount: { fontSize: 13, fontFamily: 'Poppins_400Regular', marginBottom: 10 },
  lessonRow: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    borderWidth: 1, borderRadius: 12, padding: 12, marginBottom: 8,
  },
  lessonNum: { width: 32, height: 32, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
  lessonNumText: { fontSize: 13, fontFamily: 'Poppins_700Bold' },
  lessonInfo: { flex: 1 },
  lessonTitle: { fontSize: 13, fontFamily: 'Poppins_500Medium' },
  lessonDur: { fontSize: 12, fontFamily: 'Poppins_400Regular', marginTop: 2 },
  previewBadge: { paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6, borderWidth: 1 },
  previewText: { fontSize: 11, fontFamily: 'Poppins_600SemiBold' },
  footer: { borderTopWidth: 1, padding: 16 },
  footerContent: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  footerPrice: { fontSize: 22, fontFamily: 'Poppins_700Bold' },
  footerOriginal: { fontSize: 13, fontFamily: 'Poppins_400Regular', textDecorationLine: 'line-through' },
  enrollBtn: { borderRadius: 14, paddingHorizontal: 28, paddingVertical: 14 },
  enrollBtnText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },
  continueBtn: {
    flexDirection: 'row', gap: 8, alignItems: 'center', justifyContent: 'center',
    borderRadius: 14, paddingVertical: 14,
  },
  continueBtnText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },
});
