import { ReactNode, createContext, useCallback, useContext, useState } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import { BottomSheet } from './BottomSheet';
import { Text } from './Text';
import { font, useColors } from './styles';

type SelectOption = { label: string; value: string };

type SelectSheetConfig = {
  title: string;
  options: SelectOption[];
  selected?: string;
  onSelect: (value: string) => void;
};

type ActionSheetContextType = {
  showSelectSheet: (config: SelectSheetConfig) => void;
};

const ActionSheetContext = createContext<ActionSheetContextType | null>(null);

export function useActionSheet() {
  const ctx = useContext(ActionSheetContext);
  if (!ctx) throw new Error('useActionSheet must be used within ActionSheetProvider');
  return ctx;
}

export function ActionSheetProvider({ children }: { children: ReactNode }) {
  const [sheetConfig, setSheetConfig] = useState<SelectSheetConfig | null>(null);
  const c = useColors();

  const showSelectSheet = useCallback((config: SelectSheetConfig) => {
    setSheetConfig(config);
  }, []);

  const close = () => setSheetConfig(null);

  const handleSelect = (value: string) => {
    sheetConfig?.onSelect(value);
    close();
  };

  return (
    <ActionSheetContext.Provider value={{ showSelectSheet }}>
      {children}
      {sheetConfig && (
        <BottomSheet visible={!!sheetConfig} onClose={close} title={sheetConfig.title}>
          <View style={styles.optionsList}>
            {sheetConfig.options.map(option => {
              const isSelected = option.value === sheetConfig.selected;
              return (
                <Pressable
                  key={option.value}
                  onPress={() => handleSelect(option.value)}
                  style={({ pressed }) => [
                    styles.option,
                    { borderBottomColor: c.borderSubtle },
                    pressed && { backgroundColor: c.tagBg },
                  ]}
                >
                  <Text style={[styles.optionText, { color: c.text }]}>{option.label}</Text>
                  {isSelected && <Text style={[styles.check, { color: c.accent }]}>✓</Text>}
                </Pressable>
              );
            })}
          </View>
        </BottomSheet>
      )}
    </ActionSheetContext.Provider>
  );
}

const styles = StyleSheet.create({
  optionsList: {},
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  optionText: {
    fontSize: font.lg,
  },
  check: {
    fontSize: font.lg,
    fontWeight: '600',
  },
});
