import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity } from 'react-native';
import { useAppTheme } from '@theme';
import { OrderCard, EmptyState } from '@components';
import { useAppDispatch, useAppSelector } from '@store';
import { ClipboardIcon } from '@icons';
import { getStyles } from './jobsScreen.styles';
import { getAllActiveDeliveries, getCompletedDeliveries } from './thunk';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AppStackParamList } from '@navigation/navigationTypes';
import { RouteNames } from '@utils/constants';

export const JobsScreen: React.FC = () => {
  const navigation =
    useNavigation<NativeStackNavigationProp<AppStackParamList>>();
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const dispatch = useAppDispatch();

  const [activeTab, setActiveTab] = useState<'active' | 'history'>('active');
  const { activeJob, jobHistory } = useAppSelector(state => state.job);
  const { activeDeliveries, completedDeliveries } = useAppSelector(
    state => state.deliveries,
  );

  // console.log(activeDeliveries, 'activeDeliveries');

  useFocusEffect(
    useCallback(() => {
      dispatch(getAllActiveDeliveries());
      dispatch(getCompletedDeliveries());
    }, [dispatch]),
  );

  // Default history mock jobs
  // const defaultHistory = [
  //   {
  //     pickupName: 'Cafe Coffee Day',
  //     pickupAddress: 'MG Road, Bengaluru',
  //     dropName: 'Rohit Sharma',
  //     dropAddress: 'Koramangala 4th Block, Bengaluru',
  //     amount: '78.0',
  //     distance: '1.2',
  //     itemCount: 2,
  //     paymentType: 'online',
  //   },
  //   {
  //     pickupName: 'Pizza Hut',
  //     pickupAddress: 'Indiranagar, Bengaluru',
  //     dropName: 'Aishwarya Sen',
  //     dropAddress: 'Domlur Stage 2, Bengaluru',
  //     amount: '95.0',
  //     distance: '3.8',
  //     itemCount: 3,
  //     paymentType: 'cod',
  //   },
  //   {
  //     pickupName: 'Burgers & Co',
  //     pickupAddress: 'Koramangala 5th Block',
  //     dropName: 'Sameer Khan',
  //     dropAddress: 'HSR Layout Sector 3, Bengaluru',
  //     amount: '110.0',
  //     distance: '4.5',
  //     itemCount: 1,
  //     paymentType: 'online',
  //   },
  // ];

  return (
    <View style={styles.container}>
      <View style={styles.headerContainer}>
        <Text style={styles.title}>Jobs</Text>
      </View>

      {/* Tabs Selector */}
      <View style={styles.tabBar}>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'active' && styles.tabActive]}
          activeOpacity={0.8}
          onPress={() => setActiveTab('active')}
        >
          <Text
            style={[
              styles.tabText,
              activeTab === 'active' && styles.tabTextActive,
            ]}
          >
            Active / Upcoming
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.tab, activeTab === 'history' && styles.tabActive]}
          activeOpacity={0.8}
          onPress={() => setActiveTab('history')}
        >
          <Text
            style={[
              styles.tabText,
              activeTab === 'history' && styles.tabTextActive,
            ]}
          >
            History
          </Text>
        </TouchableOpacity>
      </View>

      <ScrollView
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
      >
        {activeTab === 'active' ? (
          // Active job tab
          activeDeliveries?.delivery ? (
            <View style={styles.cardWrapper}>
              <OrderCard
                pickupName={
                  activeDeliveries?.delivery?.order?.pickupAddress?.city
                }
                pickupAddress={
                  activeDeliveries?.delivery?.order?.pickupAddress?.addressLine1
                }
                dropName={activeDeliveries?.delivery?.order?.dropAddress?.city}
                dropAddress={
                  activeDeliveries?.delivery?.order?.dropAddress?.addressLine1
                }
                amount={activeDeliveries?.delivery?.order?.totalAmount}
                distance={
                  activeDeliveries?.delivery?.estimatedDistanceKm || '0'
                }
                itemCount={
                  activeDeliveries?.delivery?.order?.orderItems?.length
                }
                paymentType={activeDeliveries?.delivery?.order?.paymentMethod}
                onPress={() =>
                  navigation.navigate(RouteNames.OrderPickedUp, {
                    jobId: activeDeliveries?.delivery?.id,
                  })
                }
              />
            </View>
          ) : (
            <View style={styles.emptyStateContainer}>
              <ClipboardIcon size={48} color={colors.placeholder} />
              <Text style={styles.emptyStateText}>
                No active deliveries right now
              </Text>
            </View>
          )
        ) : (
          // History tab
          <View>
            {completedDeliveries && completedDeliveries?.length > 0 ? (
              completedDeliveries?.map((job, idx) => (
                <View key={idx} style={styles.cardWrapper}>
                  <OrderCard
                    pickupName={
                      job.order.merchant.name || job.order.pickupAddress.city
                    }
                    pickupAddress={job.order.pickupAddress.addressLine1}
                    dropName={job.order.dropAddress.city}
                    dropAddress={job.order.dropAddress.addressLine1}
                    amount={job.order.totalAmount}
                    distance={job.estimatedDistanceKm?.toString() || '0'}
                    // itemCount={job.order?.}
                    // paymentType={job.order.paymentMethod}
                  />
                </View>
              ))
            ) : (
              <View style={styles.emptyStateContainer}>
                <ClipboardIcon size={48} color={colors.placeholder} />
                <Text style={styles.emptyStateText}>No history found</Text>
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  );
};

export default JobsScreen;
