import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAuth } from '@/contexts/AuthContext';
import { useColors } from '@/hooks/useColors';

export default function RegisterScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { register } = useAuth();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isCreator, setIsCreator] = useState(false);
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);

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

  const handleRegister = async () => {
    if (!name.trim() || !email.trim() || !password.trim()) {
      Alert.alert('Missing fields', 'Please fill in all fields.');
      return;
    }
    setLoading(true);
    try {
      await register(name.trim(), email.trim(), password, isCreator);
        if (isCreator) {
          router.replace('/creator-guidelines?onboarding=1' as any);
        } else {
          router.replace('/(tabs)' as any);
        }
    } catch {
      Alert.alert('Error', 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <LinearGradient
        colors={['#FF3CAC22', '#7928CA11', '#00000000']}
        style={[StyleSheet.absoluteFillObject, { height: 280 }]}
        start={{ x: 1, y: 0 }}
        end={{ x: 0, y: 1 }}
      />

      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
        <ScrollView
          contentContainerStyle={[s.scroll, { paddingTop: topPad + 24, paddingBottom: bottomPad + 24 }]}
          keyboardShouldPersistTaps="handled"
        >
          <TouchableOpacity onPress={() => router.back()} style={s.backBtn}>
            <Ionicons name="arrow-back" size={22} color={colors.foreground} />
          </TouchableOpacity>

          <Text style={[s.heading, { color: colors.foreground }]}>Create Account</Text>
          <Text style={[s.sub, { color: colors.mutedForeground }]}>Join 50,000+ creators and learners</Text>

          <View style={s.roleToggle}>
            <TouchableOpacity
              onPress={() => setIsCreator(false)}
              style={[s.roleBtn, !isCreator && { backgroundColor: colors.primary, borderColor: colors.primary }]}
            >
              <Ionicons name="school-outline" size={18} color={!isCreator ? '#fff' : colors.mutedForeground} />
              <Text style={[s.roleBtnText, { color: !isCreator ? '#fff' : colors.mutedForeground }]}>I want to Learn</Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => setIsCreator(true)}
              style={[s.roleBtn, isCreator && { backgroundColor: '#FF3CAC', borderColor: '#FF3CAC' }]}
            >
              <Ionicons name="videocam-outline" size={18} color={isCreator ? '#fff' : colors.mutedForeground} />
              <Text style={[s.roleBtnText, { color: isCreator ? '#fff' : colors.mutedForeground }]}>I want to Create</Text>
            </TouchableOpacity>
          </View>

          <View style={s.form}>
            <View style={[s.inputWrap, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <Ionicons name="person-outline" size={18} color={colors.mutedForeground} />
              <TextInput
                style={[s.input, { color: colors.foreground }]}
                placeholder="Full Name"
                placeholderTextColor={colors.mutedForeground}
                value={name}
                onChangeText={setName}
                autoCapitalize="words"
              />
            </View>

            <View style={[s.inputWrap, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <Ionicons name="mail-outline" size={18} color={colors.mutedForeground} />
              <TextInput
                style={[s.input, { color: colors.foreground }]}
                placeholder="Email address"
                placeholderTextColor={colors.mutedForeground}
                value={email}
                onChangeText={setEmail}
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
              />
            </View>

            <View style={[s.inputWrap, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <Ionicons name="lock-closed-outline" size={18} color={colors.mutedForeground} />
              <TextInput
                style={[s.input, { color: colors.foreground }]}
                placeholder="Create password"
                placeholderTextColor={colors.mutedForeground}
                value={password}
                onChangeText={setPassword}
                secureTextEntry={!showPw}
              />
              <TouchableOpacity onPress={() => setShowPw(!showPw)}>
                <Ionicons name={showPw ? 'eye-off-outline' : 'eye-outline'} size={18} color={colors.mutedForeground} />
              </TouchableOpacity>
            </View>

            <TouchableOpacity
              onPress={handleRegister}
              style={[s.createBtn, { backgroundColor: isCreator ? '#FF3CAC' : colors.primary }]}
              disabled={loading}
              activeOpacity={0.85}
            >
              {loading ? <ActivityIndicator color="#fff" /> : (
                <Text style={s.createBtnText}>
                  {isCreator ? 'Start Creating' : 'Start Learning'}
                </Text>
              )}
            </TouchableOpacity>
          </View>

          <TouchableOpacity onPress={() => router.back()} style={s.loginLink}>
            <Text style={[s.loginLinkText, { color: colors.mutedForeground }]}>
              Already have an account?{' '}
              <Text style={{ color: colors.primary, fontFamily: 'Poppins_600SemiBold' }}>Sign In</Text>
            </Text>
          </TouchableOpacity>
        </ScrollView>
      </KeyboardAvoidingView>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  scroll: { flexGrow: 1, paddingHorizontal: 24 },
  backBtn: { marginBottom: 24 },
  heading: { fontSize: 28, fontFamily: 'Poppins_700Bold', marginBottom: 6 },
  sub: { fontSize: 14, fontFamily: 'Poppins_400Regular', marginBottom: 24 },
  roleToggle: { flexDirection: 'row', gap: 10, marginBottom: 24 },
  roleBtn: {
    flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
    gap: 8, paddingVertical: 13, borderRadius: 12, borderWidth: 1.5, borderColor: '#2A2A2A',
  },
  roleBtnText: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  form: { gap: 10 },
  inputWrap: {
    flexDirection: 'row', alignItems: 'center', gap: 10,
    borderWidth: 1, borderRadius: 12, paddingHorizontal: 14, paddingVertical: 13,
  },
  input: { flex: 1, fontSize: 15, fontFamily: 'Poppins_400Regular' },
  createBtn: {
    borderRadius: 14, paddingVertical: 16, alignItems: 'center', marginTop: 8,
    shadowOpacity: 0.4, shadowRadius: 12, elevation: 6,
  },
  createBtnText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },
  loginLink: { alignItems: 'center', marginTop: 24 },
  loginLinkText: { fontSize: 14, fontFamily: 'Poppins_400Regular' },
});
