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

interface RoutesContextType {
  routes: RouteItem[];
  addRoute: (item: Omit<RouteItem, "id" | "createdAt">) => void;
  updateRoute: (id: string, item: Omit<RouteItem, "id" | "createdAt">) => void;
  deleteRoute: (id: string) => void;
}

const RoutesContext = createContext<RoutesContextType | null>(null);

export const useRoutes = () => {
  const ctx = useContext(RoutesContext);
  if (!ctx) throw new Error("useRoutes must be inside RoutesProvider");
  return ctx;
};

const STORAGE_KEY = "itarota79_routes";

const defaultRoutes: RouteItem[] = [
  {
    id: "r1",
    title: "Rota de Itabaiana-SE para Penedo",
    description:
      "Uma rota saindo de Itabaiana-SE com destino a Penedo, ideal para quem busca uma viagem agradável com belas paisagens e boa companhia na estrada.",
    imageUrl: "https://images.unsplash.com/photo-1558618666-fcd25c85f82e?w=800",
    date: "2026-05-25",
    time: "05:00",
    location: "Saída de Itabaiana-SE até Penedo-AL",
    routeLink: "https://maps.google.com",
    mapsLink: "https://maps.google.com/?q=Itabaiana-SE+Penedo-AL",
    gpsCoordinates: "-10.6850, -37.4278",
    distance: "aproximadamente 230 km",
    difficulty: "Moderada",
    createdAt: Date.now(),
  },
];

export const RoutesProvider = ({ children }: { children: ReactNode }) => {
  const [routes, setRoutes] = useState<RouteItem[]>(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : defaultRoutes;
  });

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

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

  const updateRoute = (
    id: string,
    item: Omit<RouteItem, "id" | "createdAt">,
  ) => {
    setRoutes((prev) => prev.map((r) => (r.id === id ? { ...r, ...item } : r)));
  };

  const deleteRoute = (id: string) => {
    setRoutes((prev) => prev.filter((r) => r.id !== id));
  };

  return (
    <RoutesContext.Provider
      value={{ routes, addRoute, updateRoute, deleteRoute }}
    >
      {children}
    </RoutesContext.Provider>
  );
};
