import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { useTheme } from '@/constants/ThemeContext';
import {
  ArrowLeft,
  User,
  Mail,
  Phone,
  Lock,
  Eye,
  EyeOff,
} from 'lucide-react-native';

import { FacebookIcon, GoogleIcon, AppleIcon } from '@/components/SocialIcons';
import styles from '@/styles/auth/register.styles';
import authService from '@/services/auth';

export default function RegisterScreen() {
  const router = useRouter();
  const { isDark } = useTheme();

  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const getPasswordStrength = (pwd: string) => {
    if (!pwd) return { label: '', color: '#E2E8F0', ratio: 0 };
    let score = 0;
    if (pwd.length >= 6) score += 1;
    if (pwd.length >= 8) score += 1;
    if (/[0-9]/.test(pwd)) score += 1;
    if (/[^A-Za-z0-9]/.test(pwd) || (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd))) score += 1;

    if (score <= 1) return { label: 'Password strength weak', color: '#EF4444', ratio: 0.25 };
    if (score === 2) return { label: 'Password strength fair', color: '#F59E0B', ratio: 0.5 };
    if (score === 3) return { label: 'Password strength good', color: '#38BDF8', ratio: 0.75 };
    return { label: 'Password strength strong', color: '#22C55E', ratio: 1.0 };
  };

  const strength = getPasswordStrength(password);

  const handleRegister = async () => {
    setError(null);

    if (!fullName.trim() || !email.trim() || !phone.trim() || !password) {
      setError('Please fill in all fields.');
      return;
    }

    if (password.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }

    if (password !== confirmPassword) {
      setError('Passwords do not match.');
      return;
    }

    try {
      setLoading(true);

      const res = await authService.register({
        full_name: fullName.trim(),
        email: email.trim().toLowerCase(),
        phone_number: phone.trim(),
        password,
        password_confirmation: confirmPassword,
      });

      if (res.status === 'success') {
        // Pass the email to the verification screen via params
        router.replace({
          pathname: '/(auth)/verify-account',
          params: { email: email.trim().toLowerCase() },
        } as any);
      } else {
        setError(res.message || 'Registration failed. Please try again.');
      }


    } catch (e: any) {
      console.error('Register error:', e);
      setError('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = () => {
    router.push('/(auth)/login' as any);
  };

  return (
    <SafeAreaView
      style={[styles.safeArea, { backgroundColor: isDark ? '#050E24' : '#FFFFFF' }]}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
          activeOpacity={0.7}
        >
          <ArrowLeft size={20} color={isDark ? '#FFFFFF' : '#0C1C3E'} />
          <Text style={[styles.backText, { color: isDark ? '#FFFFFF' : '#0C1C3E' }]}>
            Back
          </Text>
        </TouchableOpacity>

        <View style={styles.headerContainer}>
          <Text style={[styles.title, { color: isDark ? '#FFFFFF' : '#0C1C3E' }]}>
            create account
          </Text>
          <Text style={[styles.subtitle, { color: isDark ? '#94A3B8' : '#64748B' }]}>
            Join travelcam and explore cameroon
          </Text>
        </View>

        <View style={styles.formContainer}>
          {error && (
            <View
              style={{
                backgroundColor: '#FEE2E2',
                padding: 12,
                borderRadius: 8,
                marginBottom: 16,
              }}
            >
              <Text style={{ color: '#991B1B', fontSize: 13 }}>{error}</Text>
            </View>
          )}

          {/* Full Name */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#475569' }]}>
                Full Name
              </Text>
              <User size={15} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0B1F4D' : '#FFFFFF',
                  borderColor: isDark ? '#1E408A' : '#E2E8F0',
                },
              ]}
            >
              <TextInput
                value={fullName}
                onChangeText={setFullName}
                placeholder="Enter your full name"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
            </View>
          </View>

          {/* Email */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#475569' }]}>
                Email
              </Text>
              <Mail size={15} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0B1F4D' : '#FFFFFF',
                  borderColor: isDark ? '#1E408A' : '#E2E8F0',
                },
              ]}
            >
              <TextInput
                value={email}
                onChangeText={setEmail}
                placeholder="Enter your email"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                keyboardType="email-address"
                autoCapitalize="none"
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
            </View>
          </View>

          {/* Phone */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#475569' }]}>
                Phone number
              </Text>
              <Phone size={15} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0B1F4D' : '#FFFFFF',
                  borderColor: isDark ? '#1E408A' : '#E2E8F0',
                },
              ]}
            >
              <TextInput
                value={phone}
                onChangeText={setPhone}
                placeholder="Enter your phone number"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                keyboardType="phone-pad"
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
            </View>
          </View>

          {/* Password */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#475569' }]}>
                Password
              </Text>
              <Lock size={15} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0B1F4D' : '#FFFFFF',
                  borderColor: isDark ? '#1E408A' : '#E2E8F0',
                },
              ]}
            >
              <TextInput
                value={password}
                onChangeText={setPassword}
                placeholder="Enter your password"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                secureTextEntry={!showPassword}
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
              <TouchableOpacity onPress={() => setShowPassword(!showPassword)}>
                {showPassword ? (
                  <EyeOff size={18} color="#64748B" />
                ) : (
                  <Eye size={18} color="#64748B" />
                )}
              </TouchableOpacity>
            </View>

            {password.length > 0 && (
              <View style={{ marginTop: 10 }}>
                <View
                  style={{
                    height: 5,
                    backgroundColor: isDark ? '#1E293B' : '#E2E8F0',
                    borderRadius: 3,
                    overflow: 'hidden',
                  }}
                >
                  <View
                    style={{
                      height: '100%',
                      width: `${strength.ratio * 100}%`,
                      backgroundColor: strength.color,
                    }}
                  />
                </View>
                <Text
                  style={{
                    fontSize: 12,
                    color: strength.color,
                    marginTop: 6,
                    fontWeight: '600',
                    textAlign: 'center',
                  }}
                >
                  {strength.label}
                </Text>
              </View>
            )}
          </View>

          {/* Confirm Password */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#475569' }]}>
                Confirm Password
              </Text>
              <Lock size={15} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0B1F4D' : '#FFFFFF',
                  borderColor: isDark ? '#1E408A' : '#E2E8F0',
                },
              ]}
            >
              <TextInput
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                placeholder="Confirm your password"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                secureTextEntry={!showPassword}
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
            </View>
          </View>

          {/* Submit */}
          <TouchableOpacity
            style={[styles.submitButton, loading && { opacity: 0.7 }]}
            onPress={handleRegister}
            disabled={loading}
            activeOpacity={0.88}
          >
            {loading ? (
              <ActivityIndicator color="#FFFFFF" />
            ) : (
              <Text style={styles.submitButtonText}>Create account</Text>
            )}
          </TouchableOpacity>

          {/* Divider */}
          <View style={styles.dividerRow}>
            <View style={styles.dividerLine} />
            <Text style={styles.dividerText}>Or connect using</Text>
            <View style={styles.dividerLine} />
          </View>

          {/* Social Row */}
          <View style={styles.socialRow}>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={handleLogin}
              activeOpacity={0.8}
            >
              <FacebookIcon />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={handleLogin}
              activeOpacity={0.8}
            >
              <GoogleIcon />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={handleLogin}
              activeOpacity={0.8}
            >
              <AppleIcon />
            </TouchableOpacity>
          </View>

          {/* Login redirect */}
          <TouchableOpacity
            onPress={handleLogin}
            style={styles.loginRedirect}
            activeOpacity={0.7}
          >
            <Text
              style={[styles.loginRedirectText, { color: isDark ? '#94A3B8' : '#475569' }]}
            >
              Already have an account?{' '}
              <Text style={{ color: '#0099FF', fontWeight: '700' }}>Log In</Text>
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}