import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import { Feather } from '@expo/vector-icons';
import { ArrowLeft } from 'lucide-react-native';
import { router } from "expo-router";
import MenuItem from '@/components/MenuItem';

import { getAuth, signOut } from "firebase/auth";
import { getFirestore, doc, getDoc, collection, query, where, getDocs } from "firebase/firestore";

const ProfileCard = ({ cafeName, cafeAddress, city, phone }: { cafeName: string, cafeAddress: string, city: string, phone: string }) => (
  <View style={styles.profileCard}>
    <View style={styles.profileHeader}>
      <View style={styles.profileTitle}>
        <Feather name="coffee" size={20} color="#B45309" />
        <Text style={styles.cafeName}>{cafeName || "Nom De Café"}</Text>
      </View>
      <View style={styles.badge}>
        <Text style={styles.badgeText}>Validé</Text>
      </View>
    </View>
    <View style={styles.profileInfo}>
      <Feather name="map-pin" size={16} color="#4B5563" />
      <Text style={styles.infoText}>{cafeAddress || "Adresse Du Café"}, {city}</Text>
    </View>
    <View style={styles.profileInfo}>
      <Feather name="phone" size={16} color="#4B5563" />
      <Text style={styles.infoText}>+216 {phone || "+216 00 000 000"}</Text>
    </View>
  </View>
);

const handleSignOut = () => {
  Alert.alert(
    "Déconnexion",
    "Êtes-vous sûr de vouloir vous déconnecter ?",
    [
      { text: "Annuler", style: "cancel" },
      {
        text: "Déconnexion",
        style: "destructive",
        onPress: async () => {
          try {
            const auth = getAuth();
            await signOut(auth);
            router.replace('/');
          } catch (error) {
            Alert.alert("Erreur", "Impossible de se déconnecter.");
          }
        }
      }
    ]
  );
};

export default function ProfileScreen() {
  const [cafeName, setCafeName] = useState('');
  const [cafeAddress, setCafeAddress] = useState('');
  const [city, setCity] = useState('');
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchProfileData = async () => {
      try {
        setLoading(true);
        const auth = getAuth();
        const db = getFirestore();
        const user = auth.currentUser;

        if (!user) {
          setError("Utilisateur non connecté.");
          return;
        }

        const userDoc = await getDoc(doc(db, 'users', user.uid));
        if (userDoc.exists()) {
          const userData = userDoc.data();
          setPhone(userData.phone || '');
        } else {
          setError("Données utilisateur non trouvées.");
        }

        const q = query(collection(db, 'coffee_shops'), where('ownerId', '==', user.uid));
        const querySnapshot = await getDocs(q);
        if (!querySnapshot.empty) {
          const cafeData = querySnapshot.docs[0].data();
          setCafeName(cafeData.cafeName || '');
          setCafeAddress(cafeData.cafeAddress || '');
          setCity(cafeData.city || '');
        } else {
          setError("Aucune information de café trouvée.");
        }

      } catch (error) {
        setError("Erreur lors du chargement des données.");
      } finally {
        setLoading(false);
      }
    };

    fetchProfileData();
  }, []);

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <ActivityIndicator size="large" color="#B45309" />
          <Text style={{ marginTop: 12 }}>Chargement des données...</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (error) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
          <Text style={{ color: 'red', fontSize: 16, textAlign: 'center' }}>{error}</Text>
          <TouchableOpacity onPress={() => router.back()} style={{ marginTop: 20 }}>
            <Text style={{ color: '#2563EB' }}>Retour</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaProvider>
      <SafeAreaView style={styles.container}>
        <ScrollView>
          <View style={styles.header}>
            <TouchableOpacity style={styles.backButton} onPress={() => router.back()}>
              <ArrowLeft size={24} color="#666" />
            </TouchableOpacity>
            <Text style={styles.headerTitle}>Espace Personnel</Text>
          </View>

          <ProfileCard cafeName={cafeName} cafeAddress={cafeAddress} city={city} phone={phone} />

          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Commandes</Text>
            <MenuItem icon="clock" label="Historique d'achats" onPress={() => router.push('/screens/user/OrderHistoryScreen')} />
          </View>

          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Paramètres</Text>
            <MenuItem icon="bell" label="Notifications" badge={2}/>
          </View>

          <TouchableOpacity style={styles.logoutButton} onPress={handleSignOut}>
            <Feather name="log-out" size={20} color="#EF4444" />
            <Text style={styles.logoutText}>Déconnexion</Text>
          </TouchableOpacity>
        </ScrollView>
      </SafeAreaView>
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    marginTop: 5,
  },
  backButton: {
    position: 'absolute',
    left: 20,
    top: '50%',
    transform: [{ translateY: -12 }],
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: '#333',
  },
  profileCard: {
    backgroundColor: '#f8f3e9',
    borderRadius: 12,
    padding: 20,
    marginBottom: 32,
    marginVertical: 25,
    marginHorizontal: 15,
  },
  profileHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 15,
  },
  profileTitle: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  cafeName: {
    fontSize: 16,
    fontWeight: '700',
    color: '#1F2937',
  },
  badge: {
    backgroundColor: '#10B981',
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 9999,
  },
  badgeText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '500',
  },
  profileInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 8,
  },
  infoText: {
    fontSize: 14,
    color: '#4B5563',
  },
  section: {
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#1F2937',
    marginBottom: 8,
    marginHorizontal: 15
  },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingVertical: 16,
    marginHorizontal: 15
  },
  logoutText: {
    color: '#EF4444',
    fontSize: 15,
    fontWeight: '500',
  },
});
