import { create } from 'zustand'
import { crmApi } from '@/lib/api'

export interface Customer {
  id: string
  name: string
  email: string
  phone: string
  company: string
  org_number: string
  status: string
  source: string
  tags: string[]
  assigned_to: string | null
  created_at: string
  updated_at: string
}

export interface Lead {
  id: string
  name: string
  email: string
  company: string
  status: string
  source: string
}

export interface PipelineStage {
  stage: string
  count: number
  value: number
}

interface CRMState {
  customers: Customer[]
  leads: Lead[]
  pipeline: PipelineStage[]
  loading: boolean
  error: string | null
  fetchCustomers: () => Promise<void>
  fetchLeads: () => Promise<void>
  fetchPipeline: () => Promise<void>
  createCustomer: (data: Partial<Customer>) => Promise<void>
  updateCustomer: (id: string, data: Partial<Customer>) => Promise<void>
  deleteCustomer: (id: string) => Promise<void>
}

export const useCRMStore = create<CRMState>((set, get) => ({
  customers: [],
  leads: [],
  pipeline: [],
  loading: false,
  error: null,

  fetchCustomers: async () => {
    set({ loading: true, error: null })
    try {
      const data = await crmApi.customers()
      set({ customers: (data.customers || []) as Customer[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch customers', loading: false })
    }
  },

  fetchLeads: async () => {
    set({ loading: true, error: null })
    try {
      const data = await crmApi.leads()
      set({ leads: (data.leads || []) as Lead[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch leads', loading: false })
    }
  },

  fetchPipeline: async () => {
    set({ loading: true, error: null })
    try {
      const data = await crmApi.pipeline()
      set({ pipeline: (data.stages || []) as PipelineStage[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch pipeline', loading: false })
    }
  },

  createCustomer: async (data) => {
    set({ loading: true, error: null })
    try {
      await crmApi.createCustomer(data)
      await get().fetchCustomers()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to create customer', loading: false })
    }
  },

  updateCustomer: async (id, data) => {
    set({ loading: true, error: null })
    try {
      await crmApi.updateCustomer(id, data)
      await get().fetchCustomers()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to update customer', loading: false })
    }
  },

  deleteCustomer: async (id) => {
    set({ loading: true, error: null })
    try {
      await crmApi.deleteCustomer(id)
      await get().fetchCustomers()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to delete customer', loading: false })
    }
  },
}))
