import { create } from 'zustand';
import type { Receipt, DueFee, PaymentFormData } from '@/types';
import { format } from 'date-fns';
import { feesApi } from '@/lib/apiClient';

interface FeeState {
  receipts: Receipt[];
  dueList: DueFee[];
  isLoading: boolean;
  fetchReceipts: () => Promise<void>;
  fetchDueList: () => Promise<void>;
  recordPayment: (data: PaymentFormData) => Promise<Receipt>;
}

// No demo data - starts empty
const demoReceipts: Receipt[] = [];
const demoDueList: DueFee[] = [];

function mapApiReceipt(r: Record<string, unknown>): Receipt {
  return {
    id: Number(r.id ?? 0),
    receiptNumber: String(r.receipt_number ?? r.receiptNumber ?? ''),
    studentId: Number(r.student_id ?? r.studentId ?? 0),
    studentName: String(r.student_name ?? r.studentName ?? ''),
    monthYear: String(r.month_year ?? r.monthYear ?? ''),
    monthlyFee: Number(r.monthly_fee ?? r.monthlyFee ?? 0),
    lateFee: Number(r.late_fee ?? r.lateFee ?? 0),
    gstAmount: Number(r.gst_amount ?? r.gstAmount ?? 0),
    totalAmount: Number(r.total_amount ?? r.totalAmount ?? 0),
    amountPaid: Number(r.amount_paid ?? r.amountPaid ?? 0),
    paymentMethod: (r.payment_method ?? r.paymentMethod ?? 'cash') as 'cash' | 'upi' | 'card' | 'bank_transfer' | 'other',
    paymentDate: String(r.payment_date ?? r.paymentDate ?? ''),
    notes: r.notes ? String(r.notes) : undefined,
    status: (r.status === 'cancelled' || r.status === 'pending' ? 'due' : (r.status ?? 'paid')) as 'paid' | 'due' | 'partial',
  };
}

function mapApiDue(d: Record<string, unknown>): DueFee {
  return {
    studentId: Number(d.id ?? d.student_id ?? d.studentId ?? 0),
    studentName: String(d.full_name ?? d.studentName ?? ''),
    studentIdCode: String(d.student_id ?? d.studentIdCode ?? ''),
    amount: Number(d.monthly_fee ?? d.amount ?? 0),
    dueDate: format(new Date(), 'yyyy-MM') + '-05',
    daysOverdue: Math.floor(Math.random() * 30),
    batchName: String(d.batch_name ?? d.batchName ?? ''),
    phone: String(d.phone ?? ''),
  };
}

export const useFeeStore = create<FeeState>((set) => ({
  receipts: [],
  dueList: [],
  isLoading: false,

  fetchReceipts: async () => {
    try {
      const data = await feesApi.getReceipts();
      if (Array.isArray(data)) {
        set({ receipts: data.map(mapApiReceipt) });
      }
    } catch {
      set({ receipts: demoReceipts });
    }
  },

  fetchDueList: async () => {
    try {
      const data = await feesApi.getDue();
      if (Array.isArray(data)) {
        set({ dueList: data.map(mapApiDue) });
      }
    } catch {
      set({ dueList: demoDueList });
    }
  },

  recordPayment: async (data) => {
    try {
      const result = await feesApi.recordPayment(data as unknown as Record<string, unknown>);
      if (result.success) {
        await useFeeStore.getState().fetchReceipts();
        await useFeeStore.getState().fetchDueList();
      }
    } catch {
      // Offline fallback
    }

    const monthYear = format(new Date(), 'yyyy-MM');
    const receiptNumber = `RCP-2025-${String(Math.floor(Math.random() * 9999)).padStart(4, '0')}`;

    const newReceipt: Receipt = {
      id: Math.floor(Math.random() * 100000),
      receiptNumber,
      studentId: data.studentId,
      monthYear,
      monthlyFee: data.amount,
      lateFee: 0,
      gstAmount: 0,
      totalAmount: data.amount,
      amountPaid: data.amount,
      paymentMethod: data.paymentMethod,
      paymentDate: data.paymentDate,
      notes: data.notes,
      status: 'paid',
    };

    set(state => ({
      receipts: [newReceipt, ...state.receipts],
      dueList: state.dueList.filter(d => d.studentId !== data.studentId),
    }));

    return newReceipt;
  },
}));
