import React from 'react';
import {View, ScrollView, StyleSheet} from 'react-native';
import {Text} from '../Text';
import {Button} from '../Button';
import {Colors, fontSz, ms, formatAsCurrency} from '../../utils';
import {SavingsDetailType} from '../../utils/types';
import {CreateSavingsParams, UpdateSavingsParams} from '../../services/types';
import {Modal} from '../Common/modal';

type Props = {
  visible: boolean;
  editMode: boolean;
  newData: CreateSavingsParams | UpdateSavingsParams;
  existingData?: SavingsDetailType;
  onConfirm: () => void;
  onCancel: () => void;
  isLoading: boolean;
  savingsCategoryName: string;
  isLockedCategory?: boolean;
};

type ComparisonRowProps = {
  label: string;
  oldValue?: string | number | boolean;
  newValue: string | number | boolean;
  isChanged?: boolean;
};

const ComparisonRow = ({label, oldValue, newValue, isChanged}: ComparisonRowProps) => {
  // Helper function to render color swatch
  const renderColorValue = (colorValue: string | number | boolean, isOld: boolean = false) => {
    if (label === 'Color' && typeof colorValue === 'string' && colorValue !== 'Not set') {
      return (
        <View
          style={[
            styles.colorSwatch,
            { backgroundColor: colorValue },
          ]}
        />
      );
    }

    // Default text rendering for non-color values
    return (
      <Text
        fontSize={fontSz(16)}
        fontFamily={isOld ? 'Gordita-Regular' : 'Gordita-Medium'}
        fontWeight={isOld ? '400' : '600'}
        text={`${colorValue}`}
        color={Colors.baseBlueText}
        style={[
          isOld && isChanged && styles.strikeThrough,
        ]}
      />
    );
  };

  return (
    <View style={styles.comparisonRow}>
      <Text
        fontSize={fontSz(12)}
        fontFamily="Gordita-Medium"
        fontWeight="500"
        text={label}
        color={Colors.inputBackgroundLight}
        style={styles.labelText}
      />
      <View style={styles.valueContainer}>
        {oldValue !== undefined ? (
          <>
            <View style={styles.oldValueContainer}>
              {renderColorValue(oldValue, true)}
            </View>
            {isChanged && (
              <View style={styles.arrowContainer}>
                <Text
                  fontSize={fontSz(16)}
                  fontFamily="Gordita-Medium"
                  fontWeight="600"
                  text="→"
                  color={Colors.inputBackgroundLight}
                />
              </View>
            )}
            <View style={styles.newValueContainer}>
              {renderColorValue(newValue, false)}
            </View>
          </>
        ) : (
          <View style={styles.singleValueContainer}>
            {renderColorValue(newValue, false)}
          </View>
        )}
      </View>
    </View>
  );
};

