import { useRouter } from 'expo-router';
import { useEffect } from 'react';
import { 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 { useCustomerOrder } from '../src/store/order';
import { useCustomerSession } from '../src/store/session';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerCheckoutScreen() {
  const router = useRouter();
  const { address, profile, initialized, bootstrap } = useCustomerSession();
  const { paymentMethod, setPaymentMethod, createOrder, saving, error, clearError, couponCode, setCouponCode, storefront } = useCustomerOrder();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const activeCoupons = storefront?.activeCoupons ?? [];

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

  const handleCreateOrder = async () => {
    await createOrder({
      fullName: profile.fullName,
      phone: profile.phone,
      email: profile.email,
      street: address.street,
      number: address.number,
      complement: address.complement,
      neighborhood: address.neighborhood,
      city: address.city,
      state: address.state,
      zipCode: address.zipCode,
    });

    if (!useCustomerOrder.getState().error) {
      router.push('/payment');
    }
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content}>
          <CustomerPageHeader title="Checkout" subtitle="Confirme endereco e pagamento antes de enviar." backHref="/cart" backLabel="Carrinho" />

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionKicker, { color: theme.accent }]}>Entrega</Text>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>{profile.fullName}</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>{address.street}, {address.number}</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>{address.complement || 'Sem complemento'}</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>{address.neighborhood} • {address.city} • {address.state}</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>CEP {address.zipCode}</Text>
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionKicker, { color: theme.accent }]}>Pagamento</Text>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Escolha como quer pagar</Text>
            {([
              { key: 'PIX', label: 'PIX', note: 'Rapido, direto e com confirmacao imediata.' },
              { key: 'CREDIT_CARD', label: 'Cartao', note: 'Fluxo online para seguir no app.' },
              { key: 'CASH', label: 'Dinheiro', note: 'Pagamento na entrega quando a loja aceitar.' },
            ] as const).map((method) => {
              const active = paymentMethod === method.key;
              return (
                <TouchableOpacity
                  key={method.key}
                  onPress={() => setPaymentMethod(method.key)}
                  style={[
                    styles.methodButton,
                    {
                      borderColor: active ? theme.accent : theme.cardBorder,
                      backgroundColor: active ? theme.surfaceMuted : theme.surface,
                    },
                  ]}
                >
                  <Text style={[styles.methodText, { color: active ? theme.text : theme.textMuted }]}>{method.label}</Text>
                  <Text style={[styles.methodNote, { color: theme.textSoft }]}>{method.note}</Text>
                </TouchableOpacity>
              );
            })}
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionKicker, { color: theme.accent }]}>Cupom</Text>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Desconto da loja</Text>
            <TextInput
              value={couponCode}
              onChangeText={setCouponCode}
              autoCapitalize="characters"
              placeholder="Digite o codigo do cupom"
              placeholderTextColor={theme.textSoft}
              style={[styles.couponInput, { backgroundColor: theme.surfaceMuted, borderColor: theme.cardBorder, color: theme.text }]}
            />
            {activeCoupons.length ? (
              <View style={styles.couponRow}>
                {activeCoupons.slice(0, 3).map((coupon) => (
                  <TouchableOpacity
                    key={coupon.id}
                    onPress={() => setCouponCode(coupon.code)}
                    style={[styles.couponChip, { backgroundColor: theme.surfaceMuted, borderColor: theme.cardBorder }]}
                  >
                    <Text style={[styles.couponChipText, { color: theme.text }]}>{coupon.code}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            ) : (
              <Text style={[styles.helperText, { color: theme.textSoft }]}>
                Se a loja tiver cupom ativo no portal, ele sera validado ao confirmar o pedido.
              </Text>
            )}
          </View>

          {error ? <Text style={styles.errorText} onPress={clearError}>{error}</Text> : null}

          <TouchableOpacity onPress={() => void handleCreateOrder()} style={[styles.primaryButton, { backgroundColor: theme.accent, shadowColor: theme.accent }]} disabled={saving}>
            <Text style={[styles.primaryButtonText, { color: theme.accentText }]}>{saving ? 'Criando pedido...' : 'Confirmar pedido'}</Text>
          </TouchableOpacity>
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  card: { borderRadius: 18, padding: 15, borderWidth: 1 },
  sectionKicker: { fontSize: 10, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.2 },
  sectionTitle: { marginTop: 7, fontSize: 18, fontWeight: '900' },
  row: { marginTop: 8, fontSize: 13, fontWeight: '600' },
  methodButton: { marginTop: 10, borderRadius: 16, borderWidth: 1, paddingHorizontal: 13, paddingVertical: 12 },
  methodText: { fontSize: 14, fontWeight: '900' },
  methodNote: { marginTop: 4, fontSize: 11, lineHeight: 15, fontWeight: '600' },
  couponInput: { marginTop: 10, height: 48, borderRadius: 16, borderWidth: 1, paddingHorizontal: 14, fontSize: 14, fontWeight: '700' },
  couponRow: { marginTop: 10, flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  couponChip: { borderRadius: 999, borderWidth: 1, paddingHorizontal: 12, paddingVertical: 9 },
  couponChipText: { fontSize: 11, fontWeight: '900' },
  helperText: { marginTop: 8, fontSize: 11, lineHeight: 16, fontWeight: '600' },
  errorText: { fontSize: 14, color: '#FCA5A5', fontWeight: '700' },
  primaryButton: { borderRadius: 999, paddingHorizontal: 18, paddingVertical: 14, shadowOpacity: 0.24, shadowRadius: 18, shadowOffset: { width: 0, height: 10 }, elevation: 8 },
  primaryButtonText: { textAlign: 'center', fontWeight: '900', fontSize: 14 },
});
