import {
  Platform,
  requireNativeComponent,
  processColor,
  StyleProp,
  ViewStyle,
} from 'react-native';
import type { HostComponent } from 'react-native';
import PickyFabricComponent from './specs/v1/PickyNativeComponent';
import type {
  NativeColorType,
  NativeOnChange,
  NativePickerDataItem,
} from './types';
import type { PickerDataItem } from './specs/v1/PickyNativeComponent';

// Original native component for iOS/Android (old architecture)
const ComponentName = 'Picky';

type NativeIOSData = NativePickerDataItem[];
type NativeAndroidData = NativePickerDataItem;

type NativeCommonProps = {
  loop?: boolean;
  data: NativeIOSData | NativeAndroidData;
  onChange?: NativeOnChange;
};

type NativeIOSProps = {
  numberOfLines?: number;
  columnWidths: number[];
  style?: StyleProp<ViewStyle>;
  selectedIndexes?: number[];
  testID?: string;
};

type NativeAndroidProps = {
  column?: number;
  curtainColor?: NativeColorType;
  hasCurtain?: boolean;
  hasIndicator?: boolean;
  indicatorSize?: number;
  indicatorColor?: NativeColorType;
  itemSpace?: number;
  textColor?: NativeColorType;
  textSize?: number;
  selectedIndex?: number;
};

export type NativePickerProps = NativeCommonProps &
  (NativeIOSProps | NativeAndroidProps);

// The Fabric component above has already registered "Picky" on HarmonyOS.
// Registering the legacy component there as well makes module initialization fail.
const LegacyNativePicker =
  (Platform as { OS: string }).OS === 'harmony'
    ? (PickyFabricComponent as unknown as HostComponent<NativePickerProps>)
    : requireNativeComponent<NativePickerProps>(ComponentName);

// Helper to convert processColor result to Int32 (0 for null)
function colorToInt32(color: NativeColorType): number {
  return (color as number) ?? 0;
}

// Convert NativePickerDataItem[] to PickerDataItem[][] for the Fabric spec
export function convertDataForHarmony(
  data: NativePickerDataItem[]
): PickerDataItem[][] {
  return data.map((columnData) =>
    columnData.map((item) => ({
      label: item.label,
      value: String(item.value),
      textColor: colorToInt32(item.textColor),
      testID: item.testID,
    }))
  );
}

export { colorToInt32, LegacyNativePicker };
export const NativePicker = PickyFabricComponent;