'use client'

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { list } from "@/api/carColors";

export interface CarColorItem {
    id: string;
    name: string;
    hexCode: string;
}

interface CarColorType {
    carColor: CarColorItem[] | null;
    setCarColor: (content: CarColorItem[]) => void;
    fetchData: () => void;
}

const CarColorContext = createContext<CarColorType | undefined>(undefined);

export const CarColorProvider = ({ children }: { children: ReactNode }) => {
    const [carColor, setCarColor] = useState<CarColorItem[]>([]);

    const fetchData = async () => {
        setCarColor(await list());
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <CarColorContext.Provider value={{ carColor, setCarColor, fetchData }}>
            {children}
        </CarColorContext.Provider>
    );
};

export const useCarColorContext = (): CarColorType => {
    const context = useContext(CarColorContext);
    if (!context) {
        throw new Error('useCarColorContext must be used within a CarColorProvider');
    }
    return context;
};
