import { createSlice, createAsyncThunk, type PayloadAction } from "@reduxjs/toolkit"

// Define a type for the client contact
export interface ClientContact {
  id: number
  companyId: number
  companyName: string
  firstName: string
  lastName: string
  position: string
  email: string
  countryCode: string
  phoneNumber: string
  allowPlatformAccess: boolean
  avatar: string
}

// Define the state type
interface ClientContactsState {
  items: ClientContact[]
  status: "idle" | "loading" | "succeeded" | "failed"
  error: string | null
  filters: {
    search: string
    companies: number[]
    positions: string[]
  }
}

// Initial state
const initialState: ClientContactsState = {
  items: [],
  status: "idle",
  error: null,
  filters: {
    search: "",
    companies: [],
    positions: [],
  },
}

// Sample data for initial development
const sampleClientContacts: ClientContact[] = [
  {
    id: 1,
    companyId: 1,
    companyName: "Acme Corporation",
    firstName: "John",
    lastName: "Smith",
    position: "CEO",
    email: "john.smith@acmecorp.com",
    countryCode: "+1",
    phoneNumber: "555-123-4567",
    allowPlatformAccess: true,
    avatar: "john-smith",
  },
  {
    id: 2,
    companyId: 1,
    companyName: "Acme Corporation",
    firstName: "Sarah",
    lastName: "Johnson",
    position: "Operations Manager",
    email: "sarah.johnson@acmecorp.com",
    countryCode: "+1",
    phoneNumber: "555-234-5678",
    allowPlatformAccess: true,
    avatar: "sarah-johnson",
  },
  {
    id: 3,
    companyId: 1,
    companyName: "Acme Corporation",
    firstName: "Michael",
    lastName: "Brown",
    position: "Finance Director",
    email: "michael.brown@acmecorp.com",
    countryCode: "+1",
    phoneNumber: "555-345-6789",
    allowPlatformAccess: false,
    avatar: "michael-brown",
  },
  {
    id: 4,
    companyId: 2,
    companyName: "Global Healthcare",
    firstName: "Emma",
    lastName: "Wilson",
    position: "Medical Director",
    email: "emma.wilson@globalhealthcare.org",
    countryCode: "+44",
    phoneNumber: "20-7946-1234",
    allowPlatformAccess: true,
    avatar: "emma-wilson",
  },
  {
    id: 5,
    companyId: 2,
    companyName: "Global Healthcare",
    firstName: "David",
    lastName: "Lee",
    position: "Head of Operations",
    email: "david.lee@globalhealthcare.org",
    countryCode: "+44",
    phoneNumber: "20-7946-2345",
    allowPlatformAccess: false,
    avatar: "david-lee",
  },
  {
    id: 6,
    companyId: 3,
    companyName: "Edu Alliance",
    firstName: "Jennifer",
    lastName: "Garcia",
    position: "Dean of Administration",
    email: "jennifer.garcia@edualliance.edu",
    countryCode: "+1",
    phoneNumber: "416-555-3456",
    allowPlatformAccess: true,
    avatar: "jennifer-garcia",
  },
  {
    id: 7,
    companyId: 4,
    companyName: "Tech Innovations",
    firstName: "Raj",
    lastName: "Patel",
    position: "CTO",
    email: "raj.patel@techinnovations.com",
    countryCode: "+91",
    phoneNumber: "80-4567-1234",
    allowPlatformAccess: true,
    avatar: "raj-patel",
  },
  {
    id: 8,
    companyId: 4,
    companyName: "Tech Innovations",
    firstName: "Priya",
    lastName: "Sharma",
    position: "Project Manager",
    email: "priya.sharma@techinnovations.com",
    countryCode: "+91",
    phoneNumber: "80-4567-2345",
    allowPlatformAccess: false,
    avatar: "priya-sharma",
  },
  {
    id: 9,
    companyId: 5,
    companyName: "Charity Foundation",
    firstName: "James",
    lastName: "Wilson",
    position: "Executive Director",
    email: "james.wilson@charityfoundation.org",
    countryCode: "+61",
    phoneNumber: "2-9876-1234",
    allowPlatformAccess: true,
    avatar: "james-wilson",
  },
  {
    id: 10,
    companyId: 6,
    companyName: "Luxury Tours",
    firstName: "Mohammed",
    lastName: "Al-Farsi",
    position: "Sales Director",
    email: "mohammed.alfarsi@luxurytours.com",
    countryCode: "+971",
    phoneNumber: "4-123-1234",
    allowPlatformAccess: true,
    avatar: "mohammed-alfarsi",
  },
]

