import {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
} from "react";
import { GalleryItem } from "@/types";

interface GalleryContextType {
  items: GalleryItem[];
  addItem: (item: Omit<GalleryItem, "id" | "createdAt">) => void;
  updateItem: (id: string, item: Omit<GalleryItem, "id" | "createdAt">) => void;
  deleteItem: (id: string) => void;
}

const GalleryContext = createContext<GalleryContextType | null>(null);

export const useGallery = () => {
  const ctx = useContext(GalleryContext);
  if (!ctx) throw new Error("useGallery must be inside GalleryProvider");
  return ctx;
};

const STORAGE_KEY = "itarota79_gallery";

const defaultItems: GalleryItem[] = [
  {
    id: "1",
    title: "Encontro na praça Eu amo Itabaiana",
    description:
      "Mais de 20 motociclistas reunidos no primeiro encontro do clube.",
    imageUrl:
      "https://images.unsplash.com/photo-1609630875171-b1321377ee65?w=800",
    date: "2025-03-22",
    time: "16:30",
    location: "Itabaiana, SE",
    mapLink: "https://maps.app.goo.gl/WpmLNeP9CxiAq9jg7",
    eventName: "Encontro na praça Eu amo Itabaiana - 22/03/2026",
    createdAt: Date.now() - 1000,
  },
];

export const GalleryProvider = ({ children }: { children: ReactNode }) => {
  const [items, setItems] = useState<GalleryItem[]>(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : defaultItems;
  });

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
  }, [items]);

  const addItem = (item: Omit<GalleryItem, "id" | "createdAt">) => {
    setItems((prev) => [
      { ...item, id: crypto.randomUUID(), createdAt: Date.now() },
      ...prev,
    ]);
  };

  const updateItem = (
    id: string,
    item: Omit<GalleryItem, "id" | "createdAt">,
  ) => {
    setItems((prev) => prev.map((i) => (i.id === id ? { ...i, ...item } : i)));
  };

  const deleteItem = (id: string) => {
    setItems((prev) => prev.filter((i) => i.id !== id));
  };

  return (
    <GalleryContext.Provider value={{ items, addItem, updateItem, deleteItem }}>
      {children}
    </GalleryContext.Provider>
  );
};
