import { create } from 'zustand';
import type { MailProvider } from '../hooks/useMailConnect';

type ProviderSnapshot = {
  id: MailProvider;
  labelKey: string;
  icon: string;
  color: string;
  guideKey: string;
  guideUrl: string;
  disabled?: boolean;
  disabledLabelKey?: string;
  authMethod?: 'imap' | 'oauth_microsoft';
};

type MailConnectDraftState = {
  view: 'consent' | 'grid' | 'form' | 'oauth_warning' | 'oauth_pending';
  consentGiven: boolean;
  selectedProvider: ProviderSnapshot | null;
  email: string;
  title: string;
  /** Set after a successful OAuth callback so the Title-Edit sheet can open in the parent. */
  pendingOAuthConnectionId: string | null;

  setView: (view: MailConnectDraftState['view']) => void;
  setConsentGiven: (v: boolean) => void;
  setSelectedProvider: (p: ProviderSnapshot | null) => void;
  setEmail: (email: string) => void;
  setTitle: (title: string) => void;
  setPendingOAuthConnectionId: (id: string | null) => void;
  reset: () => void;
};

const INITIAL: Pick<
  MailConnectDraftState,
  'view' | 'consentGiven' | 'selectedProvider' | 'email' | 'title' | 'pendingOAuthConnectionId'
> = {
  view: 'consent',
  consentGiven: false,
  selectedProvider: null,
  email: '',
  title: '',
  pendingOAuthConnectionId: null,
};

export const useMailConnectDraft = create<MailConnectDraftState>((set) => ({
  ...INITIAL,

  setView: (view) => set({ view }),
  setConsentGiven: (consentGiven) => set({ consentGiven }),
  setSelectedProvider: (selectedProvider) => set({ selectedProvider }),
  setEmail: (email) => set({ email }),
  setTitle: (title) => set({ title }),
  setPendingOAuthConnectionId: (pendingOAuthConnectionId) => set({ pendingOAuthConnectionId }),
  reset: () => set(INITIAL),
}));
