import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useAuth, UserRole } from '@/context/AuthContext';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';
import { Ionicons } from '@expo/vector-icons';
import { Logo } from '@/components/ui/Logo';

export default function RegisterScreen() {
  const router = useRouter();
  const { register } = useAuth();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [role, setRole] = useState<UserRole>('tenant');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  function validate() {
    const e: Record<string, string> = {};
    if (!name.trim()) e.name = 'Full name is required';
    if (!email.trim()) e.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(email)) e.email = 'Invalid email';
    if (!phone.trim()) e.phone = 'Phone number is required';
    if (!password) e.password = 'Password is required';
    else if (password.length < 6) e.password = 'Minimum 6 characters';
    if (password !== confirmPassword) e.confirmPassword = 'Passwords do not match';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function handleRegister() {
    if (!validate()) return;
    setLoading(true);
    try {
      await register({ name: name.trim(), email: email.trim(), phone: phone.trim(), password, role });
    } catch (err: any) {
      Alert.alert('Registration Failed', err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <SafeAreaView style={styles.safe}>
      <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
        <TouchableOpacity onPress={() => router.back()} style={styles.backBtn}>
          <Ionicons name="arrow-back" size={22} color={Colors.primary} />
        </TouchableOpacity>

        <Logo size={52} showName style={{ marginBottom: Spacing.sm }} />
        <Text style={styles.heading}>Create Account</Text>
        <Text style={styles.subheading}>Join ResiTrack today</Text>

        {/* Role Selector */}
        <View style={styles.roleContainer}>
          <Text style={styles.roleLabel}>I am a:</Text>
          <View style={styles.roleRow}>
            {(['tenant', 'landlord'] as UserRole[]).map((r) => (
              <TouchableOpacity
                key={r}
                onPress={() => setRole(r)}
                style={[styles.roleBtn, role === r && styles.roleBtnActive]}
              >
                <Ionicons
                  name={r === 'tenant' ? 'person-outline' : 'home-outline'}
                  size={20}
                  color={role === r ? Colors.textInverse : Colors.primary}
                />
                <Text style={[styles.roleBtnText, role === r && styles.roleBtnTextActive]}>
                  {r === 'tenant' ? 'Tenant' : 'Landlord'}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        <View style={styles.form}>
          <Input label="Full Name" placeholder="Juan Dela Cruz" value={name} onChangeText={setName} leftIcon="person-outline" error={errors.name} />
          <Input label="Email Address" placeholder="you@example.com" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" leftIcon="mail-outline" error={errors.email} />
          <Input label="Phone Number" placeholder="+63 9XX XXX XXXX" value={phone} onChangeText={setPhone} keyboardType="phone-pad" leftIcon="call-outline" error={errors.phone} />
          <Input label="Password" placeholder="Min. 6 characters" value={password} onChangeText={setPassword} isPassword leftIcon="lock-closed-outline" error={errors.password} />
          <Input label="Confirm Password" placeholder="Re-enter password" value={confirmPassword} onChangeText={setConfirmPassword} isPassword leftIcon="lock-closed-outline" error={errors.confirmPassword} />

          <Button title="Create Account" onPress={handleRegister} loading={loading} style={styles.registerBtn} />

          <TouchableOpacity onPress={() => router.back()} style={styles.loginLink}>
            <Text style={styles.loginText}>
              Already have an account? <Text style={styles.loginBold}>Sign in</Text>
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: Colors.background },
  scroll: { flexGrow: 1, padding: Spacing.lg },
  backBtn: { marginBottom: Spacing.md },
  heading: { fontSize: FontSize.xxxl, fontWeight: '800', color: Colors.primary },
  subheading: { fontSize: FontSize.md, color: Colors.textSecondary, marginBottom: Spacing.lg },
  roleContainer: { marginBottom: Spacing.md },
  roleLabel: { fontSize: FontSize.sm, fontWeight: '600', color: Colors.text, marginBottom: Spacing.sm },
  roleRow: { flexDirection: 'row', gap: Spacing.sm },
  roleBtn: {
    flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
    gap: Spacing.xs, paddingVertical: Spacing.sm + 2,
    borderRadius: Radius.md, borderWidth: 1.5, borderColor: Colors.primary,
    backgroundColor: Colors.surface,
  },
  roleBtnActive: { backgroundColor: Colors.primary },
  roleBtnText: { fontSize: FontSize.md, fontWeight: '600', color: Colors.primary },
  roleBtnTextActive: { color: Colors.textInverse },
  form: { backgroundColor: Colors.surface, borderRadius: Radius.xl, padding: Spacing.lg },
  registerBtn: { marginTop: Spacing.sm },
  loginLink: { alignItems: 'center', marginTop: Spacing.lg },
  loginText: { fontSize: FontSize.md, color: Colors.textSecondary },
  loginBold: { color: Colors.primary, fontWeight: '700' },
});
