import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router, useLocalSearchParams } from 'expo-router';
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 { VideoCard } from '@/components/VideoCard';
import { useColors } from '@/hooks/useColors';
import { COURSES, CREATORS, VIDEOS, formatCount } from '@/data/mockData';

export default function CreatorProfileScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const [tab, setTab] = useState<'videos' | 'courses'>('videos');
  const [following, setFollowing] = useState(false);

  const creator = CREATORS.find((c) => c.id === id);
  const creatorVideos = VIDEOS.filter((v) => v.creatorId === id);
  const creatorCourses = COURSES.filter((c) => c.creatorId === id);

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

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

  const statsData = [
    { label: 'Followers', value: formatCount(creator.followers) },
    { label: 'Courses', value: creator.coursesCount.toString() },
    { label: 'Videos', value: creatorVideos.length.toString() },
  ];

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <ScrollView contentContainerStyle={[s.scroll, { paddingBottom: bottomPad + 40 }]} showsVerticalScrollIndicator={false}>
        <LinearGradient
          colors={[creator.avatarColor, creator.avatarColor + '66', 'transparent']}
          style={[s.headerGrad, { paddingTop: topPad + 8 }]}
          start={{ x: 0, y: 0 }}
          end={{ x: 0, y: 1 }}
        >
          <TouchableOpacity onPress={() => router.back()} style={s.backBtn}>
            <Ionicons name="arrow-back" size={22} color="#fff" />
          </TouchableOpacity>
        </LinearGradient>

        <View style={s.profileSection}>
          <View style={[s.avatar, { backgroundColor: creator.avatarColor }]}>
            <Text style={s.avatarText}>{creator.avatarInitials}</Text>
            {creator.isVerified && (
              <View style={[s.verifiedBadge, { backgroundColor: colors.background }]}>
                <Ionicons name="checkmark-circle" size={20} color={colors.primary} />
              </View>
            )}
          </View>

          <Text style={[s.name, { color: colors.foreground }]}>{creator.name}</Text>
          <Text style={[s.username, { color: colors.mutedForeground }]}>@{creator.username}</Text>
          <Text style={[s.specialty, { color: colors.primary }]}>{creator.specialty}</Text>
          <Text style={[s.bio, { color: colors.mutedForeground }]}>{creator.bio}</Text>

          <View style={s.statsRow}>
            {statsData.map((stat, i) => (
              <React.Fragment key={stat.label}>
                <View style={s.statItem}>
                  <Text style={[s.statVal, { color: colors.foreground }]}>{stat.value}</Text>
                  <Text style={[s.statLabel, { color: colors.mutedForeground }]}>{stat.label}</Text>
                </View>
                {i < statsData.length - 1 && <View style={[s.statDiv, { backgroundColor: colors.border }]} />}
              </React.Fragment>
            ))}
          </View>

          <View style={s.actionRow}>
            <TouchableOpacity
              onPress={() => setFollowing(!following)}
              style={[
                s.followBtn,
                following
                  ? { backgroundColor: 'transparent', borderColor: colors.primary }
                  : { backgroundColor: colors.primary },
              ]}
              activeOpacity={0.85}
            >
              <Text style={[s.followBtnText, { color: following ? colors.primary : '#fff' }]}>
                {following ? 'Following' : 'Follow'}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity style={[s.messageBtn, { borderColor: colors.border, backgroundColor: colors.card }]}>
              <Ionicons name="chatbubble-outline" size={18} color={colors.foreground} />
            </TouchableOpacity>
          </View>
        </View>

        <View style={[s.tabRow, { borderColor: colors.border }]}>
          <TouchableOpacity
            onPress={() => setTab('videos')}
            style={[s.tabBtn, tab === 'videos' && { borderBottomColor: colors.primary, borderBottomWidth: 2 }]}
          >
            <Ionicons name="play-circle-outline" size={18} color={tab === 'videos' ? colors.primary : colors.mutedForeground} />
            <Text style={[s.tabText, { color: tab === 'videos' ? colors.primary : colors.mutedForeground }]}>Shorts</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => setTab('courses')}
            style={[s.tabBtn, tab === 'courses' && { borderBottomColor: colors.primary, borderBottomWidth: 2 }]}
          >
            <Ionicons name="book-outline" size={18} color={tab === 'courses' ? colors.primary : colors.mutedForeground} />
            <Text style={[s.tabText, { color: tab === 'courses' ? colors.primary : colors.mutedForeground }]}>Courses</Text>
          </TouchableOpacity>
        </View>

        {tab === 'videos' ? (
          <View style={s.videosGrid}>
            {creatorVideos.map((video) => (
              <TouchableOpacity
                key={video.id}
                onPress={() => {}}
                style={s.videoThumbWrap}
                activeOpacity={0.85}
              >
                <LinearGradient
                  colors={video.gradientColors}
                  style={s.videoThumb}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="play-circle" size={32} color="rgba(255,255,255,0.7)" />
                  <View style={s.videoDuration}>
                    <Text style={s.videoDurationText}>{video.duration}</Text>
                  </View>
                </LinearGradient>
                <Text style={[s.videoTitle, { color: colors.foreground }]} numberOfLines={2}>{video.title}</Text>
                <Text style={[s.videoLikes, { color: colors.mutedForeground }]}>{formatCount(video.likes)} likes</Text>
              </TouchableOpacity>
            ))}
          </View>
        ) : (
          <View style={s.coursesSection}>
            {creatorCourses.length === 0 ? (
              <View style={s.emptyState}>
                <Ionicons name="book-outline" size={40} color={colors.mutedForeground} />
                <Text style={[s.emptyText, { color: colors.mutedForeground }]}>No courses yet</Text>
              </View>
            ) : (
              creatorCourses.map((course) => <CourseCard key={course.id} course={course} />)
            )}
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  scroll: {},
  headerGrad: { height: 120, paddingHorizontal: 16 },
  backBtn: {},
  profileSection: { paddingHorizontal: 16, alignItems: 'center', marginTop: -40, gap: 6 },
  avatar: {
    width: 90, height: 90, borderRadius: 45,
    alignItems: 'center', justifyContent: 'center',
    borderWidth: 3, borderColor: '#fff',
    elevation: 8,
  },
  avatarText: { color: '#fff', fontSize: 30, fontFamily: 'Poppins_700Bold' },
  verifiedBadge: { position: 'absolute', bottom: 0, right: 0, borderRadius: 10 },
  name: { fontSize: 22, fontFamily: 'Poppins_700Bold', marginTop: 8 },
  username: { fontSize: 14, fontFamily: 'Poppins_400Regular' },
  specialty: { fontSize: 13, fontFamily: 'Poppins_600SemiBold', marginTop: 2 },
  bio: { fontSize: 13, fontFamily: 'Poppins_400Regular', textAlign: 'center', lineHeight: 20, paddingHorizontal: 16, marginTop: 4 },
  statsRow: { flexDirection: 'row', alignItems: 'center', gap: 0, marginVertical: 12 },
  statItem: { alignItems: 'center', paddingHorizontal: 24, gap: 2 },
  statVal: { fontSize: 20, fontFamily: 'Poppins_700Bold' },
  statLabel: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  statDiv: { width: 1, height: 36 },
  actionRow: { flexDirection: 'row', gap: 12, marginTop: 4, marginBottom: 8 },
  followBtn: { borderRadius: 22, paddingHorizontal: 36, paddingVertical: 12, borderWidth: 1.5 },
  followBtnText: { fontSize: 15, fontFamily: 'Poppins_700Bold' },
  messageBtn: { width: 46, height: 46, borderRadius: 23, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
  tabRow: { flexDirection: 'row', borderBottomWidth: 1, marginTop: 8 },
  tabBtn: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6, paddingVertical: 14 },
  tabText: { fontSize: 14, fontFamily: 'Poppins_600SemiBold' },
  videosGrid: { flexDirection: 'row', flexWrap: 'wrap', padding: 8, gap: 8 },
  videoThumbWrap: { width: '47%', gap: 4 },
  videoThumb: { height: 140, borderRadius: 12, alignItems: 'center', justifyContent: 'center' },
  videoDuration: {
    position: 'absolute', bottom: 8, right: 8,
    backgroundColor: 'rgba(0,0,0,0.5)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4,
  },
  videoDurationText: { color: '#fff', fontSize: 11, fontFamily: 'Poppins_500Medium' },
  videoTitle: { fontSize: 12, fontFamily: 'Poppins_500Medium' },
  videoLikes: { fontSize: 11, fontFamily: 'Poppins_400Regular' },
  coursesSection: { padding: 16 },
  emptyState: { alignItems: 'center', paddingVertical: 40, gap: 10 },
  emptyText: { fontSize: 14, fontFamily: 'Poppins_400Regular' },
});
