import { StyleSheet } from "react-native";
import React, { useState } from "react";
import {
  Dialog,
  Text,
  View,
  PanningProvider,
  Switch,
  Picker,
  PickerValue,
} from "react-native-ui-lib";
import {
  GroceryFrequency,
  IGrocery,
  useGroceryContext,
} from "@/contexts/GroceryContext";
interface EditGroceryFrequencyProps {
  visible: boolean;
  onClose: () => void;
  item: IGrocery;
}
const EditGroceryFrequency = (props: EditGroceryFrequencyProps) => {
  const { updateGroceryItem } = useGroceryContext();
  const pickerItems = Object.values(GroceryFrequency).map((value) => ({
    label: value,
    value: value,
  }));

  return (
    <Dialog
      visible={props.visible}
      onDismiss={props.onClose}
      panDirection={PanningProvider.Directions.DOWN}
      containerStyle={{ borderRadius: 12, backgroundColor: "white" }}
    >
      <View style={styles.container}>
        <Text style={styles.title}>Edit grocery frequency</Text>
        <View style={styles.divider} />
        <View style={styles.inner}>
          <View row spread>
            <Text text70>Recurring</Text>
            <Switch
              value={props.item.recurring}
              onValueChange={(value) =>
                updateGroceryItem(props.item.id, { recurring: value })
              }
              onColor={"lime"}
            />
          </View>
          <Picker
            value={props.item.frequency}
            fieldType="form"
            useDialog
            items={pickerItems}
            onChange={(item: PickerValue) => {
              const selectedFrequency =
                GroceryFrequency[item as keyof typeof GroceryFrequency];
              if (selectedFrequency) {
                updateGroceryItem(props.item.id, {
                  frequency: selectedFrequency,
                });
              } else {
                console.error("Invalid frequency selected");
              }
            }}
          />
        </View>
      </View>
    </Dialog>
  );
};

export default EditGroceryFrequency;

const styles = StyleSheet.create({
  container: {
    paddingVertical: 10,
    display: "flex",
    flexDirection: "column",
    justifyContent: "space-between",
  },
  inner: {
    paddingHorizontal: 20,
    display: "flex",
    flexDirection: "column",
  },
  title: {
    fontSize: 20,
    fontWeight: "400",
    textAlign: "center",
  },
  divider: {
    width: "100%",
    height: 1,
    backgroundColor: "#E0E0E0",
    marginVertical: 10,
  },
});
