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

export interface Hostel {
  id: number;
  uid: string;
  name: string;
  code: string;
  type: 'boys' | 'girls' | 'co-ed';
  address: string;
  warden_id: number;
  warden_name?: string;
  phone: string;
  room_count: number;
  total_capacity: number;
  occupied_count: number;
}

export interface Room {
  id: number;
  uid: string;
  hostel_id: number;
  room_type_id: number;
  type_name?: string;
  room_number: string;
  floor: number;
  bed_count: number;
  max_beds?: number;
  occupied_beds?: number;
  status: 'available' | 'occupied' | 'maintenance';
}

export interface RoomAssignment {
  id: number;
  uid: string;
  student_id: number;
  first_name: string;
  last_name: string;
  hostel_name: string;
  room_number: string;
  bed_number: string;
  start_date: string;
  end_date: string;
  status: 'active' | 'inactive';
}

export interface HostelStore {
  hostels: Hostel[];
  rooms: Room[];
  assignments: RoomAssignment[];
  roomTypes: any[];
  loading: boolean;
  
  fetchHostels: () => Promise<void>;
  fetchRooms: (hostelId: number) => Promise<void>;
  fetchAssignments: () => Promise<void>;
  fetchRoomTypes: () => Promise<void>;
  
  addHostel: (data: any) => Promise<void>;
  addRoom: (data: any) => Promise<void>;
  assignRoom: (data: any) => Promise<void>;
  checkoutStudent: (id: number) => Promise<void>;
}

export const useHostelStore = create<HostelStore>((set, get) => ({
  hostels: [],
  rooms: [],
  assignments: [],
  roomTypes: [],
  loading: false,

  fetchHostels: async () => {
    set({ loading: true });
    try {
      const res = await api.get('/hostels');
      set({ hostels: res.data, loading: false });
    } catch (err) {
      set({ loading: false });
    }
  },

  fetchRooms: async (hostelId) => {
    const res = await api.get(`/hostels/${hostelId}/rooms`);
    set({ rooms: res.data });
  },

  fetchAssignments: async () => {
    const res = await api.get('/hostels/assignments');
    set({ assignments: res.data });
  },

  fetchRoomTypes: async () => {
    const res = await api.get('/hostels/room-types');
    set({ roomTypes: res.data });
  },

  addHostel: async (data) => {
    await api.post('/hostels', data);
    get().fetchHostels();
  },

  addRoom: async (data) => {
    await api.post('/hostels/rooms', data);
    if (data.hostel_id) get().fetchRooms(data.hostel_id);
  },

  assignRoom: async (data) => {
    await api.post('/hostels/assignments', data);
    get().fetchAssignments();
    get().fetchHostels();
  },

  checkoutStudent: async (id) => {
    await api.post(`/hostels/assignments/${id}/checkout`);
    get().fetchAssignments();
    get().fetchHostels();
  }
}));
