import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Dimensions,
  SafeAreaView,
  Alert,
} from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';
import database from '@react-native-firebase/database';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Toast from 'react-native-toast-message';
import LinearGradient from 'react-native-linear-gradient';

const { width } = Dimensions.get('window');

const Corrective_action_step1 = ({
  report,
  setActiveStep,
  navigation,
  subItemStatuses,
  setSubItemStatuses,
  resetSubItemStatuses,
  onSave,
}) => {
  const [isSaving, setIsSaving] = useState(false);
  const [isOnline, setIsOnline] = useState(true);
  const [faultyItems, setFaultyItems] = useState([]);
  const [faultyCount, setFaultyCount] = useState(0);

  // Extract faulty items with names based on "Faulty" status
  useEffect(() => {
    if (report?.step2?.selections && report?.step2?.sections) {
      const selections = report.step2.selections;
      const sections = report.step2.sections;
      const items = [];

      sections.forEach((section) => {
        const faultySubItems = section.subItems
          .filter((subItem) => selections[subItem.key] === 'Faulty') // Updated to match JSON
          .map((subItem) => ({
            id: subItem.key,
            name: subItem.itemName,
            fileName: subItem.fileName || 'No file', // Assuming fileName if available
            category: subItem.category,
            sectionName: section.name,
          }));
        if (faultySubItems.length > 0) {
          items.push(...faultySubItems);
        }
      });
      setFaultyItems(items);
      setFaultyCount(items.length); // Update faulty count based on filtered items
    }

    // Load stored corrective action data
    const loadStoredData = async () => {
      if (!report?.id) {
        console.warn('No report ID provided for loading data');
        return;
      }
      try {
        const userUid = await AsyncStorage.getItem('userUid');
        if (!userUid) {
          Toast.show({
            type: 'error',
            text1: 'Authentication Error',
            text2: 'Please log in again.',
          });
          navigation.replace('LoginScreens');
          return;
        }
        const reportRef = database().ref(`/GlobalInspectionReport/admins/${userUid}/${report.id}`);
        const snapshot = await reportRef.once('value');
        const reportData = snapshot.val();
        if (reportData?.correctiveAction?.subItemStatuses) {
          setSubItemStatuses(reportData.correctiveAction.subItemStatuses);
        }
      } catch (error) {
        console.error('Error loading stored corrective action data:', error);
        setIsOnline(false);
        Toast.show({
          type: 'error',
          text1: 'Error',
          text2: 'Failed to load stored data. Working offline.',
        });
      }
    };
    loadStoredData();

    let unsubscribe;
    const setupNetworkListener = async () => {
      try {
        const { NetInfo } = await import('@react-native-community/netinfo');
        unsubscribe = NetInfo.addEventListener((state) => {
          setIsOnline(state.isConnected);
        });
      } catch (error) {
        console.error('Error setting up network listener:', error);
        setIsOnline(false);
      }
    };
    setupNetworkListener();

    return () => {
      if (unsubscribe) unsubscribe();
    };
  }, [report, setSubItemStatuses, navigation]);

  const handleStatusChange = (subItemId, status) => {
    setSubItemStatuses((prev) => ({
      ...prev,
      [subItemId]: status,
    }));
  };

  const queueOperation = async (operation) => {
    try {
      let pendingOperations = [];
      const pendingOperationsRaw = await AsyncStorage.getItem('pendingOperations');
      pendingOperations = pendingOperationsRaw ? JSON.parse(pendingOperationsRaw) : [];
      pendingOperations.push(operation);
      await AsyncStorage.setItem('pendingOperations', JSON.stringify(pendingOperations));
      Toast.show({
        type: 'info',
        text1: 'Offline Mode',
        text2: 'Corrective action data queued for sync when online.',
      });
    } catch (error) {
      console.error('Error queuing operation:', error);
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to queue corrective action data.',
      });
    }
  };

  const checkNetworkStatus = async () => {
    try {
      const { NetInfo } = await import('@react-native-community/netinfo');
      const netInfo = await NetInfo.fetch();
      setIsOnline(netInfo.isConnected ?? false);
      return netInfo.isConnected ?? false;
    } catch (error) {
      console.error('Error checking network status:', error);
      setIsOnline(false);
      return false;
    }
  };

  const saveToFirebase = async () => {
    try {
      const userUid = await AsyncStorage.getItem('userUid');
      if (!userUid || !report?.id) return false;

      const correctiveActionData = {
        subItemStatuses,
        updatedAt: new Date().toISOString(),
        faultyCount, // Store the faulty count in corrective action
      };

      let storedReports = [];
      const storedData = await AsyncStorage.getItem('inspectionReports');
      storedReports = storedData ? JSON.parse(storedData) : [];
      const updatedReports = storedReports.map((r) =>
        r.id === report.id ? { ...r, correctiveAction: correctiveActionData } : r
      );
      if (!storedReports.some((r) => r.id === report.id)) {
        updatedReports.push({ ...report, correctiveAction: correctiveActionData });
      }
      await AsyncStorage.setItem('inspectionReports', JSON.stringify(updatedReports));

      const isOnlineNow = await checkNetworkStatus();
      if (isOnlineNow) {
        await Promise.all([
          database()
            .ref(`/GlobalInspectionReport/admins/${userUid}/${report.id}/correctiveAction`)
            .update(correctiveActionData),
          database()
            .ref(`/GlobalCorrectiveActions/admins/${userUid}/${report.id}`)
            .set(correctiveActionData),
        ]);
        let pendingOperations = [];
        const pendingData = await AsyncStorage.getItem('pendingOperations');
        pendingOperations = pendingData ? JSON.parse(pendingData) : [];
        for (const operation of pendingOperations) {
          if (operation.type === 'correctiveAction' && operation.userId === userUid) {
            await Promise.all([
              database()
                .ref(`/GlobalInspectionReport/admins/${userUid}/${operation.reportId}/correctiveAction`)
                .update(operation.correctiveAction),
              database()
                .ref(`/GlobalCorrectiveActions/admins/${userUid}/${operation.reportId}`)
                .set(operation.correctiveAction),
            ]);
          }
        }
        await AsyncStorage.setItem('pendingOperations', JSON.stringify([]));
      } else {
        await queueOperation({
          type: 'correctiveAction',
          reportId: report.id,
          userId: userUid,
          correctiveAction: correctiveActionData,
        });
      }

      if (onSave) onSave(correctiveActionData);
      return true;
    } catch (error) {
      console.error('Error in saveToFirebase:', error);
      setIsOnline(false);
      await queueOperation({
        type: 'correctiveAction',
        reportId: report.id,
        userId: await AsyncStorage.getItem('userUid') || 'unknown',
        correctiveAction: { subItemStatuses, updatedAt: new Date().toISOString(), faultyCount },
      });
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to save corrective action data. Saved offline.',
      });
      return false;
    }
  };

  const renderSubItem = (subItem, index) => {
    const currentStatus = subItemStatuses[subItem.id] || null;
    return (
      <View style={styles.subItemRow} key={subItem.id}>
        <View style={styles.subItemHeaderRow}>
          <Text style={styles.subItemNumber}>{index + 1}.</Text>
          <View style={styles.subItemDetails}>
            <Text style={styles.subItemText}>{subItem.name}</Text>
            <Text style={styles.subItemFileName}>File: {subItem.fileName}</Text>
          </View>
        </View>
        <View style={styles.statusOptionsRow}>
          {['Fixed', 'Not Fixed', 'No need'].map((status) => {
            let buttonStyle = styles.statusButton;
            let textStyle = styles.statusButtonText;
            if (currentStatus === status) {
              buttonStyle = [styles.statusButton, status === 'Fixed' ? styles.statusButtonSelected : status === 'Not Fixed' ? styles.statusButtonNotFixed : styles.statusButtonNoNeed];
              textStyle = [styles.statusButtonText, styles.statusButtonTextSelected];
            }
            return (
              <TouchableOpacity
                key={status}
                style={buttonStyle}
                onPress={() => handleStatusChange(subItem.id, status)}
              >
                <Text style={textStyle}>{status}</Text>
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
    );
  };

  const handleProceed = async () => {
    if (isSaving || !faultyItems.every((item) => subItemStatuses[item.id])) return;
    setIsSaving(true);
    try {
      const correctiveActionData = { subItemStatuses, updatedAt: new Date().toISOString(), faultyCount };
      let storedReports = [];
      const storedData = await AsyncStorage.getItem('inspectionReports');
      storedReports = storedData ? JSON.parse(storedData) : [];
      const updatedReports = storedReports.map((r) =>
        r.id === report.id ? { ...r, correctiveAction: correctiveActionData } : r
      );
      if (!storedReports.some((r) => r.id === report.id)) {
        updatedReports.push({ ...report, correctiveAction: correctiveActionData });
      }
      await AsyncStorage.setItem('inspectionReports', JSON.stringify(updatedReports));

      const saveSuccess = await saveToFirebase();
      if (saveSuccess) setActiveStep(2);
    } catch (error) {
      console.error('Error in handleProceed:', error);
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'An unexpected error occurred. Data saved offline.',
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    resetSubItemStatuses();
    navigation.replace('Inspection_Report_Home');
  };

  const insets = useSafeAreaInsets();
  const isProceedEnabled = faultyItems.length > 0 && faultyItems.every((item) => subItemStatuses[item.id]);

  if (!report || !report.step1 || !report.step2) {
    return (
      <SafeAreaProvider>
        <SafeAreaView style={styles.container} edges={['top', 'left', 'right']}>
          <Text style={styles.noItemsText}>No report data available</Text>
        </SafeAreaView>
      </SafeAreaProvider>
    );
  }

  return (
    <SafeAreaProvider>
      <SafeAreaView style={styles.container} edges={['top', 'left', 'right']}>
        <View style={styles.infoRow}>
          <Text style={styles.infoLabel}>Report#</Text>
          <Text style={styles.infoValue}>{report.step1.requestNumber || 'N/A'}</Text>
        </View>
        <View style={styles.infoRow}>
          <Text style={styles.infoLabel}>Vehicle#</Text>
          <Text style={styles.infoValue}>{report.step1.selectedEquipment?.equipmentName || 'N/A'}</Text>
        </View>
        <View style={styles.blueHeaderBar}>
          <Text style={styles.blueHeaderText}>Corrective Action Items ({faultyCount})</Text>
        </View>
        {faultyItems.length > 0 ? (
          <FlatList
            data={[{ subItems: faultyItems }]}
            renderItem={({ item }) => (
              <View>
                {item.subItems.map((subItem, idx) => renderSubItem(subItem, idx))}
              </View>
            )}
            keyExtractor={(item) => item.subItems[0]?.id || 'default'}
            style={styles.checklist}
          />
        ) : (
          <Text style={styles.noItemsText}>No faulty items found</Text>
        )}
        <View style={[styles.bottomButtonBar, { bottom: insets.bottom }]}>
          <TouchableOpacity
            style={styles.bottomBarButtonLeft}
            onPress={() => {
              Alert.alert(
                'Cancel',
                'Are you sure you want to cancel? Your changes will not be saved.',
                [
                  { text: 'No', style: 'cancel' },
                  { text: 'Yes', style: 'destructive', onPress: handleCancel },
                ]
              );
            }}
            disabled={isSaving}
          >
            <MaterialIcons name="chevron-left" size={20} color="#1676b7" />
            <Text style={styles.bottomBarButtonText}>Cancel</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.bottomBarButtonRight}
            onPress={handleProceed}
            disabled={!isProceedEnabled || isSaving}
          >
            <Text style={[styles.bottomBarButtonText, !isProceedEnabled && styles.bottomBarButtonTextDisabled]}>Next</Text>
            <MaterialIcons name="chevron-right" size={20} color={isProceedEnabled ? "#1676b7" : "#ccc"} />
          </TouchableOpacity>
        </View>
      </SafeAreaView>
      <Toast />
    </SafeAreaProvider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: width * 0.06,
    paddingTop: width * 0.03,
    paddingBottom: 0,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  infoLabel: {
    color: '#1676b7',
    fontSize: width * 0.038,
    fontWeight: '500',
  },
  infoValue: {
    color: '#1676b7',
    fontSize: width * 0.038,
    fontWeight: '600',
  },
  blueHeaderBar: {
    backgroundColor: '#195c85',
    alignItems: 'center',
    justifyContent: 'center',
    height: width * 0.09,
    marginTop: width * 0.04,
    marginBottom: width * 0.04,
    width: '90%',
    alignSelf: 'center',
  },
  blueHeaderText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: width * 0.045,
  },
  checklist: {
    flex: 1,
    paddingHorizontal: width * 0.06,
  },
  subItemRow: {
    marginBottom: width * 0.09,
    paddingVertical: width * 0.025,
  },
  subItemHeaderRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: width * 0.02,
  },
  subItemNumber: {
    fontWeight: 'bold',
    fontSize: width * 0.04,
    color: '#222',
    marginRight: 4,
  },
  subItemDetails: {
    flex: 1,
  },
  subItemText: {
    flex: 1,
    fontSize: width * 0.04,
    color: '#222',
    fontWeight: '500',
  },
  subItemFileName: {
    fontSize: width * 0.035,
    color: '#666',
    fontStyle: 'italic',
  },
  statusOptionsRow: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginTop: width * 0.01,
    marginBottom: width * 0.01,
  },
  statusButton: {
    flex: 1,
    backgroundColor: '#f2f6fa',
    paddingVertical: width * 0.025,
    marginRight: 6,
    alignItems: 'center',
    borderRadius: 2,
  },
  statusButtonSelected: {
    backgroundColor: '#195c85',
  },
  statusButtonNotFixed: {
    backgroundColor: '#dc3545',
  },
  statusButtonNoNeed: {
    backgroundColor: '#808080',
  },
  statusButtonText: {
    color: '#195c85',
    fontWeight: '600',
    fontSize: width * 0.038,
  },
  statusButtonTextSelected: {
    color: '#fff',
  },
  bottomButtonBar: {
    position: 'absolute',
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    borderTopWidth: 1,
    borderTopColor: '#ddd',
    height: 48,
    paddingHorizontal: width * 0.06,
    zIndex: 10,
  },
  bottomBarButtonLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'transparent',
    borderWidth: 0,
    paddingVertical: 8,
    paddingHorizontal: 4,
  },
  bottomBarButtonRight: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'transparent',
    borderWidth: 0,
    paddingVertical: 8,
    paddingHorizontal: 4,
  },
  bottomBarButtonText: {
    color: '#1676b7',
    fontSize: width * 0.045,
    fontWeight: 'bold',
    textAlign: 'center',
    marginHorizontal: 2,
  },
  bottomBarButtonTextDisabled: {
    color: '#ccc',
  },
  noItemsText: {
    fontSize: width * 0.04,
    color: '#666',
    textAlign: 'center',
    marginTop: width * 0.05,
  },
});

export default Corrective_action_step1;