const SavingsConfirmation = (props: Props) => {
  const {visible, editMode, newData, existingData, onConfirm, onCancel, isLoading, savingsCategoryName, isLockedCategory} = props;

  // Helper function to format currency values
  const formatCurrencyValue = (value: number) => {
    return formatAsCurrency(value / 100); // Convert from kobo to naira
  };

  // Helper function to format dates
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  // Helper function to format frequency
  const getFrequencyText = (frequency?: number) => {
    switch (frequency) {
      case 0: return 'None';
      case 1: return 'Daily';
      case 2: return 'Weekly';
      case 3: return 'Monthly';
      case 4: return 'Save as you collect';
      default: return 'Not set';
    }
  };

  // Helper function to get frequency-specific amount label
  const getPeriodicAmountLabel = (frequency?: number) => {
    switch (frequency) {
      case 1: return 'Daily Savings Amount';
      case 2: return 'Weekly Savings Amount';
      case 3: return 'Monthly Savings Amount';
      default: return 'Periodic Amount';
    }
  };

  // Helper function to calculate lock duration in months
  const calculateLockDuration = (startDate?: string, endDate?: string) => {
    if (!startDate || !endDate) {return 'Not set';}

    const start = new Date(startDate);
    const end = new Date(endDate);

    const months = ((end.getFullYear() - start.getFullYear()) * 12) +
                   (end.getMonth() - start.getMonth());

    return `${months} ${months === 1 ? 'month' : 'months'}`;
  };

  // Helper function to check if values are different
  const hasChanged = (oldVal: any, newVal: any) => {
    // Handle date comparisons by comparing formatted strings
    if (oldVal && newVal && typeof oldVal === 'string' && typeof newVal === 'string') {
      // If both look like dates, compare their formatted versions
      const oldDate = new Date(oldVal);
      const newDate = new Date(newVal);

      if (!isNaN(oldDate.getTime()) && !isNaN(newDate.getTime())) {
        return formatDate(oldVal) !== formatDate(newVal);
      }
    }

    return oldVal !== newVal;
  };

    const renderNewAccountSummary = () => (
    <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{paddingTop: 0}}>
      <View style={[styles.summaryContainer, {marginTop: 0}]}>
        {/* Basic Information Section */}
        <View style={styles.sectionContainer}>
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Bold"
            fontWeight="700"
            text="ACCOUNT DETAILS"
            color={Colors.purple60}
            style={styles.sectionTitle}
          />
          <ComparisonRow
            label="Account Name"
            newValue={newData.accountName}
          />
          <ComparisonRow
            label={isLockedCategory ? 'Lock Amount' : 'Savings Target'}
            newValue={formatCurrencyValue(newData.savingTarget)}
          />
          <ComparisonRow
            label="Category"
            newValue={savingsCategoryName}
          />

          {/* Show Lock Duration for locked savings */}
          {isLockedCategory && newData.startDate && newData.endDate && (
            <ComparisonRow
              label="Lock Duration"
              newValue={calculateLockDuration(newData.startDate, newData.endDate)}
            />
          )}
        </View>

        {/* Auto-Save Configuration - Hide for locked savings */}
        {!isLockedCategory && (
          <View style={styles.sectionContainer}>
            <Text
              fontSize={fontSz(14)}
              fontFamily="Gordita-Bold"
              fontWeight="700"
              text="SAVINGS PLAN"
              color={Colors.purple60}
              style={styles.sectionTitle}
            />
            <ComparisonRow
              label="Auto-Save"
              newValue={newData.autoSave ? 'Enabled' : 'Disabled'}
            />

            {newData.autoSave && (
              <>
                <ComparisonRow
                  label="Frequency"
                  newValue={getFrequencyText(newData.frequency)}
                />

                {newData.frequency !== 4 && newData.periodicSavingsAmount && (
                  <ComparisonRow
                    label={getPeriodicAmountLabel(newData.frequency)}
                    newValue={formatCurrencyValue(newData.periodicSavingsAmount)}
                  />
                )}

                {newData.startDate && (
                  <ComparisonRow
                    label="Start Date"
                    newValue={formatDate(newData.startDate)}
                  />
                )}

                {newData.endDate && (
                  <ComparisonRow
                    label="End Date"
                    newValue={formatDate(newData.endDate)}
                  />
                )}
              </>
            )}
          </View>
        )}

        {/* Additional Settings */}
        <View style={styles.sectionContainer}>
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Bold"
            fontWeight="700"
            text="OTHER OPTIONS"
            color={Colors.purple60}
            style={styles.sectionTitle}
          />
          <ComparisonRow
            label="Interest"
            newValue={newData.isInterestDisabled ? 'Disabled' : 'Enabled'}
          />

          {newData.narration && (
            <ComparisonRow
              label="Narration"
              newValue={newData.narration}
            />
          )}
        </View>
      </View>
    </ScrollView>
  );

  console.log(existingData, 'existingData');

  const renderEditComparison = () => {
    if (!existingData) {return null;}

    // Group changes by section
    const basicChanges = [
      {
        label: 'Account Name',
        oldValue: existingData.accountName,
        newValue: newData.accountName,
        isChanged: hasChanged(existingData.accountName, newData.accountName),
      },
      {
        label: isLockedCategory ? 'Lock Amount' : 'Savings Target',
        oldValue: formatCurrencyValue(existingData.savingTarget * 100), // Convert Naira to Kobo for display
        newValue: formatCurrencyValue(newData.savingTarget), // Already in Kobo
        isChanged: hasChanged(existingData.savingTarget * 100, newData.savingTarget), // Compare in Kobo
      },
      {
        label: 'Category',
        oldValue: existingData.categoryName,
        newValue: savingsCategoryName,
        isChanged: hasChanged(existingData.categoryName, savingsCategoryName),
      },
      {
        label: 'Color',
        oldValue: existingData.savingsPlanColor || 'Not set',
        newValue: newData.savingsPlanColor || 'Not set',
        isChanged: hasChanged(existingData.savingsPlanColor?.toLowerCase(), newData.savingsPlanColor?.toLowerCase()),
      },
    ];

    // Add Lock Duration for locked savings
    if (isLockedCategory && newData.startDate && newData.endDate) {
      basicChanges.push({
        label: 'Lock Duration',
        oldValue: existingData.startDate && existingData.endDate
          ? calculateLockDuration(existingData.startDate, existingData.endDate)
          : 'Not set',
        newValue: calculateLockDuration(newData.startDate, newData.endDate),
        isChanged: hasChanged(
          existingData.startDate && existingData.endDate
            ? calculateLockDuration(existingData.startDate, existingData.endDate)
            : 'Not set',
          calculateLockDuration(newData.startDate, newData.endDate)
        ),
      });
    }

    const configChanges = [];

    // Only include Auto-Save for flexible savings (not locked)
    if (!isLockedCategory) {
      configChanges.push({
        label: 'Auto-Save',
        oldValue: existingData.autoSave ? 'Enabled' : 'Disabled',
        newValue: newData.autoSave ? 'Enabled' : 'Disabled',
        isChanged: hasChanged(existingData.autoSave, newData.autoSave),
      });
    }

    // Only show auto-save related fields for flexible savings
    if (!isLockedCategory && newData.autoSave) {
      configChanges.push(
        {
          label: 'Frequency',
          oldValue: existingData.savingsFrequency === '0' ? 'Not set' : existingData.savingsFrequency,
          newValue: getFrequencyText(newData.frequency),
          isChanged: hasChanged(existingData.savingsFrequencyId, newData.frequency),
        }
      );

      if (newData.frequency !== 4 && newData.periodicSavingsAmount) {
        configChanges.push({
          label: getPeriodicAmountLabel(newData.frequency),
          oldValue: formatCurrencyValue(existingData.periodicSavingsAmount * 100), // Convert Naira to Kobo for display
          newValue: formatCurrencyValue(newData.periodicSavingsAmount), // Already in Kobo
          isChanged: hasChanged(existingData.periodicSavingsAmount * 100, newData.periodicSavingsAmount), // Compare in Kobo
        });
      }

      if (newData.startDate) {
        configChanges.push({
          label: 'Start Date',
          oldValue: existingData.startDate ? formatDate(existingData.startDate) : 'Not set',
          newValue: formatDate(newData.startDate),
          isChanged: hasChanged(existingData.startDate, newData.startDate),
        });
      }

      if (newData.endDate) {
        configChanges.push({
          label: 'End Date',
          oldValue: existingData.endDate ? formatDate(existingData.endDate) : 'Not set',
          newValue: formatDate(newData.endDate),
          isChanged: hasChanged(existingData.endDate, newData.endDate),
        });
      }
    }

    const additionalChanges = [
      {
        label: 'Interest',
        oldValue: existingData.isInterestDisabled ? 'Disabled' : 'Enabled',
        newValue: newData.isInterestDisabled ? 'Disabled' : 'Enabled',
        isChanged: hasChanged(existingData.isInterestDisabled, newData.isInterestDisabled),
      },
      {
        label: 'Narration',
        oldValue: existingData.narration || 'None',
        newValue: newData.narration || 'None',
        isChanged: hasChanged(existingData.narration || '', newData.narration || ''),
      },
    ];

    const hasAnyChanges = [...basicChanges, ...configChanges, ...additionalChanges].some(item => item.isChanged);

    return (
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{paddingTop: 0}}>
        <View style={[styles.summaryContainer, {marginTop: 0}]}>
          {!hasAnyChanges && (
            <View style={[styles.sectionContainer, {alignItems: 'center'}]}>
              <Text
                fontSize={fontSz(16)}
                fontFamily="Gordita-Medium"
                fontWeight="500"
                text="No changes detected"
                color={Colors.inputBackgroundLight}
              />
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text="All fields have the same values as before"
                color={Colors.inputBackgroundLight}
                style={{marginTop: ms(4), textAlign: 'center'}}
              />
            </View>
          )}

          {/* Basic Information Changes */}
          {basicChanges.some(item => item.isChanged) && (
            <View style={styles.sectionContainer}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Bold"
                fontWeight="700"
                text="ACCOUNT CHANGES"
                color={Colors.purple60}
                style={styles.sectionTitle}
              />
              {basicChanges.map((item, index) => item.isChanged && (
                <ComparisonRow
                  key={index}
                  label={item.label}
                  oldValue={item.oldValue}
                  newValue={item.newValue}
                  isChanged={item.isChanged}
                />
              ))}
            </View>
          )}

          {/* Configuration Changes */}
          {configChanges.some(item => item.isChanged) && (
            <View style={styles.sectionContainer}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Bold"
                fontWeight="700"
                text="SAVINGS PLAN CHANGES"
                color={Colors.purple60}
                style={styles.sectionTitle}
              />
              {configChanges.map((item, index) => item.isChanged && (
                <ComparisonRow
                  key={index}
                  label={item.label}
                  oldValue={item.oldValue}
                  newValue={item.newValue}
                  isChanged={item.isChanged}
                />
              ))}
            </View>
          )}

          {/* Additional Settings Changes */}
          {additionalChanges.some(item => item.isChanged) && (
            <View style={styles.sectionContainer}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Bold"
                fontWeight="700"
                text="OTHER CHANGES"
                color={Colors.purple60}
                style={styles.sectionTitle}
              />
              {additionalChanges.map((item, index) => item.isChanged && (
                <ComparisonRow
                  key={index}
                  label={item.label}
                  oldValue={item.oldValue}
                  newValue={item.newValue}
                  isChanged={item.isChanged}
                />
              ))}
            </View>
          )}

          {/* Show unchanged items in a collapsed section */}
          {hasAnyChanges && (
            <View style={[styles.sectionContainer, {opacity: 0.7}]}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Bold"
                fontWeight="700"
                text="NO CHANGES"
                color={Colors.inputBackgroundLight}
                style={styles.sectionTitle}
              />
              {[...basicChanges, ...configChanges, ...additionalChanges]
                .filter(item => !item.isChanged)
                .map((item, index) => (
                  <ComparisonRow
                    key={index}
                    label={item.label}
                    oldValue={item.oldValue}
                    newValue={item.newValue}
                    isChanged={false}
                  />
                ))}
            </View>
          )}
        </View>
      </ScrollView>
    );
  };

  const renderFooter = () => (
    <View style={styles.buttonRow}>
      <Button
        title="Cancel"
        onPress={onCancel}
        style={[styles.secondaryButton, {flex: 1, marginRight: ms(8)}]}
        textStyle={{color: Colors.purple60}}
      />
      <Button
        title={editMode ? 'Confirm Update' : 'Create Account'}
        onPress={onConfirm}
        isLoading={isLoading}
        style={[styles.primaryButton, {flex: 1, marginLeft: ms(8)}]}
      />
    </View>
  );

  return (
    <Modal
      visible={visible}
      title="Account Summary"
      onClose={onCancel}
      contentStyle={{paddingTop: 0, paddingBottom: ms(16)}}
      footer={renderFooter()}>
      {editMode ? renderEditComparison() : renderNewAccountSummary()}
    </Modal>
  );
};

