import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useState } from 'react';
import { Alert, Platform, ScrollView, StyleSheet, Switch, 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 } from '@/data/mockData';

interface SettingsRowProps {
  icon: string;
  label: string;
  value?: string;
  isSwitch?: boolean;
  switchValue?: boolean;
  onSwitchChange?: (v: boolean) => void;
  danger?: boolean;
  onPress?: () => void;
}

function SettingsRow({ icon, label, value, isSwitch, switchValue, onSwitchChange, danger, onPress }: SettingsRowProps) {
  const colors = useColors();
  return (
    <TouchableOpacity
      onPress={onPress}
      style={[s.settingsRow, { borderBottomColor: colors.border }]}
      activeOpacity={onPress ? 0.7 : 1}
      disabled={!onPress && !isSwitch}
    >
      <View style={[s.settingsIcon, { backgroundColor: danger ? '#ef444422' : colors.secondary }]}>
        <Ionicons name={icon as any} size={18} color={danger ? colors.destructive : colors.primary} />
      </View>
      <Text style={[s.settingsLabel, { color: danger ? colors.destructive : colors.foreground }]}>{label}</Text>
      <View style={{ flex: 1 }} />
      {value && <Text style={[s.settingsValue, { color: colors.mutedForeground }]}>{value}</Text>}
      {isSwitch && <Switch value={switchValue} onValueChange={onSwitchChange} trackColor={{ true: colors.primary }} />}
      {!isSwitch && onPress && <Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />}
    </TouchableOpacity>
  );
}

