"use client"

import { create } from "zustand"
import type { DriveMimeCategory, DriveSourceId } from "@/lib/drive/drive-filters"

export type DriveDatePreset =
  | "today"
  | "last7"
  | "last30"
  | "thisYear"
  | "lastYear"
  | "custom"
  | null

export interface DriveFiltersSnapshot {
  types: Set<DriveMimeCategory>
  sources: Set<DriveSourceId>
  contactEmail: string | null
  contactName: string | null
  datePreset: DriveDatePreset
  dateFrom: string | null
  dateTo: string | null
}

interface DriveFiltersStore extends DriveFiltersSnapshot {
  toggleType: (type: DriveMimeCategory) => void
  toggleSource: (source: DriveSourceId) => void
  setContact: (contact: { email?: string; name: string } | null) => void
  setDateRange: (preset: DriveDatePreset, from?: string | null, to?: string | null) => void
  clearDate: () => void
  clearAll: () => void
}

export const useDriveFiltersStore = create<DriveFiltersStore>((set, get) => ({
  types: new Set(),
  sources: new Set(),
  contactEmail: null,
  contactName: null,
  datePreset: null,
  dateFrom: null,
  dateTo: null,

  toggleType: (type) => {
    const next = new Set(get().types)
    if (next.has(type)) next.delete(type)
    else next.add(type)
    set({ types: next })
  },
  toggleSource: (source) => {
    const next = new Set(get().sources)
    if (next.has(source)) next.delete(source)
    else next.add(source)
    set({ sources: next })
  },
  setContact: (contact) =>
    set({
      contactEmail: contact?.email ?? null,
      contactName: contact?.name ?? null,
    }),
  setDateRange: (datePreset, dateFrom = null, dateTo = null) =>
    set({ datePreset, dateFrom, dateTo }),
  clearDate: () => set({ datePreset: null, dateFrom: null, dateTo: null }),
  clearAll: () =>
    set({
      types: new Set(),
      sources: new Set(),
      contactEmail: null,
      contactName: null,
      datePreset: null,
      dateFrom: null,
      dateTo: null,
    }),
}))

export function driveFiltersActive(s: DriveFiltersSnapshot): boolean {
  return (
    s.types.size > 0 ||
    s.sources.size > 0 ||
    Boolean(s.contactEmail || s.contactName) ||
    Boolean(s.datePreset)
  )
}
