import { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { CustomerFlowNav } from '../components/customer-flow-nav';
import { useCustomerSession } from '../src/store/session';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerProfileScreen() {
  const { profile, address, bootstrap, initialized, loading, saving, error, clearError, saveProfile } = useCustomerSession();
  const { mode, setMode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const [fullName, setFullName] = useState(profile.fullName);
  const [saved, setSaved] = useState('');

  useEffect(() => {
    if (!initialized) {
      void bootstrap();
    }
  }, [bootstrap, initialized]);

  useEffect(() => {
    setFullName(profile.fullName);
  }, [profile.fullName]);

  const handleSave = async () => {
    await saveProfile({ fullName });
    setSaved('Nome do cliente atualizado.');
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
        <CustomerFlowNav />
        <View style={[styles.hero, { backgroundColor: theme.surface }]}>
          <Text style={[styles.kicker, { color: theme.accent }]}>Perfil do cliente</Text>
          <Text style={[styles.title, { color: theme.text }]}>Edite os dados da sua conta.</Text>
          <Text style={[styles.copy, { color: theme.textMuted }]}>Aqui o cliente altera o nome e escolhe entre o modo claro e o escuro.</Text>
        </View>

        <View style={[styles.card, { backgroundColor: theme.surface }]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>Tema do app</Text>
          <View style={styles.themeRow}>
            <TouchableOpacity onPress={() => setMode('light')} style={[styles.themeButton, { backgroundColor: mode === 'light' ? theme.accent : theme.surfaceMuted }]}>
              <Text style={[styles.themeButtonText, { color: mode === 'light' ? theme.accentText : theme.text }]}>Claro</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => setMode('dark')} style={[styles.themeButton, { backgroundColor: mode === 'dark' ? theme.accent : theme.surfaceMuted }]}>
              <Text style={[styles.themeButtonText, { color: mode === 'dark' ? theme.accentText : theme.text }]}>Escuro</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={[styles.card, { backgroundColor: theme.surface }]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>Dados da conta</Text>
          <Text style={[styles.label, { color: theme.textSoft }]}>Nome</Text>
          <TextInput value={fullName} onChangeText={setFullName} style={[styles.input, { borderColor: theme.cardBorder, backgroundColor: theme.surfaceMuted, color: theme.text }]} placeholder="Nome completo" placeholderTextColor={theme.textSoft} />

          <Text style={[styles.label, { color: theme.textSoft }]}>E-mail</Text>
          <Text style={[styles.value, { color: theme.textMuted }]}>{profile.email}</Text>
          <Text style={[styles.label, { color: theme.textSoft }]}>Telefone</Text>
          <Text style={[styles.value, { color: theme.textMuted }]}>{profile.phone}</Text>

          {loading ? <Text style={[styles.helper, { color: theme.textSoft }]}>Carregando dados da conta...</Text> : null}
          {error ? <Text style={styles.errorText}>{error}</Text> : null}

          <TouchableOpacity onPress={() => void handleSave()} style={[styles.saveButton, { backgroundColor: theme.accent }]} disabled={saving}>
            <Text style={[styles.saveButtonText, { color: theme.accentText }]}>{saving ? 'Salvando...' : 'Salvar nome da conta'}</Text>
          </TouchableOpacity>
          {error ? <Text onPress={clearError} style={styles.clearText}>Fechar aviso</Text> : null}
          {saved ? <Text style={styles.successText}>{saved}</Text> : null}
        </View>

        <View style={[styles.card, { backgroundColor: theme.surface }]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>Endereco padrao</Text>
          <Text style={[styles.value, { color: theme.textMuted }]}>{`${address.street}, ${address.number} | ${address.neighborhood} | ${address.city}`}</Text>
          <Text style={[styles.helper, { color: theme.textSoft }]}>{`${address.complement || 'Sem complemento'} | CEP ${address.zipCode}`}</Text>
          <Text style={[styles.helper, { color: theme.textSoft }]}>Abra a tela Enderecos para editar a localizacao de entrega.</Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  content: { padding: 20, gap: 16 },
  hero: { borderRadius: 26, padding: 22 },
  kicker: { fontSize: 11, letterSpacing: 3, textTransform: 'uppercase', fontWeight: '700' },
  title: { marginTop: 12, fontSize: 28, lineHeight: 32, fontWeight: '800' },
  copy: { marginTop: 12, fontSize: 14, lineHeight: 22 },
  card: { borderRadius: 22, padding: 18 },
  sectionTitle: { fontSize: 18, fontWeight: '800' },
  label: { marginTop: 10, fontSize: 12, textTransform: 'uppercase', fontWeight: '700' },
  value: { marginTop: 4, fontSize: 16, fontWeight: '700' },
  helper: { marginTop: 8, fontSize: 13, lineHeight: 20 },
  input: { marginTop: 6, borderRadius: 16, borderWidth: 1, paddingHorizontal: 14, paddingVertical: 12, fontSize: 15 },
  themeRow: { marginTop: 14, flexDirection: 'row', gap: 10 },
  themeButton: { flex: 1, borderRadius: 16, paddingVertical: 12, alignItems: 'center' },
  themeButtonText: { fontSize: 13, fontWeight: '800' },
  saveButton: { marginTop: 16, borderRadius: 999, paddingHorizontal: 18, paddingVertical: 14 },
  saveButtonText: { textAlign: 'center', fontWeight: '900' },
  errorText: { marginTop: 10, fontSize: 13, color: '#FCA5A5', fontWeight: '700' },
  clearText: { marginTop: 8, fontSize: 13, color: '#FDBA74', fontWeight: '700' },
  successText: { marginTop: 10, fontSize: 13, color: '#34D399', fontWeight: '700' },
});
