import { Link } from 'expo-router';
import { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet, Text, View } from 'react-native';
import { CustomerBottomNav } from '../components/customer-bottom-nav';
import { CustomerPageHeader } from '../components/customer-page-header';
import { API_URL } from '../src/runtime-config';
import { formatCurrency } from '../src/store/order';
import { useCustomerSession } from '../src/store/session';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

type OrderItem = {
  id: string;
  status: string;
  total: number | string;
  createdAt: string;
  restaurant: { name: string };
  items: Array<{ id: string; quantity: number }>;
  delivery?: { etaMinutes?: number | null } | null;
};

function humanStatus(status: string) {
  return status.replaceAll('_', ' ');
}

export default function CustomerOrdersScreen() {
  const { token, initialized, loading: sessionLoading, error: sessionError, bootstrap } = useCustomerSession();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

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

  useEffect(() => {
    if (!token) {
      return;
    }

    let active = true;
    const loadOrders = async () => {
      setLoading(true);
      try {
        const response = await fetch(`${API_URL}/orders`, {
          headers: { Authorization: `Bearer ${token}` },
        });
        const payload = await response.json().catch(() => []);
        if (!response.ok) {
          throw new Error(payload?.message ?? 'Falha ao carregar pedidos.');
        }
        if (!active) {
          return;
        }
        setOrders(payload);
        setError('');
      } catch (loadError) {
        if (active) {
          setError(loadError instanceof Error ? loadError.message : 'Falha ao carregar pedidos.');
        }
      } finally {
        if (active) {
          setLoading(false);
        }
      }
    };

    void loadOrders();
    return () => {
      active = false;
    };
  }, [token]);

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
          <CustomerPageHeader title="Seus pedidos" subtitle="Acompanhe status, total e entrega em um unico lugar." backHref="/" backLabel="Inicio" />

          {sessionLoading || loading ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: theme.textMuted }]}>Carregando pedidos...</Text></View> : null}
          {sessionError ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: '#B91C1C' }]}>{sessionError}</Text></View> : null}
          {error ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: '#B91C1C' }]}>{error}</Text></View> : null}

          {!loading && !orders.length ? (
            <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
              <Text style={[styles.orderNumber, { color: theme.text }]}>Nenhum pedido ainda</Text>
              <Text style={[styles.orderMeta, { color: theme.textMuted }]}>Assim que voce fechar uma compra no app, ela aparece aqui.</Text>
            </View>
          ) : null}

          {orders.map((order) => (
            <View key={order.id} style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
              <View style={styles.orderTopRow}>
                <Text style={[styles.orderNumber, { color: theme.text }]}>#{order.id.slice(-8).toUpperCase()}</Text>
                <Text style={[styles.statusBadge, { backgroundColor: theme.surfaceMuted, color: theme.accent }]}>{humanStatus(order.status)}</Text>
              </View>
              <Text style={[styles.orderStore, { color: theme.textMuted }]}>{order.restaurant.name}</Text>
              <Text style={[styles.orderTotal, { color: theme.text }]}>{formatCurrency(order.total)}</Text>
              <Text style={[styles.orderMeta, { color: theme.textMuted }]}>{order.items.reduce((sum, item) => sum + item.quantity, 0)} itens • ETA {order.delivery?.etaMinutes ?? '--'} min</Text>
              <Text style={[styles.orderMeta, { color: theme.textSoft }]}>{new Date(order.createdAt).toLocaleString('pt-BR')}</Text>
              <Link href={`/order-tracking?orderId=${order.id}` as never} style={[styles.button, { backgroundColor: theme.accent, color: theme.accentText }]}>Acompanhar</Link>
            </View>
          ))}
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  warningCard: { borderRadius: 18, padding: 14 },
  warningText: { fontSize: 13, lineHeight: 18, fontWeight: '700' },
  card: { borderRadius: 18, padding: 15, borderWidth: 1 },
  orderTopRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 10 },
  orderNumber: { fontSize: 16, fontWeight: '900' },
  statusBadge: { borderRadius: 999, overflow: 'hidden', paddingHorizontal: 9, paddingVertical: 5, fontSize: 9, fontWeight: '900' },
  orderStore: { marginTop: 7, fontSize: 13, fontWeight: '700' },
  orderTotal: { marginTop: 8, fontSize: 21, fontWeight: '900' },
  orderMeta: { marginTop: 7, fontSize: 12, fontWeight: '600' },
  button: { marginTop: 14, borderRadius: 999, textAlign: 'center', paddingHorizontal: 16, paddingVertical: 12, fontWeight: '800', overflow: 'hidden' },
});
