import { Ionicons } from '@expo/vector-icons';
import React, { useState } from 'react';
import { Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { CourseCard } from '@/components/CourseCard';
import { useAuth } from '@/contexts/AuthContext';
import { useColors } from '@/hooks/useColors';
import { CATEGORIES, COURSES } from '@/data/mockData';

const TABS = ['All', 'My Courses', 'Bookmarked'];

export default function CoursesScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState('All');
  const [selectedCat, setSelectedCat] = useState('all');

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

  const enrolledCourses = COURSES.filter((c) => user?.enrolledCourseIds.includes(c.id));

  const filteredCourses = COURSES.filter((c) => {
    const matchesCat = selectedCat === 'all' || c.categoryId === selectedCat;
    if (activeTab === 'My Courses') return user?.enrolledCourseIds.includes(c.id) && matchesCat;
    return matchesCat;
  });

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <ScrollView
        contentContainerStyle={[s.scroll, { paddingTop: topPad + 16 }]}
        showsVerticalScrollIndicator={false}
      >
        <Text style={[s.heading, { color: colors.foreground }]}>Learn</Text>

        <View style={s.tabRow}>
          {TABS.map((tab) => (
            <TouchableOpacity
              key={tab}
              onPress={() => setActiveTab(tab)}
              style={[
                s.tab,
                activeTab === tab && { backgroundColor: colors.primary, borderColor: colors.primary },
                { borderColor: colors.border },
              ]}
              activeOpacity={0.75}
            >
              <Text style={[s.tabText, { color: activeTab === tab ? '#fff' : colors.mutedForeground }]}>
                {tab}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        {activeTab === 'All' && (
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.catScroll}>
            {[{ id: 'all', name: 'All' }, ...CATEGORIES.slice(1)].map((cat) => (
              <TouchableOpacity
                key={cat.id}
                onPress={() => setSelectedCat(cat.id)}
                style={[
                  s.catPill,
                  selectedCat === cat.id
                    ? { backgroundColor: colors.primary, borderColor: colors.primary }
                    : { backgroundColor: colors.card, borderColor: colors.border },
                ]}
              >
                <Text style={[s.catPillText, { color: selectedCat === cat.id ? '#fff' : colors.mutedForeground }]}>
                  {cat.name}
                </Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        )}

        {activeTab === 'My Courses' && enrolledCourses.length === 0 ? (
          <View style={s.emptyState}>
            <Ionicons name="book-outline" size={48} color={colors.mutedForeground} />
            <Text style={[s.emptyTitle, { color: colors.foreground }]}>No courses yet</Text>
            <Text style={[s.emptyDesc, { color: colors.mutedForeground }]}>
              Enroll in a course to start your learning journey
            </Text>
            <TouchableOpacity onPress={() => setActiveTab('All')} style={[s.browseBtn, { backgroundColor: colors.primary }]}>
              <Text style={s.browseBtnText}>Browse Courses</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <View style={s.coursesList}>
            {filteredCourses.map((course) => (
              <CourseCard
                key={course.id}
                course={course}
                progress={user?.courseProgress[course.id]}
              />
            ))}
          </View>
        )}

        <View style={{ height: Platform.OS === 'web' ? 100 : 80 }} />
      </ScrollView>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  scroll: { paddingHorizontal: 16 },
  heading: { fontSize: 26, fontFamily: 'Poppins_700Bold', marginBottom: 16 },
  tabRow: { flexDirection: 'row', gap: 8, marginBottom: 16 },
  tab: { paddingHorizontal: 16, paddingVertical: 8, borderRadius: 20, borderWidth: 1 },
  tabText: { fontSize: 13, fontFamily: 'Poppins_500Medium' },
  catScroll: { gap: 8, paddingRight: 4, marginBottom: 16 },
  catPill: { paddingHorizontal: 14, paddingVertical: 7, borderRadius: 20, borderWidth: 1 },
  catPillText: { fontSize: 12, fontFamily: 'Poppins_500Medium' },
  coursesList: { gap: 2 },
  emptyState: { alignItems: 'center', paddingVertical: 60, gap: 12 },
  emptyTitle: { fontSize: 18, fontFamily: 'Poppins_600SemiBold' },
  emptyDesc: { fontSize: 14, fontFamily: 'Poppins_400Regular', textAlign: 'center' },
  browseBtn: { marginTop: 8, paddingHorizontal: 24, paddingVertical: 12, borderRadius: 24 },
  browseBtnText: { color: '#fff', fontSize: 14, fontFamily: 'Poppins_600SemiBold' },
});
