import { Link, useLocalSearchParams } 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 { CustomerPageHeader } from '../components/customer-page-header';
import { formatCurrency, useCustomerOrder } from '../src/store/order';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerRestaurantScreen() {
  const params = useLocalSearchParams<{ slug?: string }>();
  const slug = typeof params.slug === 'string' ? params.slug : undefined;
  const { storefront, loading, error, clearError, selectStore, loadStorefront, cart, addToCart, updateQuantity } = useCustomerOrder();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);

  useEffect(() => {
    if (slug) {
      selectStore(slug);
      void loadStorefront(slug);
    } else {
      void loadStorefront();
    }
  }, [loadStorefront, selectStore, slug]);

  const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
  const categories = useMemo(
    () =>
      storefront?.productCategories.map((category) => ({
        ...category,
        products: category.products.map((product) => ({
          ...product,
          quantity: cart.find((item) => item.productId === product.id)?.quantity ?? 0,
        })),
      })) ?? [],
    [cart, storefront?.productCategories],
  );

  const featuredProduct = categories.flatMap((category) => category.products)[0] ?? null;

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
          <CustomerPageHeader
            title={storefront?.name ?? 'Loja'}
            subtitle={storefront?.description ?? 'Cardapio real conectado ao backend.'}
            backHref="/search"
            backLabel="Buscar"
          />

          <View style={[styles.heroCard, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <ImageBackground
              source={
                featuredProduct?.imageUrl
                  ? { uri: featuredProduct.imageUrl }
                  : storefront?.coverImageUrl
                    ? { uri: storefront.coverImageUrl }
                    : require('../assets/chego-logo.png')
              }
              imageStyle={styles.heroImage}
              style={styles.heroImageWrap}
            >
              <View style={[styles.heroOverlay, { backgroundColor: theme.heroOverlay }]}>
                <View style={styles.heroTopRow}>
                  <Text style={styles.heroBadge}>{storefront?.city ?? 'Entrega ativa'}</Text>
                  {storefront?.logoUrl ? <Image source={{ uri: storefront.logoUrl }} style={styles.heroLogo} resizeMode="cover" /> : null}
                </View>
                <View style={styles.heroBody}>
                  <Text style={styles.heroTitle}>{featuredProduct?.name ?? storefront?.name ?? 'Vitrine da loja'}</Text>
                  <Text style={styles.heroCopy}>
                    {featuredProduct?.description ?? storefront?.description ?? 'Escolha os pratos mais pedidos e finalize rapido.'}
                  </Text>
                </View>
              </View>
            </ImageBackground>

            <View style={styles.heroMetaRow}>
              <Text style={[styles.heroMetaText, { color: theme.text }]}>{storefront?.name ?? 'Loja'}</Text>
              <Text style={[styles.heroMetaSubtext, { color: theme.textMuted }]}>
                {[storefront?.street, storefront?.number].filter(Boolean).join(', ') || storefront?.neighborhood || 'Endereco da loja'} • {categories.reduce((sum, category) => sum + category.products.length, 0)} itens
              </Text>
            </View>
          </View>

          <View style={styles.summaryRow}>
            <Text style={[styles.summaryPill, { backgroundColor: theme.surface, color: theme.text, borderColor: theme.cardBorder }]}>
              Entrega {formatCurrency(storefront?.baseDeliveryFee)}
            </Text>
            <Text style={[styles.summaryPill, { backgroundColor: theme.surface, color: theme.text, borderColor: theme.cardBorder }]}>
              {storefront?.city ?? 'Cidade'}
            </Text>
            <Text style={[styles.summaryPill, { backgroundColor: theme.surface, color: theme.text, borderColor: theme.cardBorder }]}>
              {storefront?.zipCode ?? `${categories.length} categorias`}
            </Text>
            <Text style={[styles.summaryPill, { backgroundColor: theme.surface, color: theme.text, borderColor: theme.cardBorder }]}>
              Carrinho {totalItems}
            </Text>
          </View>

          {loading ? <Text style={[styles.infoText, { color: theme.textMuted }]}>Carregando cardapio...</Text> : null}
          {error ? <Text style={styles.errorText} onPress={clearError}>{error}</Text> : null}

          {categories.map((category) => (
            <View key={category.id} style={styles.categoryBlock}>
              <View style={styles.categoryHeader}>
                <Text style={[styles.categoryTitle, { color: theme.text }]}>{category.name}</Text>
                <Text style={[styles.categoryCount, { color: theme.textMuted }]}>{category.products.length} opcoes</Text>
              </View>

              {category.products.map((product) => (
                <View key={product.id} style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
                  {product.imageUrl ? (
                    <Image source={{ uri: product.imageUrl }} style={styles.cardImage} resizeMode="cover" />
                  ) : null}
                  <View style={styles.cardBody}>
                    <View style={styles.cardText}>
                      <Text style={[styles.cardTitle, { color: theme.text }]}>{product.name}</Text>
                      <Text style={[styles.cardMeta, { color: theme.textMuted }]}>{product.description ?? 'Sem descricao'}</Text>
                      <Text style={[styles.cardPrice, { color: theme.accent }]}>{formatCurrency(product.price)}</Text>
                    </View>
                    <View style={styles.quantityStrip}>
                      <TouchableOpacity
                        onPress={() => updateQuantity(product.id, product.quantity - 1)}
                        style={[styles.quantityButton, product.quantity === 0 ? styles.quantityButtonDisabled : null]}
                        disabled={product.quantity === 0}
                      >
                        <Text style={styles.quantityButtonText}>-</Text>
                      </TouchableOpacity>
                      <Text style={[styles.quantityValue, { color: theme.text }]}>{product.quantity}</Text>
                      <TouchableOpacity
                        onPress={() =>
                          product.quantity === 0
                            ? addToCart({ productId: product.id, name: product.name, price: Number(product.price) })
                            : updateQuantity(product.id, product.quantity + 1)
                        }
                        style={[styles.quantityButton, { backgroundColor: theme.accent }]}
                      >
                        <Text style={[styles.quantityButtonText, { color: theme.accentText }]}>+</Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ))}

          <Link href="/cart" style={[styles.primaryButton, { backgroundColor: theme.accent, color: theme.accentText }]}>
            Abrir carrinho ({totalItems})
          </Link>
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  heroCard: { borderRadius: 20, borderWidth: 1, overflow: 'hidden' },
  heroImageWrap: { minHeight: 196, justifyContent: 'space-between' },
  heroImage: { borderRadius: 20 },
  heroOverlay: { flex: 1, justifyContent: 'space-between', padding: 14 },
  heroTopRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  heroBadge: { borderRadius: 999, overflow: 'hidden', backgroundColor: 'rgba(255,255,255,0.92)', color: '#166534', paddingHorizontal: 10, paddingVertical: 6, fontSize: 11, fontWeight: '900' },
  heroLogo: { width: 26, height: 26, borderRadius: 9, backgroundColor: '#FFFFFF' },
  heroBody: { maxWidth: '78%' },
  heroTitle: { color: '#FFFFFF', fontSize: 24, lineHeight: 28, fontWeight: '900' },
  heroCopy: { marginTop: 6, color: '#F8FAFC', fontSize: 12, lineHeight: 16, fontWeight: '700' },
  heroMetaRow: { paddingHorizontal: 14, paddingVertical: 10 },
  heroMetaText: { fontSize: 14, fontWeight: '900' },
  heroMetaSubtext: { marginTop: 3, fontSize: 11, fontWeight: '700' },
  summaryRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  summaryPill: { borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8, fontSize: 12, fontWeight: '800', overflow: 'hidden', borderWidth: 1 },
  infoText: { fontSize: 14 },
  errorText: { fontSize: 14, color: '#FCA5A5', fontWeight: '700' },
  categoryBlock: { gap: 8 },
  categoryHeader: { flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'space-between' },
  categoryTitle: { fontSize: 18, fontWeight: '900' },
  categoryCount: { fontSize: 11, fontWeight: '700' },
  card: { borderRadius: 18, overflow: 'hidden', borderWidth: 1 },
  cardImage: { width: '100%', height: 156, backgroundColor: '#111827' },
  cardBody: { padding: 12, gap: 10 },
  cardText: { gap: 5 },
  cardTitle: { fontSize: 16, fontWeight: '900' },
  cardMeta: { fontSize: 12, lineHeight: 16, fontWeight: '600' },
  cardPrice: { marginTop: 4, fontSize: 15, fontWeight: '900' },
  quantityStrip: { flexDirection: 'row', alignItems: 'center', alignSelf: 'flex-end', gap: 10 },
  quantityButton: { width: 36, height: 36, borderRadius: 18, backgroundColor: '#E2E8F0', alignItems: 'center', justifyContent: 'center' },
  quantityButtonDisabled: { backgroundColor: '#334155' },
  quantityButtonText: { color: '#0F172A', fontSize: 19, fontWeight: '900' },
  quantityValue: { minWidth: 22, textAlign: 'center', fontSize: 15, fontWeight: '900' },
  primaryButton: { borderRadius: 999, textAlign: 'center', paddingHorizontal: 16, paddingVertical: 12, fontWeight: '800', overflow: 'hidden', marginBottom: 10 },
});
