import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { useQueryClient } from '@tanstack/react-query';
import { api } from '../../../services/api';

const ROLES = [
  { value: 'TECHNICIAN', label: 'Technician', desc: 'Field work & installations', color: '#059669', bg: '#F0FDF4' },
  { value: 'COLLECTOR',  label: 'Collector',  desc: 'Payments & remittances',    color: '#D97706', bg: '#FFFBEB' },
  { value: 'STAFF',      label: 'Staff',      desc: 'General access',            color: '#0891B2', bg: '#ECFEFF' },
  { value: 'ADMIN',      label: 'Admin',      desc: 'Full access + user mgmt',   color: '#7C3AED', bg: '#F5F3FF' },
];

export default function NewUserScreen() {
  const qc = useQueryClient();
  const [firstName, setFirstName] = useState('');
  const [lastName,  setLastName]  = useState('');
  const [email,     setEmail]     = useState('');
  const [phone,     setPhone]     = useState('');
  const [password,  setPassword]  = useState('');
  const [showPass,  setShowPass]  = useState(false);
  const [role,      setRole]      = useState('TECHNICIAN');
  const [loading,   setLoading]   = useState(false);

  const isValid = firstName.trim() && lastName.trim() && email.trim() && password.length >= 8;

  const submit = async () => {
    if (!isValid) return Alert.alert('Required', 'Please fill all required fields. Password must be at least 8 characters.');
    setLoading(true);
    try {
      await api.post('/api/v1/users', {
        firstName: firstName.trim(),
        lastName:  lastName.trim(),
        email:     email.trim().toLowerCase(),
        phone:     phone.trim() || undefined,
        password,
        role,
      });
      qc.invalidateQueries({ queryKey: ['users'] });
      Alert.alert('User Created!', `${firstName} ${lastName} can now log in with ${email.trim().toLowerCase()}`, [
        { text: 'Add Another', onPress: () => { setFirstName(''); setLastName(''); setEmail(''); setPhone(''); setPassword(''); } },
        { text: 'Done', onPress: () => router.back() },
      ]);
    } catch (e: any) {
      const msg = e?.response?.data?.message;
      Alert.alert('Error', Array.isArray(msg) ? msg.join('\n') : msg ?? 'Could not create user.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 12, paddingBottom: 20 }}>
          <TouchableOpacity onPress={() => router.back()} style={{ marginBottom: 12 }} activeOpacity={0.7}>
            <Text style={{ color: '#A5F3FC', fontSize: 17, fontWeight: '600' }}>← Back</Text>
          </TouchableOpacity>
          <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Add User</Text>
          <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>Create a new team member</Text>
        </View>

        <ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }} keyboardShouldPersistTaps="handled">
          {/* Name row */}
          <View style={{ flexDirection: 'row', marginBottom: 16 }}>
            <View style={{ flex: 1, marginRight: 8 }}>
              <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>First Name <Text style={{ color: '#DC2626' }}>*</Text></Text>
              <TextInput
                style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: '#0F172A' }}
                placeholder="Juan"
                placeholderTextColor="#94A3B8"
                value={firstName}
                onChangeText={setFirstName}
                autoCapitalize="words"
              />
            </View>
            <View style={{ flex: 1, marginLeft: 8 }}>
              <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>Last Name <Text style={{ color: '#DC2626' }}>*</Text></Text>
              <TextInput
                style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: '#0F172A' }}
                placeholder="Dela Cruz"
                placeholderTextColor="#94A3B8"
                value={lastName}
                onChangeText={setLastName}
                autoCapitalize="words"
              />
            </View>
          </View>

          {/* Email */}
          <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>Email <Text style={{ color: '#DC2626' }}>*</Text></Text>
          <TextInput
            style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: '#0F172A', marginBottom: 16 }}
            placeholder="juan@yourisp.com"
            placeholderTextColor="#94A3B8"
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            keyboardType="email-address"
            autoCorrect={false}
          />

          {/* Phone */}
          <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>
            Phone <Text style={{ fontSize: 14, fontWeight: '400', color: '#94A3B8' }}>(optional)</Text>
          </Text>
          <TextInput
            style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: '#0F172A', marginBottom: 16 }}
            placeholder="09171234567"
            placeholderTextColor="#94A3B8"
            value={phone}
            onChangeText={setPhone}
            keyboardType="phone-pad"
          />

          {/* Password */}
          <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>Password <Text style={{ color: '#DC2626' }}>*</Text></Text>
          <View style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, marginBottom: 6 }}>
            <TextInput
              style={{ flex: 1, paddingVertical: 14, fontSize: 16, color: '#0F172A' }}
              placeholder="Min. 8 characters"
              placeholderTextColor="#94A3B8"
              value={password}
              onChangeText={setPassword}
              secureTextEntry={!showPass}
            />
            <TouchableOpacity onPress={() => setShowPass(!showPass)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: '#0891B2' }}>{showPass ? 'Hide' : 'Show'}</Text>
            </TouchableOpacity>
          </View>
          <Text style={{ fontSize: 13, color: '#94A3B8', marginBottom: 20 }}>They can change this after first login.</Text>

          {/* Role */}
          <Text style={{ fontSize: 15, fontWeight: '700', color: '#0F172A', marginBottom: 12 }}>Role <Text style={{ color: '#DC2626' }}>*</Text></Text>
          {ROLES.map(r => (
            <TouchableOpacity
              key={r.value}
              onPress={() => setRole(r.value)}
              style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: role === r.value ? r.bg : '#FFF', borderRadius: 16, padding: 18, marginBottom: 10, borderWidth: 2, borderColor: role === r.value ? r.color : '#E2E8F0' }}
              activeOpacity={0.7}
            >
              <View style={{ width: 44, height: 44, borderRadius: 22, backgroundColor: role === r.value ? r.color : '#F1F5F9', alignItems: 'center', justifyContent: 'center', marginRight: 14 }}>
                <Text style={{ fontSize: 11, fontWeight: '800', color: role === r.value ? '#FFF' : '#94A3B8' }}>{r.value.slice(0,4)}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <Text style={{ fontSize: 16, fontWeight: '700', color: role === r.value ? r.color : '#0F172A' }}>{r.label}</Text>
                <Text style={{ fontSize: 14, color: '#64748B', marginTop: 2 }}>{r.desc}</Text>
              </View>
              <View style={{ width: 22, height: 22, borderRadius: 11, borderWidth: 2, borderColor: role === r.value ? r.color : '#CBD5E1', backgroundColor: role === r.value ? r.color : 'transparent', alignItems: 'center', justifyContent: 'center' }}>
                {role === r.value && <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: '#FFF' }} />}
              </View>
            </TouchableOpacity>
          ))}

          <View style={{ height: 16 }} />

          {/* Submit */}
          <TouchableOpacity
            style={{ backgroundColor: isValid ? '#0891B2' : '#CBD5E1', borderRadius: 14, paddingVertical: 18, alignItems: 'center' }}
            onPress={submit}
            disabled={loading || !isValid}
            activeOpacity={0.8}
          >
            {loading
              ? <ActivityIndicator color="#FFF" />
              : <Text style={{ color: '#FFF', fontSize: 17, fontWeight: '700' }}>Create User</Text>
            }
          </TouchableOpacity>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
}