export default SavingsConfirmation;

const styles = StyleSheet.create({
  comparisonRow: {
    backgroundColor: Colors.white,
    borderRadius: ms(12),
    padding: ms(16),
    marginBottom: ms(12),
    borderWidth: 1,
    borderColor: '#F0F0F0',
    position: 'relative',
  },
  labelText: {
    marginBottom: ms(8),
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  valueContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: ms(24),
  },
  oldValueContainer: {
    flex: 1,
  },
  oldValue: {
    opacity: 0.7,
  },
  strikeThrough: {
    textDecorationLine: 'line-through',
  },
  arrowContainer: {
    paddingHorizontal: ms(12),
    alignItems: 'center',
  },
  newValueContainer: {
    flex: 1,
  },
  singleValueContainer: {
    flex: 1,
  },
  changeIndicator: {
    position: 'absolute',
    top: ms(8),
    right: ms(8),
  },
  changeDot: {
    width: ms(8),
    height: ms(8),
    borderRadius: ms(4),
    backgroundColor: Colors.purple60,
  },
  summaryContainer: {
    // backgroundColor: '#F8F9FE',
    borderBottomLeftRadius: ms(16),
    borderBottomRightRadius: ms(16),
    paddingHorizontal: ms(20),
    paddingTop: ms(20),
    paddingBottom: ms(20),
    marginBottom: ms(20),
    marginTop: 0,
  },
  summaryHeader: {
    marginBottom: ms(20),
    textAlign: 'center',
  },
  sectionContainer: {
    backgroundColor: Colors.white,
    borderRadius: ms(12),
    padding: ms(16),
    marginBottom: ms(16),
    borderWidth: 1,
    borderColor: '#F0F0F0',
  },
  sectionTitle: {
    marginBottom: ms(12),
    paddingBottom: ms(8),
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  buttonContainer: {
    paddingTop: ms(20),
    rowGap: ms(12),
  },
  fixedButtonContainer: {
    backgroundColor: Colors.white,
    paddingHorizontal: ms(20),
    paddingVertical: ms(16),
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
    elevation: 4,
    shadowOffset: {width: 0, height: -2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  buttonRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  primaryButton: {
    borderRadius: ms(12),
    paddingVertical: ms(16),
    elevation: 2,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  secondaryButton: {
    backgroundColor: Colors.white,
    borderWidth: 1,
    borderColor: Colors.purple60,
    borderRadius: ms(12),
    paddingVertical: ms(16),
  },
  colorValueContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  colorSwatch: {
    width: ms(20),
    height: ms(20),
    borderRadius: ms(4),
    marginRight: ms(8),
  },
});
