import React, { useEffect, useMemo, useState } from 'react';
import { Alert, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, Image } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../context/AppContext';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { currency } from '../lib/format';
import { RootStackParamList } from '../navigation/types';
import { supabase } from '../lib/supabase';

const statusColor: Record<string, string> = {
  pendente: '#6366f1',
  confirmado: '#10b981',
  concluido: '#10b981',
  cancelado: '#ef4444',
};

const statusLabel: Record<string, string> = {
  pendente: 'Pendente',
  confirmado: 'Confirmado',
  concluido: 'Concluído',
  cancelado: 'Cancelado',
};

type ClientTab = 'favoritos' | 'agenda' | 'pedidos';
type BarberTab = 'reviews' | 'agenda_pessoal' | 'estatisticas';

export default function Profile() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const {
    user,
    appointments,
    orders,
    shops,
    favorites,
    logout,
    notifications,
    markNotificationRead,
    submitReview,
  } = useApp();

  const [activeTab, setActiveTab] = useState<string>(user?.role === 'barbearia' ? 'agenda_pessoal' : 'agenda');
  const [reviewedAppointments, setReviewedAppointments] = useState<Set<string>>(new Set());
  const [reviewTarget, setReviewTarget] = useState<{ appointmentId: string; shopId: string; shopName: string } | null>(null);
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [submittingReview, setSubmittingReview] = useState(false);
  const [shopReviews, setShopReviews] = useState<any[]>([]);

  const isBarber = user?.role === 'barbearia';
  const myShop = useMemo(() => shops.find(s => s.id === user?.shopId), [shops, user?.shopId]);

  useEffect(() => {
    let mounted = true;
    (async () => {
      if (!user) return;
      if (user.role === 'cliente') {
        const { data } = await supabase.from('reviews').select('appointment_id').eq('customer_id', user.id);
        if (!mounted || !data) return;
        setReviewedAppointments(new Set(data.map((row: any) => row.appointment_id).filter(Boolean)));
      } else if (user.role === 'barbearia' && user.shopId) {
        const { data } = await supabase.from('reviews').select('*').eq('shop_id', user.shopId).order('created_at', { ascending: false });
        if (!mounted || !data) return;
        setShopReviews(data);
      }
    })();
    return () => { mounted = false; };
  }, [user?.id]);

  const myAppointments = useMemo(
    () => (user ? (isBarber ? appointments.filter(a => a.shopId === user.shopId) : appointments.filter((a) => a.customerId === user.id)) : []),
    [appointments, user?.id, isBarber]
  );
  
  const myOrders = useMemo(
    () => (user ? orders.filter((o) => o.customerId === user.id) : []),
    [orders, user?.id]
  );
  
  const favoriteShops = useMemo(
    () => shops.filter((shop) => favorites.includes(shop.id)),
    [shops, favorites]
  );

  const myNotifications = useMemo(
    () =>
      user
        ? notifications
            .filter((n) => n.userId === user.id)
            .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
        : [],
    [notifications, user?.id]
  );

  if (!user) return null;

  const handleReviewSubmit = async () => {
    if (!reviewTarget || rating === 0) return;
    try {
      setSubmittingReview(true);
      await submitReview(reviewTarget.shopId, reviewTarget.appointmentId, rating, comment);
      setReviewedAppointments((prev) => new Set([...prev, reviewTarget.appointmentId]));
      setReviewTarget(null);
      Alert.alert('Obrigado', 'A tua avaliação foi enviada.');
    } catch (e: any) {
      Alert.alert('Erro', e?.message || 'Erro ao enviar avaliação.');
    } finally {
      setSubmittingReview(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        {/* Header Perfil */}
        <View style={styles.profileHeader}>
          <View style={styles.avatarBox}>
            <Text style={styles.avatarText}>{user.name.charAt(0).toUpperCase()}</Text>
          </View>
          <View style={styles.profileInfo}>
            <Text style={styles.profileName}>{user.name}</Text>
            <Text style={styles.profileEmail}>{user.email}</Text>
            <View style={styles.roleBadge}>
              <Text style={styles.roleText}>{isBarber ? 'Gestor de Espaço' : 'Cliente'}</Text>
            </View>
          </View>
          <TouchableOpacity onPress={logout} style={styles.logoutBtn}>
            <Text style={styles.logoutIcon}>⎗</Text>
          </TouchableOpacity>
        </View>

        {/* Notificações (Horizontal) */}
        {myNotifications.length > 0 && (
          <View style={styles.notifSection}>
            <Text style={styles.sectionTitle}>Notificações</Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.notifScroll}>
              {myNotifications.map((n) => (
                <View key={n.id} style={[styles.notifCard, !n.read && styles.notifUnread]}>
                  <Text style={styles.notifMsg} numberOfLines={2}>{n.message}</Text>
                  {!n.read && (
                    <TouchableOpacity onPress={() => markNotificationRead(n.id)}>
                      <Text style={styles.markRead}>Marcar lida</Text>
                    </TouchableOpacity>
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        )}

        {/* Tabs Role-Based */}
        <View style={styles.tabBar}>
          {(isBarber ? [
            ['agenda_pessoal', 'Agenda Global'],
            ['reviews', 'Avaliações'],
            ['estatisticas', 'Resumo'],
          ] : [
            ['agenda', 'Minha Agenda'],
            ['favoritos', 'Favoritos'],
            ['pedidos', 'Compras'],
          ]).map(([id, label]) => (
            <TouchableOpacity
              key={id}
              onPress={() => setActiveTab(id)}
              style={[styles.tabItem, activeTab === id && styles.tabActive]}
            >
              <Text style={[styles.tabText, activeTab === id && styles.tabTextActive]}>{label}</Text>
              {activeTab === id && <View style={styles.tabIndicator} />}
            </TouchableOpacity>
          ))}
        </View>

        {/* Conteúdo das Tabs */}
        <View style={styles.tabContent}>
          {/* CLIENTE TABS */}
          {activeTab === 'agenda' && (
            <View style={styles.listContainer}>
              {myAppointments.length > 0 ? (
                myAppointments.map((appt) => {
                  const shop = shops.find((s) => s.id === appt.shopId);
                  const canReview = appt.status === 'concluido' && !reviewedAppointments.has(appt.id);
                  const dateParts = appt.date.split(' ');
                  return (
                    <Card key={appt.id} style={styles.agendaCard}>
                      <View style={styles.agendaTop}>
                        <View style={styles.dateBox}>
                          <Text style={styles.dateDay}>{dateParts[0].split('-')[2]}</Text>
                          <Text style={styles.dateMonth}>{new Date(dateParts[0]).toLocaleString('pt-PT', { month: 'short' }).toUpperCase()}</Text>
                        </View>
                        <View style={styles.agendaMain}>
                          <Text style={styles.agendaShop} numberOfLines={1}>{shop?.name || 'Barbearia'}</Text>
                          <Text style={styles.agendaTime}>{dateParts[1]} · {currency(appt.total)}</Text>
                        </View>
                        <View style={[styles.statusTag, { backgroundColor: statusColor[appt.status] + '20' }]}>
                          <Text style={[styles.statusText, { color: statusColor[appt.status] }]}>{statusLabel[appt.status]}</Text>
                        </View>
                      </View>
                      {canReview && (
                        <Button variant="outline" size="sm" style={styles.reviewBtn} onPress={() => setReviewTarget({ appointmentId: appt.id, shopId: appt.shopId, shopName: shop?.name || 'Barbearia' })}>
                          Avaliar Serviço
                        </Button>
                      )}
                    </Card>
                  );
                })
              ) : <Text style={styles.emptyTxt}>Sem marcações agendadas.</Text>}
            </View>
          )}

          {activeTab === 'favoritos' && (
            <View style={styles.listContainer}>
              {favoriteShops.map(s => (
                <TouchableOpacity key={s.id} onPress={() => navigation.navigate('ShopDetails', { shopId: s.id })}>
                  <Card style={styles.shopCard}>
                    <View style={styles.shopIcon}><Text style={styles.shopIconText}>{s.name.charAt(0)}</Text></View>
                    <View style={{ flex: 1 }}><Text style={styles.shopName}>{s.name}</Text><Text style={styles.shopAddr} numberOfLines={1}>{s.address}</Text></View>
                    <Text style={styles.shopRating}>★ {s.rating.toFixed(1)}</Text>
                  </Card>
                </TouchableOpacity>
              ))}
            </View>
          )}

          {/* BARBER TABS */}
          {activeTab === 'agenda_pessoal' && (
            <View style={styles.listContainer}>
              <Text style={styles.subTitle}>Todas as marcações do espaço</Text>
              {myAppointments.map(appt => (
                <Card key={appt.id} style={styles.agendaCard}>
                   <View style={styles.agendaTop}>
                    <View style={styles.dateBox}>
                      <Text style={styles.dateDay}>{appt.date.split(' ')[0].split('-')[2]}</Text>
                      <Text style={styles.dateMonth}>{new Date(appt.date.split(' ')[0]).toLocaleString('pt-PT', { month: 'short' }).toUpperCase()}</Text>
                    </View>
                    <View style={styles.agendaMain}>
                      <Text style={styles.agendaShop}>{appt.date.split(' ')[1]}</Text>
                      <Text style={styles.agendaTime}>Status: {statusLabel[appt.status]}</Text>
                    </View>
                  </View>
                </Card>
              ))}
            </View>
          )}

          {activeTab === 'reviews' && (
            <View style={styles.listContainer}>
              {shopReviews.map(r => (
                <Card key={r.id} style={styles.reviewCard}>
                  <View style={styles.reviewHeader}>
                    <Text style={styles.reviewStars}>{'★'.repeat(r.rating)}</Text>
                    <Text style={styles.reviewDate}>{new Date(r.created_at).toLocaleDateString()}</Text>
                  </View>
                  <Text style={styles.reviewComment}>{r.comment || 'Sem comentário.'}</Text>
                </Card>
              ))}
            </View>
          )}

          {activeTab === 'estatisticas' && (
             <View style={styles.listContainer}>
                <Card style={styles.statCard}>
                   <Text style={styles.statLabel}>Total de Marcações</Text>
                   <Text style={styles.statValue}>{myAppointments.length}</Text>
                </Card>
                <Card style={styles.statCard}>
                   <Text style={styles.statLabel}>Rating Médio</Text>
                   <Text style={styles.statValue}>{myShop?.rating.toFixed(1)} ★</Text>
                </Card>
                <Card style={styles.statCard}>
                   <Text style={styles.statLabel}>Vendas em Produtos</Text>
                   <Text style={styles.statValue}>{currency(myOrders.reduce((sum, o) => sum + o.total, 0))}</Text>
                </Card>
             </View>
          )}
        </View>

        {/* Review Modal for Clients */}
        {reviewTarget && (
          <Card style={styles.reviewModal}>
            <Text style={styles.reviewTitle}>Avaliar {reviewTarget.shopName}</Text>
            <View style={styles.stars}>
              {[1,2,3,4,5].map(s => (
                <TouchableOpacity key={s} onPress={() => setRating(s)}>
                  <Text style={[styles.star, rating >= s && styles.starActive]}>★</Text>
                </TouchableOpacity>
              ))}
            </View>
            <TextInput style={styles.reviewInput} placeholder="Diz-nos o que achaste..." placeholderTextColor="#475569" multiline value={comment} onChangeText={setComment} />
            <View style={styles.reviewActions}>
              <Button variant="ghost" onPress={() => setReviewTarget(null)} style={{ flex: 1 }}>Cancelar</Button>
              <Button onPress={handleReviewSubmit} loading={submittingReview} disabled={rating === 0} style={{ flex: 2 }}>Enviar</Button>
            </View>
          </Card>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#0a0a0f' },
  content: { padding: 20, paddingBottom: 100 },
  profileHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 32, gap: 16 },
  avatarBox: { width: 64, height: 64, borderRadius: 22, backgroundColor: '#141420', alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: 'rgba(99,102,241,0.3)' },
  avatarText: { color: '#818cf8', fontSize: 24, fontWeight: '900' },
  profileInfo: { flex: 1, gap: 2 },
  profileName: { color: '#f8fafc', fontSize: 22, fontWeight: '900' },
  profileEmail: { color: '#64748b', fontSize: 14, fontWeight: '500' },
  roleBadge: { alignSelf: 'flex-start', backgroundColor: 'rgba(99,102,241,0.1)', borderRadius: 8, paddingHorizontal: 8, paddingVertical: 3, marginTop: 4 },
  roleText: { color: '#818cf8', fontSize: 10, fontWeight: '800', textTransform: 'uppercase' },
  logoutBtn: { padding: 8 },
  logoutIcon: { color: '#ef4444', fontSize: 24, fontWeight: '700' },
  sectionTitle: { color: '#f8fafc', fontSize: 18, fontWeight: '800', marginBottom: 12 },
  notifSection: { marginBottom: 32 },
  notifScroll: { marginHorizontal: -20, paddingHorizontal: 20 },
  notifCard: { backgroundColor: '#141420', width: 240, borderRadius: 16, padding: 14, marginRight: 12, borderWidth: 1, borderColor: 'rgba(255,255,255,0.06)', gap: 8 },
  notifUnread: { borderColor: 'rgba(99,102,241,0.4)' },
  notifMsg: { color: '#94a3b8', fontSize: 13, lineHeight: 18 },
  markRead: { color: '#818cf8', fontSize: 12, fontWeight: '700' },
  tabBar: { flexDirection: 'row', marginBottom: 24, borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,0.06)' },
  tabItem: { paddingVertical: 12, marginRight: 24, position: 'relative' },
  tabActive: {},
  tabText: { color: '#475569', fontSize: 15, fontWeight: '700' },
  tabTextActive: { color: '#a5b4fc' },
  tabIndicator: { position: 'absolute', bottom: -1, left: 0, right: 0, height: 2, backgroundColor: '#6366f1', borderRadius: 2 },
  tabContent: { minHeight: 200 },
  listContainer: { gap: 12 },
  emptyTxt: { color: '#475569', textAlign: 'center', marginTop: 20 },
  subTitle: { color: '#64748b', fontSize: 13, fontWeight: '700', textTransform: 'uppercase', marginBottom: 8 },
  agendaCard: { padding: 14, gap: 12 },
  agendaTop: { flexDirection: 'row', alignItems: 'center', gap: 12 },
  dateBox: { backgroundColor: '#1c1c2e', padding: 8, borderRadius: 12, alignItems: 'center', minWidth: 50 },
  dateDay: { color: '#f8fafc', fontSize: 18, fontWeight: '900' },
  dateMonth: { color: '#6366f1', fontSize: 10, fontWeight: '800' },
  agendaMain: { flex: 1, gap: 2 },
  agendaShop: { color: '#f8fafc', fontSize: 16, fontWeight: '800' },
  agendaTime: { color: '#64748b', fontSize: 13 },
  statusTag: { paddingHorizontal: 10, paddingVertical: 5, borderRadius: 10 },
  statusText: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase' },
  reviewBtn: { marginTop: 4 },
  shopCard: { flexDirection: 'row', alignItems: 'center', gap: 12, padding: 12 },
  shopIcon: { width: 44, height: 44, borderRadius: 12, backgroundColor: 'rgba(255,255,255,0.03)', alignItems: 'center', justifyContent: 'center' },
  shopIconText: { color: '#475569', fontSize: 18, fontWeight: '800' },
  shopName: { color: '#f8fafc', fontSize: 16, fontWeight: '800' },
  shopAddr: { color: '#475569', fontSize: 12 },
  shopRating: { color: '#fbbf24', fontWeight: '800', fontSize: 13 },
  reviewCard: { padding: 16, gap: 8 },
  reviewHeader: { flexDirection: 'row', justifyContent: 'space-between' },
  reviewStars: { color: '#fbbf24', fontSize: 14 },
  reviewDate: { color: '#475569', fontSize: 11 },
  reviewComment: { color: '#f8fafc', fontSize: 13, lineHeight: 18 },
  statCard: { padding: 20, alignItems: 'center', gap: 4 },
  statLabel: { color: '#64748b', fontSize: 12, fontWeight: '700', textTransform: 'uppercase' },
  statValue: { color: '#f8fafc', fontSize: 24, fontWeight: '900' },
  reviewModal: { marginTop: 24, padding: 20, gap: 16, borderColor: 'rgba(99,102,241,0.3)' },
  reviewTitle: { color: '#f8fafc', fontSize: 16, fontWeight: '800', textAlign: 'center' },
  stars: { flexDirection: 'row', justifyContent: 'center', gap: 8 },
  star: { fontSize: 32, color: '#1c1c2e' },
  starActive: { color: '#fbbf24' },
  reviewInput: { backgroundColor: '#1c1c2e', borderRadius: 14, padding: 12, color: '#f8fafc', height: 80, textAlignVertical: 'top' },
  reviewActions: { flexDirection: 'row', gap: 12 },
});
