import { Link } from 'expo-router';
import { useEffect, useMemo } from 'react';
import {
  Image,
  ImageBackground,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { CustomerBottomNav } from '../components/customer-bottom-nav';
import { formatCurrency, useCustomerOrder } from '../src/store/order';
import { useCustomerSession } from '../src/store/session';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerHome() {
  const { profile, address, bootstrap, initialized, loading, error, clearError } = useCustomerSession();
  const { stores, cart, loadStores } = useCustomerOrder();
  const { mode, toggleMode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);

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

  useEffect(() => {
    void loadStores();
  }, [loadStores]);

  const firstName = profile.fullName.split(' ')[0];
  const featuredStore = stores[0] ?? null;
  const categoryHighlights = useMemo(() => {
    const labels = Array.from(
      new Set(
        stores.flatMap((store) => store.categories ?? []).filter((entry) => entry && entry.trim().length > 0),
      ),
    ).slice(0, 6);

    return labels.map((label, index) => ({
      label,
      tone: ['#FFF1E7', '#FFF7DB', '#EEF7FF', '#FDF0FF', '#F3EEFF', '#E8F7E8'][index % 6],
    }));
  }, [stores]);

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
          <View style={styles.header}>
            <View style={styles.headerText}>
              <Text style={[styles.greeting, { color: theme.textMuted }]}>Boa noite, {firstName}</Text>
              <Text style={[styles.addressText, { color: theme.text }]}>
                {address.street || 'Seu endereco'}, {address.number || 's/n'}
              </Text>
            </View>
            <View style={styles.headerActions}>
              <TouchableOpacity onPress={toggleMode} style={[styles.themeSwitch, { backgroundColor: theme.surface }]}>
                <Text style={[styles.themeSwitchText, { color: theme.text }]}>{mode === 'light' ? 'Escuro' : 'Claro'}</Text>
              </TouchableOpacity>
              <View style={styles.headerChip}>
                <Text style={styles.headerChipText}>{cart.length}</Text>
              </View>
              <Image source={require('../assets/chego-logo.png')} style={styles.logo} resizeMode="contain" />
            </View>
          </View>

          <Link
            href="/search"
            style={[
              styles.searchBar,
              { backgroundColor: theme.surface, color: theme.textMuted, borderColor: theme.cardBorder },
            ]}
          >
            Buscar loja, prato ou categoria
          </Link>

          <View style={[styles.noticeBar, { backgroundColor: theme.notice }]}>
            <View style={[styles.noticeBadge, { backgroundColor: theme.noticeBadge }]}>
              <Text style={[styles.noticeBadgeText, { color: theme.noticeBadgeText }]}>CHEGO</Text>
            </View>
            <Text style={[styles.noticeText, { color: theme.noticeText }]}>
              Cupons, combos e entregas do dia em uma vitrine mais direta.
            </Text>
          </View>

          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.bannerRow}>
            {stores.slice(0, 8).map((store) => (
              <Link key={store.id} href={`/restaurant?slug=${store.slug}` as never} style={styles.bannerCard}>
                <ImageBackground
                  source={
                    store.featuredProducts?.[0]?.imageUrl
                      ? { uri: store.featuredProducts[0].imageUrl }
                      : store.coverImageUrl
                        ? { uri: store.coverImageUrl }
                        : require('../assets/chego-logo.png')
                  }
                  imageStyle={styles.bannerImage}
                  style={styles.bannerCardBg}
                >
                  <View style={[styles.bannerOverlay, { backgroundColor: theme.heroOverlay }]}>
                    <View style={styles.bannerTopRow}>
                      <Text style={styles.bannerBadge}>{store.city ?? 'Entrega ativa'}</Text>
                    </View>
                    <View>
                      <Text numberOfLines={2} style={styles.bannerTitle}>
                        {store.featuredProducts?.[0]?.name ?? 'Prato em destaque'}
                      </Text>
                      <Text numberOfLines={2} style={styles.bannerCopy}>
                        {store.featuredProducts?.[0]?.description ?? 'Escolha pronta para abrir o apetite e pedir agora.'}
                      </Text>
                      <View style={styles.bannerStoreSignature}>
                        <View style={styles.bannerLogoShell}>
                          {store.logoUrl ? (
                            <Image source={{ uri: store.logoUrl }} style={styles.bannerLogo} resizeMode="cover" />
                          ) : (
                            <Image source={require('../assets/chego-logo.png')} style={styles.bannerLogoFallback} resizeMode="contain" />
                          )}
                        </View>
                        <Text numberOfLines={1} style={styles.bannerStoreDetail}>
                          {store.name}
                        </Text>
                      </View>
                    </View>
                  </View>
                </ImageBackground>
              </Link>
            ))}
          </ScrollView>

          {categoryHighlights.length ? (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.cuisineRow}>
              {categoryHighlights.map((item) => (
                <Link
                  key={item.label}
                  href={`/search?category=${encodeURIComponent(item.label)}`}
                  style={[styles.cuisineChip, { backgroundColor: mode === 'light' ? item.tone : theme.chip }]}
                >
                  <Text style={[styles.cuisineText, { color: mode === 'light' ? '#111827' : theme.chipText }]}>{item.label}</Text>
                </Link>
              ))}
            </ScrollView>
          ) : null}

          <View style={styles.sectionHeader}>
            <View>
              <Text style={[styles.sectionTitle, { color: theme.text }]}>Pratos em destaque</Text>
              <Text style={[styles.sectionSubtitle, { color: theme.textMuted }]}>
                A comida entra na frente. O restaurante fica como detalhe.
              </Text>
            </View>
            <Link href="/search" style={[styles.sectionLink, { color: theme.accent }]}>
              Ver todas
            </Link>
          </View>

          {loading ? <Text style={[styles.infoText, { color: theme.textMuted }]}>Sincronizando sua conta...</Text> : null}
          {error ? (
            <Text onPress={clearError} style={[styles.errorText, { color: '#B91C1C' }]}>
              {error}
            </Text>
          ) : null}

          <View style={styles.storeList}>
            {!stores.length && !loading ? (
              <View style={[styles.emptyCard, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
                <Text style={[styles.emptyTitle, { color: theme.text }]}>Nenhuma loja carregada agora.</Text>
                <Text style={[styles.emptyBody, { color: theme.textMuted }]}>
                  Abra a busca para recarregar a vitrine do cliente.
                </Text>
              </View>
            ) : null}

            {stores.map((store) => (
              <Link
                key={store.id}
                href={`/restaurant?slug=${store.slug}` as never}
                style={[styles.storeCard, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}
              >
                <View style={[styles.storeFoodStage, { backgroundColor: theme.surfaceMuted }]}>
                  <ImageBackground
                    source={
                      store.featuredProducts?.[0]?.imageUrl
                        ? { uri: store.featuredProducts[0].imageUrl }
                        : store.coverImageUrl
                          ? { uri: store.coverImageUrl }
                          : require('../assets/chego-logo.png')
                    }
                    imageStyle={styles.storeFoodImage}
                    style={styles.storeFoodImageWrap}
                  >
                    <View style={[styles.storeFoodShade, { backgroundColor: theme.heroOverlay }]}>
                      <View style={styles.storeTopRow}>
                        <Text style={styles.storeCity}>{store.city ?? 'Cidade'}</Text>
                        <View style={styles.storeHeaderRight}>
                          <View style={styles.storeTinyLogoShell}>
                            {store.logoUrl ? (
                              <Image source={{ uri: store.logoUrl }} style={styles.storeTinyLogo} resizeMode="cover" />
                            ) : (
                              <Image source={require('../assets/chego-logo.png')} style={styles.storeTinyLogoFallback} resizeMode="contain" />
                            )}
                          </View>
                        </View>
                      </View>
                      <View style={styles.foodHeadline}>
                        <Text numberOfLines={2} style={styles.foodTitle}>
                          {store.featuredProducts?.[0]?.name ?? 'Sugestao da casa'}
                        </Text>
                        <Text numberOfLines={2} style={styles.foodDescription}>
                          {store.featuredProducts?.[0]?.description ?? 'Prato com alta saida para abrir o apetite do cliente.'}
                        </Text>
                      </View>
                    </View>
                  </ImageBackground>

                  <View style={styles.storeSignature}>
                    <View style={styles.storeIdentityRow}>
                      <View style={styles.storeIdentityLogoShell}>
                        {store.logoUrl ? (
                          <Image source={{ uri: store.logoUrl }} style={styles.storeIdentityLogo} resizeMode="cover" />
                        ) : (
                          <Image source={require('../assets/chego-logo.png')} style={styles.storeIdentityLogoFallback} resizeMode="contain" />
                        )}
                      </View>
                      <View style={styles.storeIdentityText}>
                        <Text numberOfLines={1} style={[styles.storeName, { color: theme.text }]}>{store.name}</Text>
                        <Text numberOfLines={1} style={[styles.storeNeighborhood, { color: theme.textMuted }]}>
                          {[store.street, store.number].filter(Boolean).join(', ') || store.neighborhood || 'Endereco da loja'}
                        </Text>
                      </View>
                    </View>
                  </View>
                </View>

                {store.featuredProducts?.length ? (
                  <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.productPreviewRow}>
                    {store.featuredProducts.map((product) => (
                      <View
                        key={`${store.id}-${product.name}`}
                        style={[styles.productPreviewCard, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}
                      >
                        {product.imageUrl ? (
                          <Image source={{ uri: product.imageUrl }} style={styles.productPreviewImage} resizeMode="cover" />
                        ) : (
                          <View style={[styles.productFallback, { backgroundColor: theme.surfaceMuted }]}>
                            <Text style={[styles.productFallbackText, { color: theme.text }]}>
                              {product.name.slice(0, 2).toUpperCase()}
                            </Text>
                          </View>
                        )}
                        <Text numberOfLines={2} style={[styles.productPreviewName, { color: theme.text }]}>
                          {product.name}
                        </Text>
                      </View>
                    ))}
                  </ScrollView>
                ) : null}
              </Link>
            ))}
          </View>

          {featuredStore ? (
            <Link href={`/restaurant?slug=${featuredStore.slug}` as never} style={[styles.floatingAction, { backgroundColor: theme.accent, color: theme.accentText }]}>
              Pedir agora
            </Link>
          ) : null}
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { paddingHorizontal: 14, paddingTop: 8, paddingBottom: 18, gap: 12 },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  headerText: { flex: 1 },
  greeting: { fontSize: 13, fontWeight: '600' },
  addressText: { marginTop: 2, fontSize: 20, lineHeight: 24, fontWeight: '900' },
  headerActions: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  themeSwitch: { borderRadius: 999, paddingHorizontal: 11, paddingVertical: 8, borderWidth: 1, borderColor: '#E5E7EB' },
  themeSwitchText: { fontSize: 10, fontWeight: '800' },
  headerChip: { minWidth: 30, height: 30, borderRadius: 15, backgroundColor: '#E9D5FF', alignItems: 'center', justifyContent: 'center' },
  headerChipText: { color: '#7C3AED', fontWeight: '900', fontSize: 12 },
  logo: { width: 52, height: 20 },
  searchBar: { borderRadius: 14, overflow: 'hidden', paddingHorizontal: 16, paddingVertical: 12, borderWidth: 1, fontSize: 14, fontWeight: '700' },
  noticeBar: { borderRadius: 14, paddingHorizontal: 11, paddingVertical: 9, flexDirection: 'row', alignItems: 'center', gap: 8 },
  noticeBadge: { borderRadius: 999, paddingHorizontal: 10, paddingVertical: 6 },
  noticeBadgeText: { fontSize: 10, fontWeight: '900' },
  noticeText: { flex: 1, fontSize: 11, lineHeight: 16, fontWeight: '700' },
  bannerRow: { gap: 8, paddingRight: 10 },
  bannerCard: { width: 172, borderRadius: 18, overflow: 'hidden' },
  bannerCardBg: { minHeight: 108, justifyContent: 'flex-end' },
  bannerImage: { borderRadius: 18 },
  bannerOverlay: { padding: 10, minHeight: 108, justifyContent: 'space-between' },
  bannerTopRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  bannerBadge: { alignSelf: 'flex-start', borderRadius: 999, backgroundColor: 'rgba(255,255,255,0.2)', color: '#FFFFFF', paddingHorizontal: 10, paddingVertical: 5, fontSize: 9, fontWeight: '900', overflow: 'hidden' },
  bannerLogoShell: { width: 24, height: 24, borderRadius: 8, backgroundColor: 'rgba(255,255,255,0.96)', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' },
  bannerLogo: { width: '100%', height: '100%' },
  bannerLogoFallback: { width: 18, height: 9 },
  bannerStoreSignature: { marginTop: 7, flexDirection: 'row', alignItems: 'center', gap: 7, alignSelf: 'flex-start', maxWidth: '100%' },
  bannerTitle: { marginTop: 8, fontSize: 16, lineHeight: 19, color: '#FFFFFF', fontWeight: '900', maxWidth: 132 },
  bannerCopy: { marginTop: 4, fontSize: 10, lineHeight: 14, color: '#F8FAFC', fontWeight: '700' },
  bannerStoreDetail: { flexShrink: 1, fontSize: 9, color: '#E2E8F0', fontWeight: '800', textAlign: 'left' },
  cuisineRow: { gap: 8, paddingRight: 12 },
  cuisineChip: { borderRadius: 14, paddingHorizontal: 12, paddingVertical: 10 },
  cuisineText: { fontSize: 11, fontWeight: '800' },
  sectionHeader: { flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 },
  sectionTitle: { fontSize: 20, lineHeight: 24, fontWeight: '900' },
  sectionSubtitle: { marginTop: 3, fontSize: 11, fontWeight: '600' },
  sectionLink: { fontSize: 13, fontWeight: '900' },
  infoText: { fontSize: 14 },
  errorText: { fontSize: 14, fontWeight: '700' },
  storeList: { gap: 12 },
  emptyCard: { borderRadius: 20, borderWidth: 1, padding: 16 },
  emptyTitle: { fontSize: 15, fontWeight: '900' },
  emptyBody: { marginTop: 6, fontSize: 12, lineHeight: 17, fontWeight: '600' },
  storeCard: { borderRadius: 20, borderWidth: 1, padding: 9, overflow: 'hidden' },
  storeFoodStage: { borderRadius: 16, overflow: 'hidden' },
  storeFoodImageWrap: { minHeight: 168, justifyContent: 'space-between' },
  storeFoodImage: { borderRadius: 16 },
  storeFoodShade: { flex: 1, justifyContent: 'space-between', padding: 10 },
  storeTopRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 8 },
  storeHeaderRight: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  storeCity: { borderRadius: 999, overflow: 'hidden', backgroundColor: 'rgba(255,255,255,0.92)', color: '#166534', paddingHorizontal: 10, paddingVertical: 6, fontSize: 11, fontWeight: '900' },
  storeFee: { borderRadius: 999, overflow: 'hidden', backgroundColor: 'rgba(17,24,39,0.72)', color: '#FFFFFF', paddingHorizontal: 10, paddingVertical: 6, fontSize: 11, fontWeight: '900' },
  storeTinyLogoShell: { width: 24, height: 24, borderRadius: 8, backgroundColor: 'rgba(255,255,255,0.96)', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' },
  storeTinyLogo: { width: '100%', height: '100%' },
  storeTinyLogoFallback: { width: 20, height: 10 },
  foodHeadline: { maxWidth: '74%' },
  foodTitle: { color: '#FFFFFF', fontSize: 21, lineHeight: 24, fontWeight: '900' },
  foodDescription: { marginTop: 5, color: '#F3F4F6', fontSize: 11, lineHeight: 15, fontWeight: '700' },
  storeSignature: { paddingHorizontal: 6, paddingVertical: 8, backgroundColor: 'transparent' },
  storeIdentityRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', gap: 10 },
  storeIdentityLogoShell: { width: 22, height: 22, borderRadius: 7, backgroundColor: '#FFFFFF', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' },
  storeIdentityLogo: { width: '100%', height: '100%' },
  storeIdentityLogoFallback: { width: 18, height: 9 },
  storeIdentityText: { minWidth: 0, maxWidth: 170, alignItems: 'flex-start' },
  storeName: { fontSize: 13, lineHeight: 16, fontWeight: '900', textAlign: 'left' },
  storeNeighborhood: { fontSize: 10, fontWeight: '700', textAlign: 'left' },
  productPreviewRow: { gap: 8, paddingTop: 8, paddingBottom: 2 },
  productPreviewCard: { width: 96, borderRadius: 14, borderWidth: 1, overflow: 'hidden' },
  productPreviewImage: { width: '100%', height: 76 },
  productFallback: { width: '100%', height: 84, alignItems: 'center', justifyContent: 'center' },
  productFallbackText: { fontSize: 18, fontWeight: '900' },
  productPreviewName: { paddingHorizontal: 8, paddingVertical: 8, fontSize: 10, lineHeight: 13, fontWeight: '800', textAlign: 'center' },
  floatingAction: { alignSelf: 'center', marginTop: 2, borderRadius: 999, overflow: 'hidden', paddingHorizontal: 20, paddingVertical: 11, fontSize: 12, fontWeight: '900', textAlign: 'center' },
});
