import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https";
import { toast } from "sonner";

interface VehicleBrand {
  name: string;
  id: string;
  company: string;
}

interface Vehicle {
  brandId?: string;
  id: number;
  name: string;
  company: string;
  modelName: string;
  chargeType: string;
  imageUrl: string;
}

interface VehicleState {
  vehicleBrands: VehicleBrand[];
  vehicles: Vehicle[];
  loading: boolean;
  error: string | null;
}

const initialState: VehicleState = {
  vehicleBrands: [],
  vehicles: [],
  loading: false,
  error: null,
};

export const fetchVehicleBrands = createAsyncThunk<
  VehicleBrand[],
  void,
  { rejectValue: string }
>("vehicle/fetchVehicleBrands", async (_, { rejectWithValue }) => {
  try {
    const response = await http.get("/get-vehicle-brand");

    if (!response.data || !Array.isArray(response.data.data)) {
      throw new Error("Expected array of vehicle brands");
    }

    // Map the brand names (strings) to objects with 'id' and 'name' properties
    return response.data.data.map((brand: string) => ({
      id: brand, // Use brand name as the ID
      name: brand, // Use brand name as the label
    }));
  } catch (error: any) {
    return rejectWithValue("Failed to fetch vehicle brands");
  }
});

export const vehicleList = createAsyncThunk<
  Vehicle[],
  void,
  { rejectValue: string }
>("fetchVehicles", async (_, { rejectWithValue }) => {
  try {
    const token = localStorage?.getItem("authToken");
    if (!token) throw new Error("No token found");

    const response = await http.get("/get-vehicles");
	// console.log("---------",response?.data?.data);

    if (!response.data?.data) throw new Error("Invalid API response");

    return response.data.data;
  } catch (error: any) {
    toast.error("Error Fetching Profile" + error);
    return rejectWithValue(
      error?.response?.data?.message || "An error occurred"
    );
  }
});

// Add Vehicle
export const addVehicle = createAsyncThunk<
  Vehicle,
  {
    name: string;
    company: string;
    modelName: string;
    chargeType: string;
    imageFile: File;
  },
  { rejectValue: string }
>("addVehicle", async ({ name, company, modelName, chargeType, imageFile }, { rejectWithValue }) => {
  try {
    const formData = new FormData();
    formData.append("name", name);
    formData.append("company", company);
    formData.append("modelName", modelName);
    formData.append("chargeType", chargeType);
    formData.append("image", imageFile);
 
    const response = await http.post("create-vehicle", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    console.log("first", imageFile);
    return response.data.data;
  } catch (error: any) {
    return rejectWithValue(
      error.response?.data?.message || "An error occurred"
    );
  }
});

// Update Vehicle details
export const updateVehicle = createAsyncThunk<
	Vehicle,
	{
		id: string | number;
		name: string;
		company: string;
		modelName: string;
		chargeType: string;
		imageUrl: File | string | null;
	},
	{ rejectValue: string }
>(
	"updateVehicle",
	async (
		{ id, name, company, modelName, chargeType, imageUrl },
		{ rejectWithValue }
	) => {
		try {
			const formData = new FormData();
			formData.append("name", name);
			formData.append("company", company);
			formData.append("modelName", modelName);
			formData.append("chargeType", chargeType);

			if (imageUrl instanceof File) {
				formData.append("image", imageUrl); // Append new file
			}

			const response = await http.patch(
				`/update-vehicle/${id}`,
				formData,
				{
					headers: {
						"Content-Type": "multipart/form-data",
					},
				}
			);

			toast.success("Vehicle Details updated successfully");
			return response.data.data;
		} catch (error: any) {
			toast.error("Error updating the vehicle: " + error);
			return rejectWithValue(
				error.response?.data?.message || "An error occurred"
			);
		}
	}
);


export const deleteVehicle = createAsyncThunk<
  string,
  string,
  { rejectValue: string }
>("deleteVehicle", async (id, { rejectWithValue }) => {
  try {
    const response = await http.delete(`/delete-vehicle/${id}`);
    toast.success(response.data?.message);
    return id;
  } catch (error: any) {
    toast.error("Error deleting the vehicle" + error);

    return rejectWithValue(
      error.response?.data?.message || "An error occurred"
    );
  }
});

const vehicleSlice = createSlice({
  name: "vehicle",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
		.addCase(vehicleList.pending, (state) => {
			state.loading = true;
			state.error = null;
		})
		.addCase(
			vehicleList.fulfilled,
			(state, action: PayloadAction<Vehicle[]>) => {
				state.loading = false;
				state.vehicles = action.payload; // Replaces vehicle list in state
			}
		)

		.addCase(vehicleList.rejected, (state, action) => {
			state.loading = false;
			state.error = action.error.message || "Failed to fetch users";
		})
		.addCase(fetchVehicleBrands.pending, (state) => {
			state.loading = true;
		})
		.addCase(
			fetchVehicleBrands.fulfilled,
			(state, action: PayloadAction<VehicleBrand[]>) => {
				state.loading = false;
				state.vehicleBrands = action.payload;
			}
		)
		.addCase(fetchVehicleBrands.rejected, (state, action) => {
			state.loading = false;
			state.error = action.payload || "Failed to fetch vehicle brands";
		})
		.addCase(addVehicle.pending, (state) => {
			state.loading = true;
		})
		.addCase(
			addVehicle.fulfilled,
			(state, action: PayloadAction<Vehicle>) => {
				state.loading = false;
				state.vehicles.push(action.payload);
			}
		)

		.addCase(addVehicle.rejected, (state) => {
			state.loading = false;
		})
		.addCase(updateVehicle.pending, (state) => {
			state.loading = true;
		})
		.addCase(updateVehicle.fulfilled, (state, action) => {
			state.loading = false;
			const updatedVehicle = action.payload;
			state.vehicles = state.vehicles.map((vehicle) =>
				vehicle.id === updatedVehicle.id ? updatedVehicle : vehicle
			);
			toast.success("Vehicle Details updated successfully");
		})

		.addCase(updateVehicle.rejected, (state) => {
			state.loading = false;
		})
		.addCase(deleteVehicle.pending, (state) => {
			state.loading = true;
		})
		.addCase(deleteVehicle.fulfilled, (state, action) => {
			state.loading = false;
			state.vehicles = state.vehicles.filter(
				(vehicle) => String(vehicle.id) !== String(action.payload)
			);
		})
		.addCase(deleteVehicle.rejected, (state) => {
			state.loading = false;
		});
  },
});

export default vehicleSlice.reducer;
