import { Link, useLocalSearchParams } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import { Image, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, 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 CustomerProductScreen() {
  const params = useLocalSearchParams<{ id?: string; slug?: string }>();
  const productId = typeof params.id === 'string' ? params.id : '';
  const slug = typeof params.slug === 'string' ? params.slug : undefined;
  const { storefront, loading, error, clearError, selectStore, loadStorefront, addToCart } = useCustomerOrder();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const [notes, setNotes] = useState('');
  const [added, setAdded] = useState('');

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

  const product = useMemo(
    () => storefront?.productCategories.flatMap((category) => category.products).find((item) => item.id === productId),
    [productId, storefront],
  );

  const handleAdd = () => {
    if (!product) {
      return;
    }
    addToCart({
      productId: product.id,
      name: product.name,
      price: Number(product.price),
      notes: notes || undefined,
    });
    setAdded('Produto adicionado no carrinho.');
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
          <CustomerPageHeader
            title={product?.name ?? 'Produto'}
            subtitle={product?.description ?? 'Produto real do cardapio da loja.'}
            backHref={slug ? `/restaurant?slug=${slug}` : '/search'}
            backLabel="Voltar"
          />

          {product?.imageUrl ? <Image source={{ uri: product.imageUrl }} style={styles.productImage} resizeMode="cover" /> : null}

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

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Valor</Text>
            <Text style={[styles.price, { color: theme.accent }]}>{formatCurrency(product?.price)}</Text>
            <Text style={[styles.helper, { color: theme.textMuted }]}>Adicione uma observacao se precisar ajustar esse item.</Text>
            <TextInput
              value={notes}
              onChangeText={setNotes}
              placeholder="Ex.: sem cebola, cortar em 8 fatias"
              placeholderTextColor={theme.textSoft}
              style={[styles.input, { borderColor: theme.cardBorder, backgroundColor: theme.surfaceMuted, color: theme.text }]}
            />
          </View>

          {added ? <Text style={[styles.successText, { color: theme.accent }]}>{added}</Text> : null}

          <TouchableOpacity onPress={handleAdd} style={[styles.primaryButton, { backgroundColor: theme.accent }]}>
            <Text style={[styles.primaryButtonText, { color: theme.accentText }]}>Adicionar no carrinho</Text>
          </TouchableOpacity>
          <Link href="/cart" style={[styles.secondaryButton, { backgroundColor: theme.surface, color: theme.text }]}>Abrir carrinho</Link>
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  productImage: { width: '100%', height: 220, borderRadius: 20, backgroundColor: '#111827' },
  infoText: { fontSize: 13 },
  errorText: { fontSize: 13, color: '#FCA5A5', fontWeight: '700' },
  card: { borderRadius: 18, padding: 15, borderWidth: 1 },
  sectionTitle: { fontSize: 17, fontWeight: '900' },
  price: { marginTop: 8, fontSize: 22, fontWeight: '900' },
  helper: { marginTop: 8, fontSize: 13, lineHeight: 18, fontWeight: '600' },
  input: { marginTop: 12, borderRadius: 14, borderWidth: 1, paddingHorizontal: 13, paddingVertical: 11, fontSize: 14 },
  successText: { fontSize: 12, fontWeight: '700' },
  primaryButton: { borderRadius: 999, paddingHorizontal: 16, paddingVertical: 12 },
  primaryButtonText: { textAlign: 'center', fontWeight: '800' },
  secondaryButton: { borderRadius: 999, textAlign: 'center', paddingHorizontal: 16, paddingVertical: 12, fontWeight: '800', overflow: 'hidden', marginBottom: 10 },
});
