import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity } from 'react-native';
import {
  useNavigation,
  CompositeNavigationProp,
} from '@react-navigation/native';
import { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './myOrdersScreen.styles';
import { Header, OrderHistoryCard } from '@components';
import { useAppTheme } from '@theme';
import { AppStackParamList } from '../../../navigation/appStack';
import { MainTabParamList } from '../../../navigation/mainTabNavigator';
import { RootState, useAppDispatch, useAppSelector } from '@store';
import { getOrderHistoryThunk } from '../checkoutPaymentScreen';
import { formatDate } from '@utils/helper';

type MyOrdersNavProp = CompositeNavigationProp<
  BottomTabNavigationProp<MainTabParamList, 'MyOrdersScreen'>,
  StackNavigationProp<AppStackParamList>
>;

const TABS = ['All', 'Ongoing', 'Completed'];
const mockOrders = [
  {
    id: 'ORD-591283',
    providerName: 'Pizza Planet',
    providerImage: '',
    orderDate: '29 Jun 2026',
    status: 'Delivered',
    total: 599,
  },
  {
    id: 'ORD-771239',
    providerName: 'Fresh Mart',
    providerImage: '',
    orderDate: '28 Jun 2026',
    status: 'Ongoing',
    total: 349,
  },
  {
    id: 'ORD-108239',
    providerName: 'Burger Barn',
    providerImage: '',
    orderDate: '27 Jun 2026',
    status: 'Delivered',
    total: 449,
  },
];

export const MyOrdersScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<MyOrdersNavProp>();
  const [activeTab, setActiveTab] = useState('All');
  const dispatch = useAppDispatch();
  const { orderHistory } = useAppSelector(
    (state: RootState) => state.paymentMethods,
  );
  console.log(orderHistory);

  useEffect(() => {
    dispatch(getOrderHistoryThunk());
  }, []);

  const ONGOING_STATUSES = [
    'PENDING',
    'CONFIRMED',
    'PREPARING',
    'READY_FOR_PICKUP',
    'OUT_FOR_DELIVERY',
  ];
  const COMPLETED_STATUSES = ['DELIVERED', 'CANCELLED'];

  const orders = Array.isArray(orderHistory) ? orderHistory : [];

  const filteredOrders =
    activeTab === 'All'
      ? orders
      : activeTab === 'Ongoing'
      ? orders.filter(o => ONGOING_STATUSES.includes(o.status))
      : orders.filter(o => COMPLETED_STATUSES.includes(o.status));

  return (
    <View style={styles.container}>
      <Header title="My Orders" />
      <View style={styles.tabRow}>
        {TABS.map(tab => (
          <TouchableOpacity
            key={tab}
            style={[styles.tab, activeTab === tab && styles.tabActive]}
            onPress={() => setActiveTab(tab)}
            activeOpacity={0.7}
          >
            <Text
              style={[
                styles.tabText,
                activeTab === tab && styles.tabTextActive,
              ]}
            >
              {tab}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
      <FlatList
        data={filteredOrders}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <OrderHistoryCard
            providerName={item?.merchant?.name || ''}
            providerImage={item?.merchant?.imageUrl || ''}
            orderDate={formatDate(item?.createdAt)}
            status={item.status}
            total={Number(item?.totalAmount) || 0}
            items={item.orderItems}
            onReorder={() => {
              navigation.navigate('ProviderDetailsScreen', {
                providerId: 'p1',
                providerName: item?.merchant?.name || '',
              });
            }}
            onDetails={() => {
              if (
                item?.status === 'PENDING' ||
                item?.status === 'CONFIRMED' ||
                item?.status === 'PREPARING' ||
                item?.status === 'READY_FOR_PICKUP' ||
                item?.status === 'OUT_FOR_DELIVERY'
              ) {
                navigation.navigate('OrderDetailsScreen', {
                  orderId: item.id,
                });
              } else {
                navigation.navigate('OrderDeliveredScreen', {
                  orderId: item.id,
                });
              }
            }}
          />
        )}
        contentContainerStyle={styles.list}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={styles.emptyText}>No orders found</Text>
          </View>
        }
      />
    </View>
  );
};