export default function ProfileScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { user, logout, switchRole } = useAuth();
  const [notifications, setNotifications] = useState(true);

  const topPad = Platform.OS === 'web' ? 67 : insets.top;
  const enrolledCount = user?.enrolledCourseIds.length ?? 0;
  const enrolledCourses = COURSES.filter((c) => user?.enrolledCourseIds.includes(c.id));

  const handleLogout = () => {
    Alert.alert('Sign Out', 'Are you sure you want to sign out?', [
      { text: 'Cancel', style: 'cancel' },
      { text: 'Sign Out', style: 'destructive', onPress: logout },
    ]);
  };

  const handleSwitchRole = () => {
    const next = !user?.isCreator;
    const label = next ? 'Creator' : 'Learner';
    Alert.alert(
      `Switch to ${label}?`,
      next
        ? 'You will get access to creator tools and can upload courses and earn money.'
        : 'You will switch to learner mode. You can still switch back anytime.',
      [
        { text: 'Cancel', style: 'cancel' },
        { text: `Switch to ${label}`, onPress: () => switchRole(next) },
      ]
    );
  };

  const stats = [
    { label: 'Courses', value: enrolledCount.toString() },
    { label: 'Completed', value: '0' },
    { label: 'Certificates', value: '0' },
  ];

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

        <View style={s.profileCard}>
          <LinearGradient
            colors={['#FF6B3522', '#FF3CAC11']}
            style={[s.profileCardBg, { borderColor: colors.border }]}
          >
            <View style={[s.avatar, { backgroundColor: user?.avatarColor ?? colors.primary }]}>
              <Text style={s.avatarText}>{user?.avatarInitials ?? '?'}</Text>
            </View>
            <View style={s.profileInfo}>
              <Text style={[s.profileName, { color: colors.foreground }]}>{user?.name}</Text>
              <Text style={[s.profileEmail, { color: colors.mutedForeground }]}>{user?.email}</Text>
              <View style={[s.roleBadge, { backgroundColor: user?.isCreator ? '#FF3CAC22' : colors.primary + '22', borderColor: user?.isCreator ? '#FF3CAC55' : colors.primary + '55' }]}>
                <Ionicons name={user?.isCreator ? 'videocam' : 'school'} size={12} color={user?.isCreator ? '#FF3CAC' : colors.primary} />
                <Text style={[s.roleBadgeText, { color: user?.isCreator ? '#FF3CAC' : colors.primary }]}>
                  {user?.isCreator ? 'Creator' : 'Learner'}
                </Text>
              </View>
            </View>
          </LinearGradient>
        </View>

        <View style={[s.statsRow, { backgroundColor: colors.card, borderColor: colors.border }]}>
          {stats.map((stat, i) => (
            <React.Fragment key={stat.label}>
              <View style={s.statItem}>
                <Text style={[s.statValue, { color: colors.primary }]}>{stat.value}</Text>
                <Text style={[s.statLabel, { color: colors.mutedForeground }]}>{stat.label}</Text>
              </View>
              {i < stats.length - 1 && <View style={[s.statDivider, { backgroundColor: colors.border }]} />}
            </React.Fragment>
          ))}
        </View>

        {enrolledCourses.length > 0 && (
          <>
            <Text style={[s.sectionTitle, { color: colors.foreground }]}>My Courses</Text>
            {enrolledCourses.map((course) => (
              <View key={course.id} style={[s.courseRow, { backgroundColor: colors.card, borderColor: colors.border }]}>
                <LinearGradient colors={course.gradientColors} style={s.courseThumb} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }}>
                  <Ionicons name="play-circle" size={24} color="rgba(255,255,255,0.8)" />
                </LinearGradient>
                <View style={s.courseRowInfo}>
                  <Text style={[s.courseRowTitle, { color: colors.foreground }]} numberOfLines={2}>{course.title}</Text>
                  <View style={[s.progTrack, { backgroundColor: colors.border }]}>
                    <View style={[s.progFill, { width: `${user?.courseProgress[course.id] ?? 0}%` as any, backgroundColor: colors.primary }]} />
                  </View>
                  <Text style={[s.progLabel, { color: colors.mutedForeground }]}>{user?.courseProgress[course.id] ?? 0}% complete</Text>
                </View>
              </View>
            ))}
          </>
        )}

        {user?.isCreator && (
          <>
            <Text style={[s.sectionTitle, { color: colors.foreground }]}>Creator</Text>
            <View style={[s.settingsCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <SettingsRow icon="cash-outline" label="Earnings & Payouts" value="₦384K" onPress={() => router.push('/earnings' as any)} />
              <SettingsRow icon="bar-chart-outline" label="Analytics" onPress={() => router.push('/earnings' as any)} />
            </View>
          </>
        )}

        {/* Switch Role Card */}
        <View style={[s.switchRoleCard, { backgroundColor: user?.isCreator ? '#FF3CAC0D' : '#FF6B350D', borderColor: user?.isCreator ? '#FF3CAC44' : '#FF6B3544' }]}>
          <View style={s.switchRoleLeft}>
            <Ionicons name={user?.isCreator ? 'videocam' : 'school'} size={22} color={user?.isCreator ? '#FF3CAC' : colors.primary} />
            <View>
              <Text style={[s.switchRoleTitle, { color: colors.foreground }]}>
                You are a <Text style={{ color: user?.isCreator ? '#FF3CAC' : colors.primary }}>{user?.isCreator ? 'Creator' : 'Learner'}</Text>
              </Text>
              <Text style={[s.switchRoleSub, { color: colors.mutedForeground }]}>
                Switch to {user?.isCreator ? 'Learner' : 'Creator'} mode anytime
              </Text>
            </View>
          </View>
          <TouchableOpacity
            onPress={handleSwitchRole}
            style={[s.switchRoleBtn, { borderColor: user?.isCreator ? '#FF3CAC' : colors.primary }]}
            activeOpacity={0.8}
          >
            <Ionicons name="swap-horizontal" size={14} color={user?.isCreator ? '#FF3CAC' : colors.primary} />
            <Text style={[s.switchRoleBtnText, { color: user?.isCreator ? '#FF3CAC' : colors.primary }]}>
              Switch
            </Text>
          </TouchableOpacity>
        </View>

        <Text style={[s.sectionTitle, { color: colors.foreground }]}>Settings</Text>
        <View style={[s.settingsCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <SettingsRow icon="notifications-outline" label="Notifications" isSwitch switchValue={notifications} onSwitchChange={setNotifications} />
          <SettingsRow icon="shield-checkmark-outline" label="Privacy" onPress={() => {}} />
          <SettingsRow icon="help-circle-outline" label="Help & Support" onPress={() => {}} />
          <SettingsRow icon="information-circle-outline" label="About" value="v1.0" onPress={() => {}} />
          <SettingsRow icon="log-out-outline" label="Sign Out" danger onPress={handleLogout} />
        </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: 20 },
  profileCard: { marginBottom: 16 },
  profileCardBg: {
    borderRadius: 20, borderWidth: 1, padding: 20,
    flexDirection: 'row', alignItems: 'center', gap: 16,
  },
  avatar: { width: 68, height: 68, borderRadius: 34, alignItems: 'center', justifyContent: 'center' },
  avatarText: { color: '#fff', fontSize: 24, fontFamily: 'Poppins_700Bold' },
  profileInfo: { flex: 1, gap: 4 },
  profileName: { fontSize: 18, fontFamily: 'Poppins_700Bold' },
  profileEmail: { fontSize: 13, fontFamily: 'Poppins_400Regular' },
  roleBadge: { flexDirection: 'row', alignItems: 'center', gap: 4, alignSelf: 'flex-start', paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6, borderWidth: 1 },
  roleBadgeText: { fontSize: 11, fontFamily: 'Poppins_600SemiBold' },
  statsRow: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around',
    borderRadius: 16, borderWidth: 1, padding: 16, marginBottom: 24,
  },
  statItem: { alignItems: 'center', gap: 2 },
  statValue: { fontSize: 22, fontFamily: 'Poppins_700Bold' },
  statLabel: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  statDivider: { width: 1, height: 36 },
  sectionTitle: { fontSize: 17, fontFamily: 'Poppins_700Bold', marginBottom: 12 },
  courseRow: {
    flexDirection: 'row', gap: 12, alignItems: 'center',
    borderRadius: 14, borderWidth: 1, padding: 12, marginBottom: 10,
  },
  courseThumb: { width: 60, height: 60, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  courseRowInfo: { flex: 1, gap: 6 },
  courseRowTitle: { fontSize: 13, fontFamily: 'Poppins_600SemiBold', lineHeight: 18 },
  progTrack: { height: 4, borderRadius: 2, overflow: 'hidden' },
  progFill: { height: '100%', borderRadius: 2 },
  progLabel: { fontSize: 11, fontFamily: 'Poppins_400Regular' },
  switchRoleCard: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    borderRadius: 16, borderWidth: 1.5, padding: 16, marginBottom: 24,
  },
  switchRoleLeft: { flexDirection: 'row', alignItems: 'center', gap: 12, flex: 1 },
  switchRoleTitle: { fontSize: 14, fontFamily: 'Poppins_600SemiBold', marginBottom: 2 },
  switchRoleSub: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  switchRoleBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 5,
    paddingHorizontal: 12, paddingVertical: 8, borderRadius: 20, borderWidth: 1.5,
  },
  switchRoleBtnText: { fontSize: 12, fontFamily: 'Poppins_600SemiBold' },
  settingsCard: { borderRadius: 16, borderWidth: 1, overflow: 'hidden' },
  settingsRow: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1,
  },
  settingsIcon: { width: 32, height: 32, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
  settingsLabel: { fontSize: 14, fontFamily: 'Poppins_500Medium' },
  settingsValue: { fontSize: 13, fontFamily: 'Poppins_400Regular' },
});
