import { create } from 'zustand'
import type { Attachment } from '../domain/inquiry'

export type OfferStep = 'select_properties' | 'pdf_review' | 'checked' | 'send'

interface OfferWizardState {
  isOpen: boolean
  selectedNeedId: string | null
  needTitle: string
  selectedPropertyIds: string[]
  currentStep: OfferStep
  offerDraftId: string | null
  editableFields: Record<string, string>
  pdfPreviewReady: boolean
  messageDraft: string
  messageSubject: string
  attachments: Attachment[]
  open(needId: string, needTitle: string): void
  close(): void
  toggleProperty(id: string): void
  setSelectedProperties(ids: string[]): void
  setStep(step: OfferStep): void
  setOfferDraftId(id: string): void
  updateField(fieldId: string, value: string): void
  setPdfReady(): void
  setMessageDraft(text: string): void
  setMessageSubject(s: string): void
  addAttachment(a: Attachment): void
  removeAttachment(id: string): void
  reset(): void
}

export const useOfferWizardStore = create<OfferWizardState>((set) => ({
  isOpen: false,
  selectedNeedId: null,
  needTitle: '',
  selectedPropertyIds: [],
  currentStep: 'select_properties',
  offerDraftId: null,
  editableFields: {},
  pdfPreviewReady: false,
  messageDraft: '',
  messageSubject: '',
  attachments: [],
  open: (needId, needTitle) =>
    set((s) => ({
      isOpen: true,
      selectedNeedId: needId,
      needTitle,
      selectedPropertyIds: s.selectedPropertyIds,
      currentStep: 'select_properties',
      offerDraftId: null,
      editableFields: {},
      pdfPreviewReady: false,
      messageDraft: '',
      messageSubject: '',
      attachments: [],
    })),
  close: () => set({ isOpen: false }),
  toggleProperty: (id) =>
    set((s) => ({
      selectedPropertyIds: s.selectedPropertyIds.includes(id)
        ? s.selectedPropertyIds.filter((p) => p !== id)
        : [...s.selectedPropertyIds, id],
    })),
  setSelectedProperties: (ids) => set({ selectedPropertyIds: ids }),
  setStep: (currentStep) => set({ currentStep }),
  setOfferDraftId: (id) => set({ offerDraftId: id }),
  updateField: (fieldId, value) =>
    set((s) => ({ editableFields: { ...s.editableFields, [fieldId]: value } })),
  setPdfReady: () => set({ pdfPreviewReady: true }),
  setMessageDraft: (messageDraft) => set({ messageDraft }),
  setMessageSubject: (messageSubject) => set({ messageSubject }),
  addAttachment: (a) => set((s) => ({ attachments: [...s.attachments, a] })),
  removeAttachment: (id) =>
    set((s) => ({ attachments: s.attachments.filter((a) => a.id !== id) })),
  reset: () =>
    set({
      isOpen: false,
      selectedNeedId: null,
      needTitle: '',
      selectedPropertyIds: [],
      currentStep: 'select_properties',
      offerDraftId: null,
      editableFields: {},
      pdfPreviewReady: false,
      messageDraft: '',
      messageSubject: '',
      attachments: [],
    }),
}))
