import React, { useEffect, useState } from 'react';
import {
  View, Text, TextInput, TouchableOpacity,
  StyleSheet, Alert, ActivityIndicator, ScrollView,
} from 'react-native';
import { fetchProfile, updateProfile, logout } from '../../services/api';
import { User } from '../../types';

export default function ProfileScreen({ navigation }: any) {
  const [user, setUser]       = useState<User | null>(null);
  const [name, setName]       = useState('');
  const [phone, setPhone]     = useState('');
  const [address, setAddress] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving]   = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const data = await fetchProfile();
        setUser(data);
        setName(data.name || '');
        setPhone(data.phone || '');
        setAddress(data.address || '');
      } catch {
        Alert.alert('Error', 'Could not load profile.');
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const handleSave = async () => {
    if (!name.trim()) { Alert.alert('Error', 'Name is required.'); return; }
    setSaving(true);
    try {
      const updated = await updateProfile({ name: name.trim(), phone: phone.trim(), address: address.trim() });
      setUser(updated);
      Alert.alert('Saved!', 'Profile updated successfully.');
    } catch (err: any) {
      Alert.alert('Error', err?.response?.data?.error || 'Update failed.');
    } finally {
      setSaving(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigation.replace('Login');
  };

  if (loading) return <ActivityIndicator color="#f97316" size="large" style={styles.loader} />;

  return (
    <ScrollView style={styles.bg} contentContainerStyle={styles.container}>
      <Text style={styles.title}>👤 My Profile</Text>
      <View style={styles.emailCard}>
        <Text style={styles.emailLabel}>Email (cannot change)</Text>
        <Text style={styles.emailValue}>{user?.email}</Text>
        <View style={[styles.roleBadge, user?.role === 'admin' ? styles.adminBadge : styles.customerBadge]}>
          <Text style={styles.roleText}>{user?.role?.toUpperCase()}</Text>
        </View>
      </View>

      <Text style={styles.label}>Full Name *</Text>
      <TextInput style={styles.input} value={name} onChangeText={setName} placeholder="Your name" placeholderTextColor="#64748b" />

      <Text style={styles.label}>Phone Number</Text>
      <TextInput style={styles.input} value={phone} onChangeText={setPhone} placeholder="Phone number" placeholderTextColor="#64748b" keyboardType="phone-pad" />

      <Text style={styles.label}>Default Address</Text>
      <TextInput
        style={[styles.input, { minHeight: 80 }]}
        value={address} onChangeText={setAddress}
        placeholder="Your delivery address"
        placeholderTextColor="#64748b"
        multiline
      />

      <TouchableOpacity style={styles.saveBtn} onPress={handleSave} disabled={saving}>
        {saving ? <ActivityIndicator color="#fff" /> : <Text style={styles.saveBtnText}>Save Changes</Text>}
      </TouchableOpacity>

      <TouchableOpacity style={styles.logoutBtn} onPress={handleLogout}>
        <Text style={styles.logoutText}>🚪 Logout</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  bg:             { flex: 1, backgroundColor: '#0f172a' },
  container:      { padding: 20 },
  loader:         { flex: 1, backgroundColor: '#0f172a' },
  title:          { fontSize: 22, fontWeight: '800', color: '#fff', marginBottom: 16 },
  emailCard:      { backgroundColor: '#1e293b', borderRadius: 12, padding: 16, marginBottom: 20 },
  emailLabel:     { fontSize: 12, color: '#64748b', marginBottom: 4 },
  emailValue:     { fontSize: 16, color: '#fff', fontWeight: '600' },
  roleBadge:      { borderRadius: 6, paddingHorizontal: 10, paddingVertical: 3, alignSelf: 'flex-start', marginTop: 8 },
  adminBadge:     { backgroundColor: 'rgba(249,115,22,0.2)' },
  customerBadge:  { backgroundColor: 'rgba(59,130,246,0.2)' },
  roleText:       { color: '#f97316', fontWeight: '700', fontSize: 11 },
  label:          { color: '#94a3b8', fontSize: 13, marginBottom: 6 },
  input:          {
    backgroundColor: '#1e293b', borderRadius: 10, padding: 14,
    color: '#fff', marginBottom: 14, fontSize: 15,
    borderWidth: 1, borderColor: '#334155',
  },
  saveBtn:        { backgroundColor: '#f97316', borderRadius: 12, padding: 16, alignItems: 'center', marginBottom: 12 },
  saveBtnText:    { color: '#fff', fontSize: 16, fontWeight: '700' },
  logoutBtn:      { backgroundColor: '#1e293b', borderRadius: 12, padding: 16, alignItems: 'center', borderWidth: 1, borderColor: '#ef4444' },
  logoutText:     { color: '#ef4444', fontSize: 16, fontWeight: '700' },
});
