import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useAppTheme } from '@theme';
import { ScreenHeader, PrimaryButton } from '@components';
import { useAppDispatch, useAppSelector } from '@store';
import { advanceJobStatus } from '@store/commonReducers/job';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AppStackParamList } from '@navigation/navigationTypes';
import { RouteNames, JobStatus } from '@utils/constants';
import { getStyles } from './confirmPickupScreen.styles';

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

  const activeJob = useAppSelector((state) => state.job.activeJob);

  // Togglable checklist for food/merchandise items
  const [checkedItems, setCheckedItems] = useState<{ [key: number]: boolean }>({
    0: true,
    1: true,
  });

  const items = [
    { id: 0, name: 'Cappuccino (Medium)', qty: 1 },
    { id: 1, name: 'Chocolate Croissant', qty: 1 },
  ];

  const handleToggleCheck = (id: number) => {
    setCheckedItems((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  const handlePickedUp = () => {
    // Ensure all items are checked before picking up
    const allChecked = items.every((item) => checkedItems[item.id]);
    if (!allChecked) {
      Alert.alert('Incomplete Verification', 'Please confirm that you have checked all items before picking up.');
      return;
    }

    dispatch(advanceJobStatus(JobStatus.PickedUp));
    navigation.navigate(RouteNames.OrderPickedUp);
  };

  const handleReportIssue = () => {
    Alert.alert('Report Issue', 'Helpdesk notified. Support agent will contact you shortly.');
  };

  if (!activeJob) return null;

  return (
    <View style={styles.container}>
      <ScreenHeader
        title="Confirm Pickup"
        showBack={true}
        onBack={() => navigation.goBack()}
      />

      <ScrollView contentContainerStyle={styles.scrollContainer} showsVerticalScrollIndicator={false}>
        {/* Order ID Banner */}
        <View style={styles.orderHeader}>
          <Text style={styles.orderIdText}>Order ID: {activeJob.orderId}</Text>
          <View style={styles.paymentTag}>
            <Text style={styles.paymentTagText}>ONLINE PAID</Text>
          </View>
        </View>

        {/* Merchant Info */}
        <View style={styles.merchantInfoCard}>
          <Text style={styles.merchantLabel}>Pickup Store</Text>
          <Text style={styles.merchantName}>{activeJob.pickupName}</Text>
        </View>

        {/* Items Checklist */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Verify Items ({items.length})</Text>
          {items.map((item) => (
            <TouchableOpacity
              key={item.id}
              style={styles.itemRow}
              activeOpacity={0.8}
              onPress={() => handleToggleCheck(item.id)}
            >
              <View style={[styles.checkbox, checkedItems[item.id] && styles.checkboxChecked]}>
                {checkedItems[item.id] && <Text style={styles.checkSign}>✓</Text>}
              </View>
              <Text style={styles.itemNameText}>{item.name}</Text>
              <Text style={styles.itemQtyText}>x{item.qty}</Text>
            </TouchableOpacity>
          ))}
        </View>

        {/* Action Buttons */}
        <View style={styles.btnRow}>
          <PrimaryButton
            title="Issue"
            onPress={handleReportIssue}
            style={styles.issueBtn}
            textStyle={{ color: colors.error }}
          />
          <PrimaryButton
            title="Picked Up"
            onPress={handlePickedUp}
            style={styles.pickedUpBtn}
          />
        </View>
      </ScrollView>
    </View>
  );
};

export default ConfirmPickupScreen;
