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

export interface OffboardingRecord {
  id: number;
  uid: string;
  user_id: number;
  audience: 'student' | 'staff';
  reason: 'graduated' | 'transferred' | 'withdrawn' | 'expelled' | 'resigned' | 'terminated' | 'retired' | 'deceased' | 'other';
  reason_notes: string | null;
  initiated_by: number;
  status: 'in_progress' | 'completed' | 'cancelled';
  effective_date: string;
  destination: string | null;
  alumni_status: 'active_alumni' | 'inactive_alumni' | null;
  created_at: string;
  updated_at: string;
  user_name: string;
  user_role: string;
  user_id_number: string;
  initiator_name: string | null;
  actions?: OffboardingAction[];
}

export interface OffboardingAction {
  id: number;
  uid: string;
  record_id: number;
  step: 'enrollment_closed' | 'hostel_released' | 'transport_removed' | 'clubs_removed' | 'fee_settled' | 'leave_closed' | 'payroll_finalized' | 'class_assignments_cleared' | 'subject_assignments_cleared' | 'account_deactivated' | 'record_archived';
  status: 'pending' | 'completed' | 'skipped' | 'failed';
  notes: string | null;
  performed_by: number | null;
  performed_by_name?: string | null;
  performed_at: string;
}

export interface AlumniRecord {
  id: number;
  uid: string;
  first_name: string;
  last_name: string;
  email: string;
  phone: string | null;
  archive_status: string;
  effective_date: string;
  reason: string;
  reason_notes: string | null;
  destination: string | null;
  cohort_name: string | null;
  cohort_id: number | null;
}

export interface FormerStaffRecord {
  id: number;
  uid: string;
  first_name: string;
  last_name: string;
  email: string;
  phone: string | null;
  role: string;
  archive_status: string;
  effective_date: string;
  reason: string;
  reason_notes: string | null;
  department_name: string | null;
  department_id: number | null;
}

interface OffboardingState {
  records: OffboardingRecord[];
  alumni: AlumniRecord[];
  formerStaff: FormerStaffRecord[];
  loading: boolean;
  error: string | null;
  fetchRecords: (filters?: { audience?: string; status?: string }) => Promise<void>;
  fetchRecordDetails: (id: number) => Promise<OffboardingRecord | null>;
  fetchAlumni: (filters?: { cohort_id?: number | string; year?: string; search?: string }) => Promise<void>;
  fetchFormerStaff: (filters?: { department_id?: number | string; search?: string }) => Promise<void>;
  offboardStudent: (userId: number, payload: any) => Promise<any>;
  offboardStaff: (userId: number, payload: any) => Promise<any>;
  cancelOffboarding: (id: number) => Promise<void>;
  overrideAction: (id: number, reason: string) => Promise<void>;
}

export const useOffboardingStore = create<OffboardingState>((set) => ({
  records: [],
  alumni: [],
  formerStaff: [],
  loading: false,
  error: null,

  fetchRecords: async (filters) => {
    set({ loading: true, error: null });
    try {
      const res = await api.get('/offboarding/records', { params: filters });
      set({ records: res.data.records || [], loading: false });
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
    }
  },

  fetchRecordDetails: async (id) => {
    set({ loading: true, error: null });
    try {
      const res = await api.get(`/offboarding/records/${id}`);
      set({ loading: false });
      return res.data;
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
      return null;
    }
  },

  fetchAlumni: async (filters) => {
    set({ loading: true, error: null });
    try {
      const res = await api.get('/offboarding/alumni', { params: filters });
      set({ alumni: res.data || [], loading: false });
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
    }
  },

  fetchFormerStaff: async (filters) => {
    set({ loading: true, error: null });
    try {
      const res = await api.get('/offboarding/former-staff', { params: filters });
      set({ formerStaff: res.data || [], loading: false });
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
    }
  },

  offboardStudent: async (userId, payload) => {
    set({ loading: true, error: null });
    try {
      const res = await api.post(`/offboarding/students/${userId}`, payload);
      set({ loading: false });
      return res.data;
    } catch (err: any) {
      const errMsg = err.response?.data?.error || err.message;
      set({ error: errMsg, loading: false });
      throw new Error(errMsg);
    }
  },

  offboardStaff: async (userId, payload) => {
    set({ loading: true, error: null });
    try {
      const res = await api.post(`/offboarding/staff/${userId}`, payload);
      set({ loading: false });
      return res.data;
    } catch (err: any) {
      const errMsg = err.response?.data?.error || err.message;
      set({ error: errMsg, loading: false });
      throw new Error(errMsg);
    }
  },

  cancelOffboarding: async (id) => {
    set({ loading: true, error: null });
    try {
      await api.post(`/offboarding/records/${id}/cancel`);
      set({ loading: false });
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
      throw err;
    }
  },

  overrideAction: async (id, reason) => {
    set({ loading: true, error: null });
    try {
      await api.post(`/offboarding/records/${id}/override`, { reason });
      set({ loading: false });
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, loading: false });
      throw err;
    }
  }
}));
