import React, { useCallback } from 'react';
import { View, Text, ScrollView } from 'react-native';
import { useAppTheme } from '@theme';
import { WalletIcon } from '@icons';
import { useAppDispatch, useAppSelector } from '@store';
import { formatCurrency, formatDate } from '@utils';
import { getStyles } from './earningsScreen.styles';
import { getCompletedDeliveries } from '../jobsScreen';
import { useFocusEffect } from '@react-navigation/native';

export const EarningsScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);

  // const { todayEarnings, completedCount, onlineMinutes } = useAppSelector(
  //   state => state.earnings,
  // );

  const dispatch = useAppDispatch();
  // const { jobHistory } = useAppSelector(state => state.job);
  const { completedDeliveries } = useAppSelector(state => state.deliveries)
  // console.log('completedDeliveries', completedDeliveries)

  // Default mock jobs history if none completed yet
  // const defaultHistory: {
  //   orderId: string;
  //   time: string;
  //   amount: string;
  //   paymentType: 'online' | 'cod';
  // }[] = [
  //     {
  //       orderId: '#ORD125487',
  //       time: '12:35 PM',
  //       amount: '78.0',
  //       paymentType: 'online',
  //     },
  //     {
  //       orderId: '#ORD125422',
  //       time: '11:15 AM',
  //       amount: '65.0',
  //       paymentType: 'cod',
  //     },
  //     {
  //       orderId: '#ORD125389',
  //       time: '09:40 AM',
  //       amount: '120.0',
  //       paymentType: 'online',
  //     },
  //     {
  //       orderId: '#ORD125310',
  //       time: 'Yesterday',
  //       amount: '85.0',
  //       paymentType: 'online',
  //     },
  //   ];

  const totalAmount = completedDeliveries?.reduce((acc, item) => {
    return acc + Number(item?.order?.deliveryFee);
  }, 0);

  // console.log('totalAmount', totalAmount)

  useFocusEffect(useCallback(() => {
    dispatch(getCompletedDeliveries());
  }, [dispatch]))
  // const deliveryList = Array.isArray(completedDeliveries)
  //   ? completedDeliveries
  //   : (completedDeliveries as any)?.data || (completedDeliveries as any)?.bankAccounts || [];

  // const displayHistory =
  //   deliveryList?.length > 0
  //     ? deliveryList
  //       .map((delivery: any) => ({
  //         orderId: delivery.orderId,
  //         time: delivery.deliveredAt
  //           ? new Date(delivery.deliveredAt).toLocaleTimeString([], {
  //             hour: '2-digit',
  //             minute: '2-digit',
  //           })
  //           : 'Delivered',
  //         amount: delivery?.totalAmount,
  //         paymentType: delivery?.paymentMethod,
  //       }))
  //       .concat(defaultHistory)
  //     : defaultHistory;

  // const formatOnlineTime = (mins: number) => {
  //   const hours = Math.floor(mins / 60);
  //   const remainingMins = mins % 60;
  //   return `${hours}h ${remainingMins < 10 ? `0${remainingMins}` : remainingMins
  //     }m`;
  // };

  return (
    <View style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContainer}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.headerContainer}>
          <Text style={styles.title}>Earnings</Text>
        </View>

        {/* Total Earnings Card */}
        <View style={styles.summaryCard}>
          <Text style={styles.summaryTitle}>Total Earnings</Text>
          <Text style={styles.totalAmount}>
            {formatCurrency(totalAmount || 0)}
          </Text>

          {/* <View style={styles.statsRow}>
            <View style={styles.statBox}>
              <Text style={styles.statVal}>{completedDeliveries?.length}</Text>
              <Text style={styles.statLabel}>Deliveries</Text>
            </View> */}

          {/* <View style={styles.statDivider} />

            <View style={styles.statBox}>
              <Text style={styles.statVal}>
                {formatOnlineTime(onlineMinutes)}
              </Text>
              <Text style={styles.statLabel}>Online Time</Text>
            </View>

            <View style={styles.statDivider} />

            <View style={styles.statBox}>
              <Text style={styles.statVal}>₹78.50</Text>
              <Text style={styles.statLabel}>Avg / Order</Text>
            </View>*/}
          {/* </View> */}
        </View>

        {/* Recent Deliveries List */}
        <View style={styles.listSection}>
          <Text style={styles.sectionTitle}>Recent Deliveries</Text>

          {completedDeliveries?.map((item, index) => (
            <View key={index} style={styles.earningItem}>
              <View style={styles.itemLeft}>
                <View style={styles.iconContainer}>
                  <WalletIcon size={20} color={colors.primary} />
                </View>
                <View>
                  <Text style={styles.orderIdText}>{item.orderId}</Text>
                  <Text style={styles.timeText}>{formatDate(item?.deliveredAt || '')}</Text>
                </View>
              </View>

              <View style={styles.itemRight}>
                <Text style={styles.itemAmount}>
                  +{formatCurrency(Number(item?.order?.deliveryFee))}
                </Text>
                <View style={styles.paymentBadge}>
                  <Text style={styles.paymentText}>
                    {/* {item?.order?.pa.toUpperCase()} */}
                  </Text>
                </View>
              </View>
            </View>
          ))}
        </View>
      </ScrollView>
    </View>
  );
};

export default EarningsScreen;
