import React, { useEffect } from 'react';
import { View, Text, ScrollView, ActivityIndicator } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { RouteProp } from '@react-navigation/native';
import { Header, OrderStatusTimeline } from '@components';
import { useAppTheme } from '@theme';
import { getStyles } from './orderDetailsScreen.styles';
import { RootState, useAppDispatch, useAppSelector } from '@store';
import { getOrderByIdThunk } from '../checkoutPaymentScreen';
import { formatDate, formatTime } from '@utils/helper';
import { AppStackParamList } from '../../../navigation/appStack';

type OrderDetailsRouteProp = RouteProp<AppStackParamList, 'OrderDetailsScreen'>;
type OrderDetailsNavProp = StackNavigationProp<AppStackParamList>;

export const OrderDetailsScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const route = useRoute<OrderDetailsRouteProp>();
  const navigation = useNavigation<OrderDetailsNavProp>();
  const dispatch = useAppDispatch();

  const orderId = route.params?.orderId;

  const { orderDetails, orderDetailsLoading, orderDetailsError } =
    useAppSelector((state: RootState) => state.paymentMethods);

  useEffect(() => {
    if (orderId) {
      dispatch(getOrderByIdThunk(orderId));
    }
  }, [dispatch, orderId]);

  if (orderDetailsLoading) {
    return (
      <View style={styles.container}>
        <Header title="Order Details" onBack={() => navigation.goBack()} />
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
          <Text style={styles.loadingText}>Fetching order details...</Text>
        </View>
      </View>
    );
  }

  if (orderDetailsError || !orderDetails) {
    return (
      <View style={styles.container}>
        <Header title="Order Details" onBack={() => navigation.goBack()} />
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>
            {orderDetailsError || 'Could not load order details.'}
          </Text>
        </View>
      </View>
    );
  }

  const orderDate = orderDetails.createdAt
    ? `${formatDate(orderDetails.createdAt)} at ${formatTime(
        orderDetails.createdAt,
      )}`
    : '';

  return (
    <View style={styles.container}>
      <Header title="Order Details" onBack={() => navigation.goBack()} />
      <ScrollView contentContainerStyle={styles.content}>
        {/* Top Info Section */}
        <View style={styles.section}>
          <View style={styles.headerRow}>
            <Text style={styles.orderNumber}>
              Order {orderDetails.orderNumber?.split('-').pop() || ''}
            </Text>
            <View style={styles.statusBadge}>
              <Text style={styles.statusText}>{orderDetails.status}</Text>
            </View>
          </View>
          <Text style={styles.dateText}>Placed on {orderDate}</Text>
          <Text style={styles.dateText}>
            Payment: {orderDetails.paymentMethod}
          </Text>

          {/* Merchant Info */}
          <View style={styles.merchantRow}>
            <View style={styles.merchantIcon}>
              <Text>🏪</Text>
            </View>
            <Text style={styles.merchantName}>
              {orderDetails.merchant?.name || 'Store'}
            </Text>
          </View>
        </View>

        {/* Order Status Timeline Section */}
        <View style={styles.timelineSection}>
          <Text style={styles.sectionTitle}>Order Status</Text>
          <OrderStatusTimeline
            tracking={orderDetails.tracking}
            currentStatus={orderDetails.status}
          />
        </View>

        {/* Order Items Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Order Items</Text>
          {orderDetails.orderItems?.map((item, index) => (
            <View key={item.id || index} style={styles.itemRow}>
              <View style={styles.itemInfo}>
                <View style={styles.itemQuantityBadge}>
                  <Text style={styles.itemQuantityText}>{item.quantity}x</Text>
                </View>
                <Text style={styles.itemName}>{item.name}</Text>
              </View>
              <Text style={styles.itemPrice}>₹{item.totalAmount}</Text>
            </View>
          ))}
        </View>

        {/* Bill Summary Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Bill Summary</Text>
          <View style={styles.billRow}>
            <Text style={styles.billLabel}>Item Total</Text>
            <Text style={styles.billValue}>₹{orderDetails.subtotal}</Text>
          </View>
          <View style={styles.billRow}>
            <Text style={styles.billLabel}>Delivery Fee</Text>
            <Text style={styles.billValue}>₹{orderDetails.deliveryFee}</Text>
          </View>
          <View style={styles.billRow}>
            <Text style={styles.billLabel}>Platform Fee</Text>
            <Text style={styles.billValue}>₹{orderDetails.platformFee}</Text>
          </View>
          <View style={styles.billRow}>
            <Text style={styles.billLabel}>Taxes</Text>
            <Text style={styles.billValue}>₹{orderDetails.taxAmount}</Text>
          </View>

          <View style={styles.billDivider} />

          <View style={styles.billRow}>
            <Text style={styles.billTotalLabel}>Grand Total</Text>
            <Text style={styles.billTotalValue}>
              ₹{orderDetails.totalAmount}
            </Text>
          </View>
        </View>

        {/* Delivery Address Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Delivery Details</Text>
          <Text style={styles.addressType}>
            {orderDetails.dropAddress?.label || 'Home'}
          </Text>
          <Text style={styles.addressText}>
            {orderDetails.dropAddress?.houseNumber
              ? `${orderDetails.dropAddress.houseNumber}, `
              : ''}
            {orderDetails.dropAddress?.addressLine1}
          </Text>
          <Text style={styles.addressText}>
            {orderDetails.dropAddress?.landmark
              ? `Landmark: ${orderDetails.dropAddress.landmark}`
              : ''}
          </Text>
          <Text style={styles.addressText}>
            Phone: {orderDetails.dropAddress?.phone}
          </Text>
        </View>

        {/* Payment Info */}
        {orderDetails.payments && orderDetails.payments.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Payment Details</Text>
            <View style={styles.paymentRow}>
              <Text style={styles.paymentIcon}>💳</Text>
              <Text style={styles.paymentText}>
                Paid via {orderDetails.payments[0].method} (
                {orderDetails.payments[0].status})
              </Text>
            </View>
          </View>
        )}
      </ScrollView>
    </View>
  );
};

export default OrderDetailsScreen;
