/**
 * Front Office Module - Zustand Store
 *
 * Covers the two new front-office sub-resources added by the
 * 2026-06-12 backend change:
 *   - phone call logs   (/api/front-office/phone-calls)
 *   - postal dispatch   (/api/front-office/postal)
 *
 * The store wraps the shared `api` axios client; auth headers come from
 * the request interceptor in `client/src/store/api.ts`.
 *
 * Visitor logs, admission enquiries and complaints are handled by their
 * own pages and were not moved into a store — they use `api` directly
 * the same way `front-office/VisitorLog.tsx` does. This store deliberately
 * follows that lightweight pattern rather than a heavy caching one.
 */

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

/* ---------- phone-call log shape ---------- */

export interface PhoneCall {
  id: number;
  uid: string;
  caller_name: string;
  caller_phone: string;
  caller_type: 'parent' | 'student' | 'vendor' | 'government' | 'other';
  direction: 'incoming' | 'outgoing';
  call_time: string;
  duration_seconds: number | null;
  purpose: string;
  response: string;
  follow_up_required: 0 | 1 | boolean;
  follow_up_date: string | null;
  handled_by: number | null;
  handler_name?: string;
  notes: string;
  created_at: string;
  updated_at: string;
}

export interface PhoneCallCreate {
  caller_name: string;
  caller_phone?: string;
  caller_type?: PhoneCall['caller_type'];
  direction?: PhoneCall['direction'];
  call_time?: string;
  duration_seconds?: number;
  purpose?: string;
  response?: string;
  follow_up_required?: boolean;
  follow_up_date?: string;
  handled_by?: number;
  notes?: string;
}

/* ---------- postal dispatch shape ---------- */

export interface PostalItem {
  id: number;
  uid: string;
  type: 'dispatch' | 'receive';
  reference_number: string | null;
  sender: string;
  receiver: string;
  address: string | null;
  courier: string | null;
  tracking_number: string | null;
  dispatch_date: string;
  received_date: string | null;
  received_by: number | null;
  description: string | null;
  status: 'pending' | 'sent' | 'delivered' | 'returned';
  created_by: number | null;
  sender_name?: string;
  receiver_name?: string;
  created_by_name?: string;
  created_at: string;
  updated_at: string;
}

export interface PostalCreate {
  type?: PostalItem['type'];
  reference_number?: string;
  sender: string;
  receiver: string;
  address?: string;
  courier?: string;
  tracking_number?: string;
  dispatch_date?: string;
  description?: string;
}

/* ---------- store interface ---------- */

interface FrontOfficeStore {
  // state
  phoneCalls: PhoneCall[];
  postal: PostalItem[];
  loading: boolean;
  error: string | null;

  // phone-calls
  fetchPhoneCalls: (filters?: { from?: string; to?: string; handled_by?: number | string }) => Promise<void>;
  createPhoneCall: (data: PhoneCallCreate) => Promise<PhoneCall>;
  updatePhoneCall: (id: number, data: Partial<PhoneCallCreate>) => Promise<void>;
  deletePhoneCall: (id: number) => Promise<void>;
  markFollowUpDone: (id: number, notes?: string) => Promise<void>;

  // postal
  fetchPostal: (filters?: { type?: PostalItem['type']; status?: PostalItem['status']; from?: string; to?: string }) => Promise<void>;
  createPostalItem: (data: PostalCreate) => Promise<PostalItem>;
  updatePostalItem: (id: number, data: Partial<PostalCreate & { status: PostalItem['status'] }>) => Promise<void>;
  markSent: (id: number) => Promise<void>;
  markDelivered: (id: number) => Promise<void>;
  deletePostalItem: (id: number) => Promise<void>;
}

/* ---------- implementation ---------- */

export const useFrontOfficeStore = create<FrontOfficeStore>((set, get) => ({
  phoneCalls: [],
  postal: [],
  loading: false,
  error: null,

  // ============ PHONE CALLS ============

  fetchPhoneCalls: async (filters) => {
    set({ loading: true, error: null });
    try {
      const params: Record<string, string> = {};
      if (filters?.from) params.from = filters.from;
      if (filters?.to) params.to = filters.to;
      if (filters?.handled_by) params.handled_by = String(filters.handled_by);
      const res = await api.get('/front-office/phone-calls', { params });
      set({ phoneCalls: res.data, loading: false });
    } catch (err: any) {
      set({ error: err?.message || 'Failed to load phone calls', loading: false });
      console.error('fetchPhoneCalls error', err);
    }
  },

  createPhoneCall: async (data) => {
    const res = await api.post('/front-office/phone-calls', data);
    set(state => ({ phoneCalls: [res.data, ...state.phoneCalls] }));
    return res.data;
  },

  updatePhoneCall: async (id, data) => {
    await api.put(`/front-office/phone-calls/${id}`, data);
    set(state => ({
      phoneCalls: state.phoneCalls.map(c => (c.id === id ? { ...c, ...data } : c)),
    }));
  },

  deletePhoneCall: async (id) => {
    try {
      console.log(`Attempting to delete phone call with ID: ${id}`);
      const res = await api.delete(`/front-office/phone-calls/${id}`);
      console.log(`Delete response:`, res.data);
      set(state => ({ phoneCalls: state.phoneCalls.filter(c => c.id !== id) }));
    } catch (err: any) {
      console.error(`Failed to delete phone call ${id}:`, err.response?.data || err.message);
      throw err;
    }
  },

  markFollowUpDone: async (id, notes) => {
    await api.put(`/front-office/phone-calls/${id}/follow-up`, { notes });
    set(state => ({
      phoneCalls: state.phoneCalls.map(c =>
        c.id === id ? { ...c, follow_up_required: 0 as any } : c
      ),
    }));
  },

  // ============ POSTAL ============

  fetchPostal: async (filters) => {
    set({ loading: true, error: null });
    try {
      const params: Record<string, string> = {};
      if (filters?.type) params.type = filters.type;
      if (filters?.status) params.status = filters.status;
      if (filters?.from) params.from = filters.from;
      if (filters?.to) params.to = filters.to;
      const res = await api.get('/front-office/postal', { params });
      set({ postal: res.data, loading: false });
    } catch (err: any) {
      set({ error: err?.message || 'Failed to load postal items', loading: false });
      console.error('fetchPostal error', err);
    }
  },

  createPostalItem: async (data) => {
    const res = await api.post('/front-office/postal', data);
    set(state => ({ postal: [res.data, ...state.postal] }));
    return res.data;
  },

  updatePostalItem: async (id, data) => {
    await api.put(`/front-office/postal/${id}`, data);
    set(state => ({
      postal: state.postal.map(p => (p.id === id ? { ...p, ...data } : p)),
    }));
  },

  markSent: async (id) => {
    await api.put(`/front-office/postal/${id}/mark-sent`);
    set(state => ({
      postal: state.postal.map(p => (p.id === id ? { ...p, status: 'sent' } : p)),
    }));
  },

  markDelivered: async (id) => {
    await api.put(`/front-office/postal/${id}/mark-delivered`);
    set(state => ({
      postal: state.postal.map(p => (p.id === id ? { ...p, status: 'delivered' } : p)),
    }));
  },

  deletePostalItem: async (id) => {
    await api.delete(`/front-office/postal/${id}`);
    set(state => ({ postal: state.postal.filter(p => p.id !== id) }));
  },
}));

export default useFrontOfficeStore;
