import React from 'react'
import {
  SDKState,
  SDKAction,
  SDKStep,
  CheckpointStatus,
  UseCaseAssessment,
  Risk,
  Control,
  UserPreferences,
  CustomerType,
  CompanyProfile,
  ImportedDocument,
  GapAnalysis,
  SDKPackageId,
  ProjectInfo,
} from './types'
import { SyncState } from './sync'

// =============================================================================
// INITIAL STATE
// =============================================================================

const initialPreferences: UserPreferences = {
  language: 'de',
  theme: 'light',
  compactMode: false,
  showHints: true,
  autoSave: true,
  autoValidate: true,
  allowParallelWork: true, // Standard: Paralleles Arbeiten erlaubt
}

export const initialState: SDKState = {
  // Metadata
  version: '1.0.0',
  projectVersion: 1,
  lastModified: new Date(),

  // Tenant & User
  tenantId: '',
  userId: '',
  subscription: 'PROFESSIONAL',

  // Project Context
  projectId: '',
  projectInfo: null,

  // Customer Type
  customerType: null,

  // Company Profile
  companyProfile: null,

  // Compliance Scope
  complianceScope: null,

  // Source Policy
  sourcePolicy: null,

  // Progress
  currentPhase: 1,
  currentStep: 'company-profile',
  completedSteps: [],
  checkpoints: {},

  // Imported Documents (for existing customers)
  importedDocuments: [],
  gapAnalysis: null,

  // Phase 1 Data
  useCases: [],
  activeUseCase: null,
  screening: null,
  modules: [],
  requirements: [],
  controls: [],
  evidence: [],
  checklist: [],
  risks: [],

  // Phase 2 Data
  aiActClassification: null,
  obligations: [],
  dsfa: null,
  toms: [],
  retentionPolicies: [],
  vvt: [],
  documents: [],
  cookieBanner: null,
  consents: [],
  dsrConfig: null,
  escalationWorkflows: [],

  // IACE (Industrial AI Compliance Engine)
  iaceProjects: [],

  // RAG Corpus Versioning
  ragCorpusStatus: null,

  // Security
  sbom: null,
  securityIssues: [],
  securityBacklog: [],

  // Catalog Manager
  customCatalogs: {},

  // UI State
  commandBarHistory: [],
  recentSearches: [],
  preferences: initialPreferences,
}

// =============================================================================
// EXTENDED ACTION TYPES
// =============================================================================

// Extended action type to include demo data loading
export type ExtendedSDKAction =
  | SDKAction
  | { type: 'LOAD_DEMO_DATA'; payload: Partial<SDKState> }

// =============================================================================
// CONTEXT TYPES
// =============================================================================

export interface SDKContextValue {
  state: SDKState
  dispatch: React.Dispatch<ExtendedSDKAction>

  // Navigation
  currentStep: SDKStep | undefined
  goToStep: (stepId: string) => void
  goToNextStep: () => void
  goToPreviousStep: () => void
  canGoNext: boolean
  canGoPrevious: boolean

  // Progress
  completionPercentage: number
  phase1Completion: number
  phase2Completion: number
  packageCompletion: Record<SDKPackageId, number>

  // Customer Type
  setCustomerType: (type: CustomerType) => void

  // Company Profile
  setCompanyProfile: (profile: CompanyProfile) => void
  updateCompanyProfile: (updates: Partial<CompanyProfile>) => void

  // Compliance Scope
  setComplianceScope: (scope: import('./compliance-scope-types').ComplianceScopeState) => void
  updateComplianceScope: (updates: Partial<import('./compliance-scope-types').ComplianceScopeState>) => void

  // Import (for existing customers)
  addImportedDocument: (doc: ImportedDocument) => void
  setGapAnalysis: (analysis: GapAnalysis) => void

  // Checkpoints
  validateCheckpoint: (checkpointId: string) => Promise<CheckpointStatus>
  overrideCheckpoint: (checkpointId: string, reason: string) => Promise<void>
  getCheckpointStatus: (checkpointId: string) => CheckpointStatus | undefined

  // State Updates
  updateUseCase: (id: string, data: Partial<UseCaseAssessment>) => void
  addRisk: (risk: Risk) => void
  updateControl: (id: string, data: Partial<Control>) => void

  // Persistence
  saveState: () => Promise<void>
  loadState: () => Promise<void>

  // Demo Data
  loadDemoData: (demoState: Partial<SDKState>) => void
  seedDemoData: () => Promise<{ success: boolean; message: string }>
  clearDemoData: () => Promise<boolean>
  isDemoDataLoaded: boolean

  // Sync
  syncState: SyncState
  forceSyncToServer: () => Promise<void>
  isOnline: boolean

  // Export
  exportState: (format: 'json' | 'pdf' | 'zip') => Promise<Blob>

  // Command Bar
  isCommandBarOpen: boolean
  setCommandBarOpen: (open: boolean) => void

  // Project Management
  projectId: string | undefined
  createProject: (name: string, customerType: CustomerType, copyFromProjectId?: string) => Promise<ProjectInfo>
  listProjects: () => Promise<ProjectInfo[]>
  switchProject: (projectId: string) => void
  archiveProject: (projectId: string) => Promise<void>
  restoreProject: (projectId: string) => Promise<ProjectInfo>
  permanentlyDeleteProject: (projectId: string) => Promise<void>
}

export const SDK_STORAGE_KEY = 'ai-compliance-sdk-state'
