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

const STATUSES: OrderStatus[] = [
  'pending', 'confirmed', 'out_for_delivery', 'delivered', 'cancelled',
];

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

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

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

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

  const handleStatus = (order: Order) => {
    Alert.alert(
      'Update Status',
      `Order #${order.id.slice(-8).toUpperCase()}`,
      STATUSES.map(s => ({
        text: s.replace(/_/g, ' ').toUpperCase(),
        onPress: async () => {
          try {
            await adminUpdateOrderStatus(order.id, s);
            await loadOrders();
          } catch {
            Alert.alert('Error', 'Could not update status.');
          }
        },
      })),
    );
  };

  const renderItem = ({ item }: { item: Order }) => (
    <View style={styles.card}>
      <View style={styles.cardTop}>
        <Text style={styles.orderId}>#{item.id.slice(-8).toUpperCase()}</Text>
        <TouchableOpacity
          style={[styles.badge, { backgroundColor: STATUS_COLORS[item.status] + '22' }]}
          onPress={() => handleStatus(item)}
        >
          <Text style={[styles.badgeText, { color: STATUS_COLORS[item.status] }]}>
            {item.status.replace(/_/g, ' ').toUpperCase()} ▼
          </Text>
        </TouchableOpacity>
      </View>
      <Text style={styles.customer}>
        👤 {item.customer_name} | {item.customer_phone}
      </Text>
      <Text style={styles.meta}>
        {item.fulfillment === 'delivery' ? '🚚 Delivery' : '🏪 Pickup'}
        {item.address ? ` — ${item.address}` : ''}
      </Text>
      <Text style={styles.meta}>💵 Cash on Delivery</Text>
      {item.items?.map(oi => (
        <Text key={oi.id} style={styles.item}>
          • {oi.product_name} × {oi.quantity}
        </Text>
      ))}
      <Text style={styles.total}>₦{Number(item.total).toLocaleString()}</Text>
      <Text style={styles.date}>📅 {new Date(item.created_at).toLocaleDateString()}</Text>
    </View>
  );

  return (
    <View style={styles.bg}>
      <View style={styles.header}>
        <Text style={styles.title}>🚚 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.</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' },
  customer: { color: '#94a3b8', fontSize: 13, marginBottom: 2 },
  meta:     { color: '#64748b', fontSize: 13, marginBottom: 2 },
  item:     { color: '#94a3b8', fontSize: 12, marginLeft: 8 },
  total:    { color: '#f97316', fontWeight: '800', fontSize: 16, marginTop: 8 },
  date:     { color: '#475569', fontSize: 11, marginTop: 4 },
  empty:    { color: '#64748b', textAlign: 'center', marginTop: 40 },
});
