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

interface MembersContextType {
  members: Member[];
  addMember: (member: Omit<Member, "id" | "createdAt">) => void;
  updateMember: (id: string, member: Omit<Member, "id" | "createdAt">) => void;
  deleteMember: (id: string) => void;
}

const MembersContext = createContext<MembersContextType | null>(null);

export const useMembers = () => {
  const ctx = useContext(MembersContext);
  if (!ctx) throw new Error("useMembers must be inside MembersProvider");
  return ctx;
};

const STORAGE_KEY = "itarota79_members";

const defaultMembers: Member[] = [
  { id: "1", name: "Carlos Silva", city: "Itabaiana, SE", moto: "Honda CB 500X", photo: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&h=200&fit=crop&crop=face", createdAt: Date.now() },
  { id: "2", name: "Rafael Santos", city: "Aracaju, SE", moto: "Yamaha MT-07", photo: "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=200&h=200&fit=crop&crop=face", createdAt: Date.now() - 1000 },
];

export const MembersProvider = ({ children }: { children: ReactNode }) => {
  const [members, setMembers] = useState<Member[]>(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : defaultMembers;
  });

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

  const addMember = (member: Omit<Member, "id" | "createdAt">) => {
    setMembers((prev) => [
      { ...member, id: crypto.randomUUID(), createdAt: Date.now() },
      ...prev,
    ]);
  };

  const updateMember = (id: string, member: Omit<Member, "id" | "createdAt">) => {
    setMembers((prev) =>
      prev.map((m) => (m.id === id ? { ...m, ...member } : m))
    );
  };

  const deleteMember = (id: string) => {
    setMembers((prev) => prev.filter((m) => m.id !== id));
  };

  return (
    <MembersContext.Provider value={{ members, addMember, updateMember, deleteMember }}>
      {children}
    </MembersContext.Provider>
  );
};
