import { BottomSheet } from '@/aesthetics/BottomSheet';
import { Text } from '@/aesthetics/Text';
import { buttonHeight, font, radius, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import { useState } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import type { MemoLoggerOption } from './types';

type OptionsLayoutProps = {
  options: MemoLoggerOption[];
  colorBg: string;
  colorIcon: string;
  selectedIndices?: number[];
  onPress: (index: number) => void;
};

export function OptionsLayout({
  options,
  colorBg,
  colorIcon,
  selectedIndices,
  onPress,
}: OptionsLayoutProps) {
  const c = useColors();
  const isIconOnly = options.every(o => o.icon && !o.label);
  const isLabelOnly = options.every(o => o.label && !o.icon);

  if (isIconOnly) {
    return (
      <View style={styles.iconRow}>
        {options.map((opt, i) => {
          const isSelected = selectedIndices?.includes(i);
          return (
            <Pressable
              key={i}
              onPress={() => onPress(i)}
              style={({ pressed }) => [
                styles.iconOption,
                { backgroundColor: isSelected ? c.accent : pressed ? colorBg : c.tagBg },
                pressed && { transform: [{ scale: 0.95 }] },
              ]}
            >
              <Text style={styles.iconOptionText}>{opt.icon}</Text>
            </Pressable>
          );
        })}
      </View>
    );
  }

  if (isLabelOnly) {
    return (
      <View style={styles.labelOptionsRow}>
        {options.map((opt, i) => {
          const isSelected = selectedIndices?.includes(i);
          return (
            <Pressable
              key={i}
              onPress={() => onPress(i)}
              style={({ pressed }) => [
                styles.labelOption,
                { backgroundColor: isSelected ? c.accent : pressed ? colorBg : c.tagBg },
                pressed && { transform: [{ scale: 0.97 }] },
              ]}
            >
              {({ pressed }) => (
                <Text
                  style={[
                    styles.labelOptionText,
                    { color: isSelected ? c.onAccent : pressed ? colorIcon : c.text },
                  ]}
                >
                  {opt.label}
                </Text>
              )}
            </Pressable>
          );
        })}
      </View>
    );
  }

  return (
    <View style={styles.selectGrid}>
      {options.map((opt, i) => {
        const isSelected = selectedIndices?.includes(i);
        return (
          <Pressable
            key={i}
            onPress={() => onPress(i)}
            style={({ pressed }) => [
              styles.selectOptionWithIcon,
              { backgroundColor: isSelected ? c.accent : pressed ? colorBg : c.tagBg },
              pressed && { transform: [{ scale: 0.97 }] },
            ]}
          >
            {opt.icon && <Text style={styles.selectOptionIcon}>{opt.icon}</Text>}
            {opt.label && (
              <Text style={[styles.selectOptionText, { color: isSelected ? c.onAccent : c.text }]}>
                {opt.label}
              </Text>
            )}
          </Pressable>
        );
      })}
    </View>
  );
}

type SelectLoggerProps = {
  visible: boolean;
  title: string;
  options: MemoLoggerOption[];
  colorBg: string;
  colorIcon: string;
  selectLimit?: number;
  onSelect: (indices: number[]) => void;
  onClose: () => void;
};

export function SelectLogger({
  visible,
  title,
  options,
  colorBg,
  colorIcon,
  selectLimit = 1,
  onSelect,
  onClose,
}: SelectLoggerProps) {
  const c = useColors();
  const strings = useStrings();
  const isSingle = selectLimit === 1;
  const [selected, setSelected] = useState<number[]>([]);

  const handleClose = () => {
    setSelected([]);
    onClose();
  };

  const handlePress = (index: number) => {
    if (isSingle) {
      onSelect([index]);
      return;
    }
    setSelected(prev => {
      if (prev.includes(index)) return prev.filter(i => i !== index);
      if (prev.length >= selectLimit) return prev;
      return [...prev, index];
    });
  };

  const handleConfirm = () => {
    if (selected.length === 0) return;
    onSelect(selected);
    setSelected([]);
  };

  return (
    <BottomSheet visible={visible} onClose={handleClose} title={title}>
      <View style={styles.container}>
        <OptionsLayout
          options={options}
          colorBg={colorBg}
          colorIcon={colorIcon}
          selectedIndices={isSingle ? undefined : selected}
          onPress={handlePress}
        />
        {!isSingle && (
          <Pressable
            onPress={handleConfirm}
            disabled={selected.length === 0}
            style={({ pressed }) => [
              styles.confirmBtn,
              { backgroundColor: c.accent },
              pressed && { opacity: 0.8 },
              selected.length === 0 && { opacity: 0.4 },
            ]}
          >
            <Text style={[styles.confirmBtnText, { color: c.onAccent }]}>
              {strings.userCustomLogs.log}
            </Text>
          </Pressable>
        )}
      </View>
    </BottomSheet>
  );
}

const styles = StyleSheet.create({
  container: { gap: spacing.lg },
  iconRow: { flexDirection: 'row', justifyContent: 'center', gap: spacing.md },
  iconOption: {
    width: buttonHeight.lg,
    height: buttonHeight.lg,
    borderRadius: radius.lg,
    alignItems: 'center',
    justifyContent: 'center',
  },
  iconOptionText: { fontSize: 32 },
  labelOptionsRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  labelOption: {
    flex: 1,
    minWidth: 90,
    minHeight: buttonHeight.xl,
    borderRadius: radius.lg,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.md,
  },
  labelOptionText: { fontSize: font.md, fontWeight: '600', textAlign: 'center' },
  selectGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  selectOptionWithIcon: {
    width: '48%',
    minHeight: buttonHeight.xl,
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.md,
    borderRadius: radius.lg,
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.xs,
  },
  selectOptionIcon: { fontSize: 24 },
  selectOptionText: { fontSize: font.sm, fontWeight: '500' },
  confirmBtn: {
    minHeight: buttonHeight.md,
    paddingVertical: spacing.md,
    borderRadius: radius.md,
    alignItems: 'center',
    justifyContent: 'center',
  },
  confirmBtnText: { fontSize: font.md, fontWeight: '600' },
});
