import React from 'react';
import {StyleSheet, View} from 'react-native';
import {Colors, fontSz, globalStyles, ms, FrequencyType, wp} from '../../utils';
import {CustomPressable} from '../Button';
import {Text} from '../Text';
import {useSDKConfig} from '../../contexts/SDKConfigContext';

type FrequencyOption = {
  id: number;
  name: FrequencyType;
  description: string;
};

const frequencyOptions: FrequencyOption[] = [
  {
    id: 0,
    name: 'Daily',
    description: 'Save a fixed amount every day',
  },
  {
    id: 1,
    name: 'Weekly',
    description: 'Save a fixed amount every week',
  },
  {
    id: 2,
    name: 'Monthly',
    description: 'Save a fixed amount every month',
  },
  {
    id: 3,
    name: 'Save as you collect',
    description: 'Save a part of every inflow into your wallet',
  },
];

type Props = {
  selectedFrequency: FrequencyType;
  onSelectFrequency: (frequency: FrequencyType) => void;
  label?: string;
  showAsterisk?: boolean;
  errorMsg?: string;
};

const FrequencyCards = ({
  selectedFrequency,
  onSelectFrequency,
  label = 'How often do you want to save?',
  showAsterisk = true,
  errorMsg = '',
}: Props) => {
  const {primaryColor} = useSDKConfig();

  const getCardColors = (option: FrequencyOption, isSelected: boolean) => {
    switch (option.name) {
      case 'Daily':
        return {
          background: isSelected ? '#E8F5E8' : '#F8FDF8',
          border: isSelected ? '#4CAF50' : '#E8F5E8',
          text: isSelected ? '#2E7D32' : '#4CAF50',
        };
      case 'Weekly':
        return {
          background: isSelected ? '#FFF4E6' : '#FFFBF5',
          border: isSelected ? '#FF9800' : '#FFF4E6',
          text: isSelected ? '#E65100' : '#FF9800',
        };
      case 'Monthly':
        return {
          background: isSelected ? '#E3F2FD' : '#F8FCFF',
          border: isSelected ? '#2196F3' : '#E3F2FD',
          text: isSelected ? '#1565C0' : '#2196F3',
        };
      case 'Save as you collect':
        return {
          background: isSelected ? '#F3E8FF' : '#FDFBFF',
          border: isSelected ? '#9C27B0' : '#F3E8FF',
          text: isSelected ? '#6A1B9A' : '#9C27B0',
        };
      default:
        return {
          background: isSelected ? `${primaryColor}20` : '#F8F9FA',
          border: isSelected ? primaryColor : '#E9ECEF',
          text: isSelected ? primaryColor : Colors.headerText,
        };
    }
  };

  // Group options into rows of 2
  const rows = [];
  for (let i = 0; i < frequencyOptions.length; i += 2) {
    rows.push(frequencyOptions.slice(i, i + 2));
  }

  return (
    <View style={styles.container}>
      {label && (
        <View style={styles.labelContainer}>
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            text={label}
            color={Colors.inputBackgroundLight}
          />
          {showAsterisk && (
            <Text
              fontSize={fontSz(14)}
              fontFamily="Gordita-Regular"
              fontWeight="400"
              text="*"
              color={Colors.debitRed}
            />
          )}
        </View>
      )}

      <View style={styles.gridContainer}>
        {rows.map((row, rowIndex) => (
          <View key={rowIndex} style={styles.row}>
            {row.map((option) => {
              const isSelected = selectedFrequency === option.name;
              const colors = getCardColors(option, isSelected);

              return (
                <CustomPressable
                  key={option.id}
                  onPress={() => onSelectFrequency(option.name)}
                  style={[
                    styles.card,
                    {
                      backgroundColor: colors.background,
                      borderColor: colors.border,
                      borderWidth: 1,
                    },
                  ]}>

                  <View style={styles.cardContent}>
                    <Text
                      fontSize={fontSz(14)}
                      fontFamily="Gordita-Medium"
                      fontWeight="500"
                      text={option.name}
                      color={colors.text}
                      textAlign="left"
                      numberOfLines={2}
                    />

                    <Text
                      fontSize={fontSz(11)}
                      fontFamily="Gordita-Regular"
                      fontWeight="400"
                      text={option.description}
                      color={Colors.inputBackgroundLight}
                      textAlign="left"
                      style={styles.description}
                      numberOfLines={3}
                    />
                  </View>
                </CustomPressable>
              );
            })}
          </View>
        ))}
      </View>

      {errorMsg && errorMsg.length > 0 && (
        <Text
          fontSize={fontSz(14)}
          fontFamily="Gordita-Regular"
          fontWeight="400"
          text={errorMsg}
          color={Colors.error}
          style={styles.errorText}
        />
      )}
    </View>
  );
};

export default FrequencyCards;

const styles = StyleSheet.create({
  container: {
    marginVertical: ms(5),
  },
  labelContainer: {
    flexDirection: 'row',
    marginBottom: ms(12),
  },
  gridContainer: {
    gap: ms(12),
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: ms(12),
  },
  card: {
    flex: 1,
    height: ms(85),
    paddingTop: ms(12),
    paddingHorizontal: ms(12),
    paddingBottom: ms(8),
    borderRadius: ms(12),
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.08,
    shadowRadius: 4,
    elevation: 2,
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
  },
  cardContent: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    width: '100%',
  },
  description: {
    marginTop: ms(8),
    lineHeight: fontSz(13),
  },
  errorText: {
    marginTop: ms(8),
  },
});
