import React, { useMemo, useState } from 'react';
import { Alert, Image, Linking, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { RouteProp, useNavigation, useRoute } 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';

type Tab = 'servicos' | 'barbeiros' | 'produtos' | 'detalhes';

const defaultSchedule = [
  { day: 'Segunda-feira', open: '09:00', close: '19:30' },
  { day: 'Terça-feira', open: '09:00', close: '19:30' },
  { day: 'Quarta-feira', open: '09:00', close: '19:30' },
  { day: 'Quinta-feira', open: '09:00', close: '19:30' },
  { day: 'Sexta-feira', open: '09:00', close: '19:30' },
  { day: 'Sábado', open: '09:00', close: '19:00' },
  { day: 'Domingo', open: '', close: '', closed: true },
];

export default function ShopDetails() {
  const route = useRoute<RouteProp<RootStackParamList, 'ShopDetails'>>();
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const { shopId } = route.params;
  const { shops, shopsReady, addToCart, user, toggleFavorite, isFavorite } = useApp();
  const shop = useMemo(() => shops.find((s) => s.id === shopId), [shops, shopId]);
  const [tab, setTab] = useState<Tab>('servicos');

  if (!shopsReady && !shop) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.centerState}>
          <Text style={styles.centerTitle}>Carregando...</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (!shop) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.centerState}>
          <Text style={styles.centerTitle}>Não encontrado</Text>
          <Button onPress={() => navigation.navigate('Explore')}>Voltar</Button>
        </View>
      </SafeAreaView>
    );
  }

  const openMap = () => {
    const url = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(`${shop.name} ${shop.address}`)}`;
    Linking.openURL(url);
  };

  const reserveService = (serviceId?: string) => {
    if (!user) { navigation.navigate('Login'); return; }
    navigation.navigate('Booking', { shopId: shop.id, serviceId });
  };

  const addProduct = (productId: string) => {
    if (!user) { navigation.navigate('Login'); return; }
    addToCart({ shopId: shop.id, type: 'product', refId: productId, qty: 1 });
    Alert.alert('Sucesso', 'Produto adicionado ao carrinho.');
  };

  const schedule = shop.schedule || defaultSchedule;
  const currentDayIndex = new Date().getDay() === 0 ? 6 : new Date().getDay() - 1;

  return (
    <View style={styles.container}>
      <ScrollView bounces={false} contentContainerStyle={styles.scrollContent}>
        {/* Imagem Hero e Overlay */}
        <View style={styles.hero}>
          {shop.imageUrl ? (
            <Image source={{ uri: shop.imageUrl }} style={styles.heroImage} />
          ) : (
            <View style={styles.heroPlaceholder}><Text style={styles.heroPlaceholderText}>💈</Text></View>
          )}
          <View style={styles.heroOverlay} />
          
          <SafeAreaView style={styles.heroHeader}>
            <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backBtn}>
              <Text style={styles.backIcon}>←</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => toggleFavorite(shop.id)} style={styles.favBtn}>
              <Text style={[styles.favIcon, isFavorite(shop.id) && styles.favActive]}>
                {isFavorite(shop.id) ? '♥' : '♡'}
              </Text>
            </TouchableOpacity>
          </SafeAreaView>

          <View style={styles.heroBody}>
            <View style={styles.ratingBox}>
              <Text style={styles.ratingValue}>★ {shop.rating.toFixed(1)}</Text>
            </View>
            <Text style={styles.shopName}>{shop.name}</Text>
            <TouchableOpacity onPress={openMap} style={styles.addrBox}>
              <Text style={styles.shopAddr} numberOfLines={2}>📍 {shop.address}</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Tabs Estilizadas */}
        <View style={styles.tabSection}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.tabsScroll}>
            {[
              ['servicos', 'Serviços'],
              ['barbeiros', 'Equipa'],
              ['produtos', 'Loja'],
              ['detalhes', 'Sobre'],
            ].map(([id, label]) => (
              <TouchableOpacity
                key={id}
                onPress={() => setTab(id as Tab)}
                style={[styles.tabItem, tab === id && styles.tabItemActive]}
              >
                <Text style={[styles.tabText, tab === id && styles.tabTextActive]}>{label}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        {/* Listagem de Conteúdo */}
        <View style={styles.contentArea}>
          {tab === 'servicos' && (
            <View style={styles.grid}>
              {shop.services.map((s) => (
                <Card key={s.id} style={styles.serviceCard}>
                  <View style={styles.svcInfo}>
                    <Text style={styles.svcName}>{s.name}</Text>
                    <Text style={styles.svcMeta}>{s.duration} min · {currency(s.price)}</Text>
                  </View>
                  <Button size="sm" onPress={() => reserveService(s.id)}>Agendar</Button>
                </Card>
              ))}
            </View>
          )}

          {tab === 'barbeiros' && (
            <View style={styles.barberList}>
              {shop.barbers.map((b) => (
                <Card key={b.id} style={styles.barberCard}>
                  <View style={styles.barberAvatar}>
                    <Text style={styles.avatarTxt}>{b.name.charAt(0)}</Text>
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.barberName}>{b.name}</Text>
                    <Text style={styles.barberSpecs}>{b.specialties.join(', ')}</Text>
                  </View>
                </Card>
              ))}
            </View>
          )}

          {tab === 'produtos' && (
            <View style={styles.grid}>
              {shop.products.map((p) => (
                <Card key={p.id} style={styles.productCard}>
                  <View style={styles.prodHeader}>
                    <Text style={styles.prodName}>{p.name}</Text>
                    <Text style={styles.prodPrice}>{currency(p.price)}</Text>
                  </View>
                  <Text style={styles.prodStock}>{p.stock} em stock</Text>
                  <Button size="sm" variant="outline" onPress={() => addProduct(p.id)} disabled={p.stock <= 0}>
                    {p.stock > 0 ? 'Adicionar' : 'Esgotado'}
                  </Button>
                </Card>
              ))}
            </View>
          )}

          {tab === 'detalhes' && (
            <Card style={styles.detailsBox}>
              <Text style={styles.detailTitle}>Horário</Text>
              {schedule.map((s, idx) => (
                <View key={s.day} style={styles.schedRow}>
                  <Text style={[styles.schedDay, idx === currentDayIndex && styles.today]}>{s.day}</Text>
                  <Text style={[styles.schedTime, idx === currentDayIndex && styles.today]}>
                    {s.closed ? 'Fechado' : `${s.open} - ${s.close}`}
                  </Text>
                </View>
              ))}
              <View style={styles.divider} />
              <Text style={styles.detailTitle}>Contacto</Text>
              <TouchableOpacity onPress={() => Linking.openURL(`tel:${shop.contacts?.phone1}`)}>
                <Text style={styles.contactLink}>{shop.contacts?.phone1 || 'Não disponível'}</Text>
              </TouchableOpacity>
            </Card>
          )}
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a0a0f',
  },
  scrollContent: {
    paddingBottom: 40,
  },
  hero: {
    height: 380,
    position: 'relative',
  },
  heroImage: {
    width: '100%',
    height: '100%',
  },
  heroPlaceholder: {
    width: '100%',
    height: '100%',
    backgroundColor: '#141420',
    alignItems: 'center',
    justifyContent: 'center',
  },
  heroPlaceholderText: {
    fontSize: 64,
  },
  heroOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(10,10,15,0.5)',
  },
  heroHeader: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingTop: 10,
  },
  backBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(255,255,255,0.1)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  backIcon: {
    color: '#fff',
    fontSize: 20,
    fontWeight: '700',
  },
  favBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(255,255,255,0.1)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  favIcon: {
    color: '#fff',
    fontSize: 22,
  },
  favActive: {
    color: '#ef4444',
  },
  heroBody: {
    position: 'absolute',
    bottom: 30,
    left: 20,
    right: 20,
    gap: 10,
  },
  ratingBox: {
    alignSelf: 'flex-start',
    backgroundColor: 'rgba(99,102,241,0.9)',
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 4,
  },
  ratingValue: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '900',
  },
  shopName: {
    color: '#fff',
    fontSize: 32,
    fontWeight: '900',
  },
  addrBox: {
    opacity: 0.8,
  },
  shopAddr: {
    color: '#f8fafc',
    fontSize: 14,
    fontWeight: '500',
  },
  tabSection: {
    backgroundColor: '#141420',
    paddingVertical: 6,
  },
  tabsScroll: {
    paddingHorizontal: 20,
    gap: 16,
  },
  tabItem: {
    paddingVertical: 14,
    paddingHorizontal: 4,
    borderBottomWidth: 2,
    borderBottomColor: 'transparent',
  },
  tabItemActive: {
    borderBottomColor: '#6366f1',
  },
  tabText: {
    color: '#475569',
    fontSize: 14,
    fontWeight: '700',
  },
  tabTextActive: {
    color: '#f8fafc',
  },
  contentArea: {
    padding: 20,
  },
  grid: {
    gap: 12,
  },
  serviceCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    gap: 12,
  },
  svcInfo: {
    flex: 1,
    gap: 4,
  },
  svcName: {
    color: '#f8fafc',
    fontSize: 16,
    fontWeight: '800',
  },
  svcMeta: {
    color: '#64748b',
    fontSize: 13,
  },
  barberList: {
    gap: 12,
  },
  barberCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 14,
    gap: 14,
  },
  barberAvatar: {
    width: 50,
    height: 50,
    borderRadius: 16,
    backgroundColor: '#1c1c2e',
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatarTxt: {
    color: '#6366f1',
    fontSize: 20,
    fontWeight: '900',
  },
  barberName: {
    color: '#f8fafc',
    fontSize: 16,
    fontWeight: '800',
  },
  barberSpecs: {
    color: '#475569',
    fontSize: 12,
  },
  productCard: {
    padding: 16,
    gap: 8,
  },
  prodHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  prodName: {
    color: '#f8fafc',
    fontSize: 16,
    fontWeight: '800',
    flex: 1,
  },
  prodPrice: {
    color: '#a5b4fc',
    fontSize: 16,
    fontWeight: '900',
  },
  prodStock: {
    color: '#475569',
    fontSize: 12,
    marginBottom: 4,
  },
  detailsBox: {
    padding: 20,
    gap: 12,
  },
  detailTitle: {
    color: '#f8fafc',
    fontSize: 18,
    fontWeight: '800',
    marginBottom: 8,
  },
  schedRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  schedDay: {
    color: '#64748b',
    fontSize: 14,
  },
  schedTime: {
    color: '#f8fafc',
    fontSize: 14,
    fontWeight: '600',
  },
  today: {
    color: '#6366f1',
    fontWeight: '800',
  },
  divider: {
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.06)',
    marginVertical: 12,
  },
  contactLink: {
    color: '#818cf8',
    fontSize: 16,
    fontWeight: '700',
  },
  centerState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 40,
  },
  centerTitle: {
    color: '#f8fafc',
    fontSize: 18,
    fontWeight: '800',
  },
});
