import { FlatList } from "react-native";
import React, { useEffect, useState } from "react";
import { View, Text, ListItem, Button, TextField } from "react-native-ui-lib";
import GroceryItem from "./GroceryItem";
import {
  IGrocery,
  GroceryCategory,
  GroceryFrequency,
  useGroceryContext,
} from "@/contexts/GroceryContext";
import HeaderTemplate from "@/components/shared/HeaderTemplate";
import CategoryDropdown from "./CategoryDropdown";
import { MaterialIcons } from "@expo/vector-icons";
import EditGroceryItem from "./EditGroceryItem";

const GroceryList = () => {
  const {
    groceries,
    updateGroceryItem,
    isAddingGrocery,
    setIsAddingGrocery,
    addGrocery,
  } = useGroceryContext();
  const [approvedGroceries, setapprovedGroceries] = useState<IGrocery[]>(
    groceries.filter((item) => item.approved === true)
  );
  const [pendingGroceries, setPendingGroceries] = useState<IGrocery[]>(
    groceries.filter((item) => item.approved !== true)
  );
  const [category, setCategory] = useState<GroceryCategory>(
    GroceryCategory.Bakery
  );
  const [title, setTitle] = useState<string>("");

  // Group approved groceries by category
  const approvedGroceriesByCategory = approvedGroceries.reduce(
    (groups: any, item: IGrocery) => {
      const category = item.category || "Uncategorized";
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(item);
      return groups;
    },
    {}
  );

  useEffect(() => {
    if (title?.length > 2 && title?.length <= 25) {
      addGrocery({
        id: 0,
        title: title,
        category: category,
        approved: false,
        recurring: false,
        frequency: GroceryFrequency.Never,
        bought: false,
      });

      setIsAddingGrocery(false);
    }
  }, [category]);

  useEffect(() => {
    setapprovedGroceries(groceries.filter((item) => item.approved === true));
    setPendingGroceries(groceries.filter((item) => item.approved !== true));
  }, [groceries]);

  return (
    <View marginH-20>
      <HeaderTemplate
        message={"Welcome to your grocery list"}
        isWelcome={false}
      >
        <View row spread>
          <View
            backgroundColor="#e2eed8"
            padding-8
            style={{ borderRadius: 50 }}
          >
            <Text text70BL color="#46a80a">
              {approvedGroceries.length} list{" "}
              {approvedGroceries.length === 1 ? (
                <Text text70BL color="#46a80a">
                  item
                </Text>
              ) : (
                <Text text70BL color="#46a80a">
                  items
                </Text>
              )}
            </Text>
          </View>
          <View
            backgroundColor="#faead2"
            padding-8
            style={{ borderRadius: 50 }}
          >
            <Text text70BL color="#e28800">
              {pendingGroceries.length} pending
            </Text>
          </View>
          <Button
          backgroundColor='transparent'
          paddingH-10
            iconSource={() => (
              <MaterialIcons name="person-add-alt" size={24} color="gray" />
            )}
          />
        </View>
      </HeaderTemplate>

      {/* Pending Approval Section */}
      <View row spread marginT-40 marginB-20 centerV>
        <Text text70BL>Pending Approval</Text>
        <View
          centerV
          style={{
            aspectRatio: 1,
            width: 40,
            backgroundColor: "#faead2",
            borderRadius: 50,
          }}
        >
          <Text text60L center color="#e28800">
            {pendingGroceries.length.toString()}
          </Text>
        </View>
      </View>
      {pendingGroceries.length > 0 ? (
        <FlatList
          data={pendingGroceries}
          renderItem={({ item }) => (
            <GroceryItem item={item} handleItemApproved={updateGroceryItem} />
          )}
          keyExtractor={(item) => item.id.toString()}
        />
      ) : (
        <Text>No items pending approval.</Text>
      )}

      {/* Approved Section */}
      <View row spread marginT-40 marginB-20 centerV>
        <Text text70BL>Shopping List</Text>
        <View
          centerV
          style={{
            aspectRatio: 1,
            width: 40,
            backgroundColor: "#e2eed8",
            borderRadius: 50,
          }}
        >
          <Text text60L center color="#46a80a">
            {approvedGroceries.length.toString()}
          </Text>
        </View>
      </View>
      {isAddingGrocery && (
        <EditGroceryItem title={title} setTitle={setTitle} setCategory={setCategory} />
      )}

      {/* Render Approved Groceries Grouped by Category */}
      {approvedGroceries.length > 0 ? (
        <FlatList
          data={Object.keys(approvedGroceriesByCategory)}
          renderItem={({ item: category }) => (
            <View key={category}>
              {/* Render Category Header */}
              <Text
                text70M
                style={{ marginVertical: 10, paddingHorizontal: 15 }}
                color="#666"
              >
                {category}
              </Text>
              {/* Render Grocery Items for this Category */}
              {approvedGroceriesByCategory[category].map(
                (grocery: IGrocery) => (
                  <GroceryItem
                    key={grocery.id}
                    item={grocery}
                    handleItemApproved={updateGroceryItem}
                  />
                )
              )}
            </View>
          )}
          keyExtractor={(category) => category}
        />
      ) : (
        <Text>No approved items.</Text>
      )}
    </View>
  );
};

export default GroceryList;