// Define the payload type for adding a new client contact
export interface AddClientContactPayload {
  companyId: number
  firstName: string
  lastName: string
  position: string
  email: string
  countryCode: string
  phoneNumber: string
  allowPlatformAccess: boolean
}

// Async thunks for API calls
export const fetchClientContacts = createAsyncThunk(
  "clientContacts/fetchClientContacts",
  async (_, { rejectWithValue }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))
      return sampleClientContacts
    } catch (error) {
      return rejectWithValue("Failed to fetch client contacts")
    }
  },
)

export const addClientContact = createAsyncThunk(
  "clientContacts/addClientContact",
  async (payload: AddClientContactPayload, { rejectWithValue, getState, dispatch }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))

      // Get the company name from the client companies state
      const state = getState() as any
      const company = state.clientCompanies.items.find((company: any) => company.id === payload.companyId)

      if (!company) {
        return rejectWithValue("Invalid company selected")
      }

      // Generate avatar seed
      const avatarSeed = `${payload.firstName.toLowerCase()}-${payload.lastName.toLowerCase()}`

      // Generate a new ID (in a real app, the server would do this)
      const newContact = {
        id: Date.now(),
        ...payload,
        companyName: company.name,
        avatar: avatarSeed,
      }

      // Increment the contact count for the company
      // This would typically be handled by the server in a real app
      const { incrementContactCount } = await import("./clientCompaniesSlice")
      dispatch(incrementContactCount(payload.companyId))

      return newContact
    } catch (error) {
      return rejectWithValue("Failed to add client contact")
    }
  },
)

export const updateClientContact = createAsyncThunk(
  "clientContacts/updateClientContact",
  async (payload: { id: number; updates: Partial<ClientContact> }, { rejectWithValue }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))
      return payload
    } catch (error) {
      return rejectWithValue("Failed to update client contact")
    }
  },
)

export const deleteClientContact = createAsyncThunk(
  "clientContacts/deleteClientContact",
  async (id: number, { rejectWithValue, getState, dispatch }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))

      // Get the contact to find its company ID
      const state = getState() as any
      const contact = state.clientContacts.items.find((contact: any) => contact.id === id)

      if (contact) {
        // Decrement the contact count for the company
        // This would typically be handled by the server in a real app
        const { decrementContactCount } = await import("./clientCompaniesSlice")
        dispatch(decrementContactCount(contact.companyId))
      }

      return id
    } catch (error) {
      return rejectWithValue("Failed to delete client contact")
    }
  },
)

// Create the slice
const clientContactsSlice = createSlice({
  name: "clientContacts",
  initialState,
  reducers: {
    updateFilters: (state, action: PayloadAction<Partial<ClientContactsState["filters"]>>) => {
      state.filters = { ...state.filters, ...action.payload }
    },
    resetFilters: (state) => {
      state.filters = initialState.filters
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchClientContacts.pending, (state) => {
        state.status = "loading"
      })
      .addCase(fetchClientContacts.fulfilled, (state, action) => {
        state.status = "succeeded"
        state.items = action.payload
      })
      .addCase(fetchClientContacts.rejected, (state, action) => {
        state.status = "failed"
        state.error = action.payload as string
      })
      .addCase(addClientContact.fulfilled, (state, action) => {
        state.items.push(action.payload)
      })
      .addCase(updateClientContact.fulfilled, (state, action) => {
        const { id, updates } = action.payload
        state.items = state.items.map((item) => (item.id === id ? { ...item, ...updates } : item))
      })
      .addCase(deleteClientContact.fulfilled, (state, action) => {
        state.items = state.items.filter((item) => item.id !== action.payload)
      })
  },
})

export const { updateFilters, resetFilters } = clientContactsSlice.actions

export default clientContactsSlice.reducer

