import React, { useEffect, useState } from 'react';
import {
  View, Text, FlatList, StyleSheet,
  ActivityIndicator, Alert, TouchableOpacity,
} from 'react-native';
import { fetchMyOrders } from '../../services/api';
import { Order } from '../../types';

const STATUS_COLORS: Record<string, string> = {
  pending:           '#f59e0b',
  confirmed:         '#3b82f6',
  out_for_delivery:  '#8b5cf6',
  delivered:         '#22c55e',
  cancelled:         '#ef4444',
};

export default function MyOrdersScreen() {
  const [orders, setOrders]   = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => { loadOrders(); }, []);

  const loadOrders = async () => {
    setLoading(true);
    try {
      const data = await fetchMyOrders();
      setOrders(data);
    } catch {
      Alert.alert('Error', 'Could not load orders.');
    } finally {
      setLoading(false);
    }
  };

  const renderItem = ({ item }: { item: Order }) => (
    <View style={styles.card}>
      <View style={styles.cardTop}>
        <Text style={styles.orderId}>Order #{item.id.slice(-8).toUpperCase()}</Text>
        <View style={[styles.badge, { backgroundColor: STATUS_COLORS[item.status] + '22' }]}>
          <Text style={[styles.badgeText, { color: STATUS_COLORS[item.status] }]}>
            {item.status.replace(/_/g, ' ').toUpperCase()}
          </Text>
        </View>
      </View>
      <Text style={styles.date}>📅 {new Date(item.created_at).toLocaleDateString()}</Text>
      <Text style={styles.fulfillment}>
        {item.fulfillment === 'delivery' ? '🚚 Delivery' : '🏪 Pickup'}
        {item.address ? ` — ${item.address}` : ''}
      </Text>
      <Text style={styles.payment}>💵 Cash on Delivery</Text>
      {item.items && item.items.length > 0 && (
        <View style={styles.itemsList}>
          {item.items.map(oi => (
            <Text key={oi.id} style={styles.orderItem}>
              • {oi.product_name} × {oi.quantity} — ₦{(oi.price * oi.quantity).toLocaleString()}
            </Text>
          ))}
        </View>
      )}
      <Text style={styles.total}>Total: ₦{Number(item.total).toLocaleString()}</Text>
    </View>
  );

  return (
    <View style={styles.bg}>
      <View style={styles.header}>
        <Text style={styles.title}>📦 My Orders</Text>
        <TouchableOpacity onPress={loadOrders}>
          <Text style={styles.refresh}>↻ Refresh</Text>
        </TouchableOpacity>
      </View>
      {loading
        ? <ActivityIndicator color="#f97316" size="large" style={{ marginTop: 40 }} />
        : (
          <FlatList
            data={orders}
            keyExtractor={(i: Order) => i.id}
            renderItem={renderItem}
            contentContainerStyle={styles.list}
            ListEmptyComponent={<Text style={styles.empty}>No orders yet. Place your first order!</Text>}
          />
        )
      }
    </View>
  );
}

const styles = StyleSheet.create({
  bg:          { flex: 1, backgroundColor: '#0f172a' },
  header:      { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 },
  title:       { fontSize: 20, fontWeight: '700', color: '#fff' },
  refresh:     { color: '#f97316', fontWeight: '700' },
  list:        { padding: 16, paddingTop: 0 },
  card:        { backgroundColor: '#1e293b', borderRadius: 14, padding: 16, marginBottom: 12 },
  cardTop:     { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 8 },
  orderId:     { color: '#fff', fontWeight: '700', fontSize: 14 },
  badge:       { borderRadius: 6, paddingHorizontal: 10, paddingVertical: 3 },
  badgeText:   { fontSize: 11, fontWeight: '700' },
  date:        { color: '#64748b', fontSize: 13, marginBottom: 4 },
  fulfillment: { color: '#94a3b8', fontSize: 13, marginBottom: 2 },
  payment:     { color: '#22c55e', fontSize: 13, marginBottom: 8 },
  itemsList:   { backgroundColor: '#0f172a', borderRadius: 8, padding: 10, marginBottom: 8 },
  orderItem:   { color: '#94a3b8', fontSize: 13, marginBottom: 2 },
  total:       { color: '#f97316', fontWeight: '800', fontSize: 16 },
  empty:       { color: '#64748b', textAlign: 'center', marginTop: 40, fontSize: 15 },
});
