"use client"

import { create } from "zustand"

interface MailSearchState {
  inputValue: string
  dropdownOpen: boolean
  selectedIndex: number
  advancedOpen: boolean
  /** Filter chips active in the dropdown (before submitting to URL). */
  chipAttachment: boolean
  chipLast7Days: boolean
  chipFromMe: boolean
}

interface MailSearchActions {
  setInputValue: (value: string) => void
  setDropdownOpen: (open: boolean) => void
  setSelectedIndex: (index: number) => void
  setAdvancedOpen: (open: boolean) => void
  toggleChipAttachment: () => void
  toggleChipLast7Days: () => void
  toggleChipFromMe: () => void
  resetChips: () => void
  reset: () => void
}

const INITIAL: MailSearchState = {
  inputValue: "",
  dropdownOpen: false,
  selectedIndex: -1,
  advancedOpen: false,
  chipAttachment: false,
  chipLast7Days: false,
  chipFromMe: false,
}

export const useMailSearchStore = create<MailSearchState & MailSearchActions>()(
  (set) => ({
    ...INITIAL,

    setInputValue: (value) =>
      set({ inputValue: value, dropdownOpen: value.length > 0, selectedIndex: -1 }),

    setDropdownOpen: (open) => set({ dropdownOpen: open }),

    setSelectedIndex: (index) => set({ selectedIndex: index }),

    setAdvancedOpen: (open) =>
      set({ advancedOpen: open, dropdownOpen: false }),

    toggleChipAttachment: () =>
      set((s) => ({ chipAttachment: !s.chipAttachment })),

    toggleChipLast7Days: () =>
      set((s) => ({ chipLast7Days: !s.chipLast7Days })),

    toggleChipFromMe: () =>
      set((s) => ({ chipFromMe: !s.chipFromMe })),

    resetChips: () =>
      set({ chipAttachment: false, chipLast7Days: false, chipFromMe: false }),

    reset: () => set(INITIAL),
  })
)
