import { create } from 'zustand';
import api from './api';

export interface Vehicle {
  id: number;
  uid: string;
  vehicle_number: string;
  vehicle_model: string;
  vehicle_type: string;
  fuel_type: string;
  registration_number: string;
  driver_id: number;
  driver_name?: string;
  status: 'active' | 'maintenance' | 'retired';
  capacity?: number;
}

export interface Route {
  id: number;
  uid: string;
  route_title: string;
  start_place: string;
  end_place: string;
  distance: string;
  vehicle_id: number;
  vehicle_number?: string;
  driver_name?: string;
  code?: string;
}

export interface TransportAllocation {
  id: number;
  uid: string;
  student_id: number;
  first_name: string;
  last_name: string;
  route_id: number;
  route_title: string;
  pickup_point_id: number | null;
  stop_name: string | null;
  vehicle_route_id: number | null;
  vehicle_number: string | null;
  fee_amount: number;
  effective_from: string | null;
  effective_to: string | null;
  status: 'active' | 'inactive';
}

export interface TransportStore {
  vehicles: Vehicle[];
  routes: Route[];
  allocations: TransportAllocation[];
  loading: boolean;
  
  fetchVehicles: () => Promise<void>;
  fetchRoutes: () => Promise<void>;
  fetchAllocations: () => Promise<void>;
  
  addVehicle: (data: any) => Promise<void>;
  addRoute: (data: any) => Promise<void>;
  allocateTransport: (data: any) => Promise<void>;
  deallocateTransport: (id: number) => Promise<void>;
  assignRouteUnit: (routeId: number, vehicleId: number | null, driverId: number | null) => Promise<void>;
}

export const useTransportStore = create<TransportStore>((set, get) => ({
  vehicles: [],
  routes: [],
  allocations: [],
  loading: false,

  fetchVehicles: async () => {
    set({ loading: true });
    const res = await api.get('/transport/vehicles');
    set({ vehicles: res.data, loading: false });
  },

  fetchRoutes: async () => {
    const res = await api.get('/transport/routes');
    set({ routes: res.data });
  },

  fetchAllocations: async () => {
    const res = await api.get('/transport/allocations');
    set({ allocations: res.data });
  },

  addVehicle: async (data) => {
    await api.post('/transport/vehicles', data);
    get().fetchVehicles();
  },

  addRoute: async (data) => {
    await api.post('/transport/routes', data);
    get().fetchRoutes();
  },

  allocateTransport: async (data) => {
    await api.post('/transport/allocations', data);
    get().fetchAllocations();
  },

  deallocateTransport: async (id) => {
    await api.delete(`/transport/allocations/${id}`);
    get().fetchAllocations();
  },

  assignRouteUnit: async (routeId, vehicleId, driverId) => {
    await api.post(`/transport/routes/${routeId}/assign`, { vehicle_id: vehicleId, driver_id: driverId });
    get().fetchRoutes();
    get().fetchVehicles();
  }
}));
