import { create } from 'zustand'

interface POSUser {
  id: string
  email: string
  firstName: string
  lastName: string
  role: string
}

type ReceiptFormat = 'thermal' | 'full'

interface POSState {
  currentTransactionId: string | null
  locationId: string | null
  registerId: string | null
  drawerSessionId: string | null
  locked: boolean
  cashier: POSUser | null
  token: string | null
  lastActivity: number
  accountId: string | null
  accountName: string | null
  accountPhone: string | null
  accountEmail: string | null
  receiptFormat: ReceiptFormat
  setTransaction: (id: string | null) => void
  setLocation: (id: string) => void
  setRegister: (id: string | null) => void
  setDrawerSession: (id: string | null) => void
  unlock: (user: POSUser, token: string) => void
  lock: () => void
  touchActivity: () => void
  setAccount: (id: string, name: string, phone?: string | null, email?: string | null) => void
  clearAccount: () => void
  setReceiptFormat: (format: ReceiptFormat) => void
  reset: () => void
}

const RECEIPT_FORMAT_KEY = 'pos_receipt_format'

function getStoredReceiptFormat(): ReceiptFormat {
  const stored = localStorage.getItem(RECEIPT_FORMAT_KEY)
  return stored === 'full' ? 'full' : 'thermal'
}

export const usePOSStore = create<POSState>((set) => ({
  currentTransactionId: null,
  locationId: null,
  registerId: localStorage.getItem('pos_register_id') ?? null,
  drawerSessionId: localStorage.getItem('pos_drawer_session_id') ?? null,
  locked: true,
  cashier: null,
  token: null,
  lastActivity: Date.now(),
  accountId: null,
  accountName: null,
  accountPhone: null,
  accountEmail: null,
  receiptFormat: getStoredReceiptFormat(),
  setTransaction: (id) => set({ currentTransactionId: id }),
  setLocation: (id) => set({ locationId: id }),
  setRegister: (id) => { if (id) localStorage.setItem('pos_register_id', id); else localStorage.removeItem('pos_register_id'); set({ registerId: id }) },
  setDrawerSession: (id) => { if (id) localStorage.setItem('pos_drawer_session_id', id); else localStorage.removeItem('pos_drawer_session_id'); set({ drawerSessionId: id }) },
  unlock: (user, token) => set({ locked: false, cashier: user, token, lastActivity: Date.now() }),
  lock: () => set({ locked: true, currentTransactionId: null }),
  touchActivity: () => set({ lastActivity: Date.now() }),
  setAccount: (id, name, phone, email) => set({ accountId: id, accountName: name, accountPhone: phone ?? null, accountEmail: email ?? null }),
  clearAccount: () => set({ accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
  setReceiptFormat: (format) => { localStorage.setItem(RECEIPT_FORMAT_KEY, format); set({ receiptFormat: format }) },
  reset: () => set({ currentTransactionId: null, accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
}))
