/**
 * State Management Types
 *
 * Types for React context state management:
 * - Reducer actions (VendorComplianceAction)
 * - State shape (VendorComplianceState)
 * - Context value with computed properties and action methods
 * - Statistics and API response types
 * - Form data types
 */

import type React from 'react'
import type { LocalizedText, Contact, ResponsibleParty, Address } from './types-common'
import type {
  ProcessingActivity,
  ProcessingActivityStatus,
  DataSubjectCategory,
  PersonalDataCategory,
  RecipientCategory,
  ThirdCountryTransfer,
  RetentionPeriod,
  LegalBasis,
  DataSource,
  SystemReference,
  DataFlow,
  ProtectionLevel,
  TransferMechanismType,
} from './types-processing'
import type {
  Vendor,
  VendorStatus,
  VendorRole,
  ServiceCategory,
  DataAccessLevel,
  ProcessingLocation,
  Certification,
  ReviewFrequency,
} from './types-vendor'
import type {
  ContractDocument,
  ContractStatus,
  DocumentType,
} from './types-contract'
import type {
  Finding,
  FindingType,
  FindingSeverity,
} from './types-finding'
import type {
  Control,
  ControlInstance,
  RiskAssessment,
  RiskLevel,
} from './types-risk'
import type { ExportFormat } from './types-audit'

// ==========================================
// STATE MANAGEMENT - ACTIONS
// ==========================================

export type VendorComplianceAction =
  // Processing Activities
  | { type: 'SET_PROCESSING_ACTIVITIES'; payload: ProcessingActivity[] }
  | { type: 'ADD_PROCESSING_ACTIVITY'; payload: ProcessingActivity }
  | { type: 'UPDATE_PROCESSING_ACTIVITY'; payload: { id: string; data: Partial<ProcessingActivity> } }
  | { type: 'DELETE_PROCESSING_ACTIVITY'; payload: string }
  // Vendors
  | { type: 'SET_VENDORS'; payload: Vendor[] }
  | { type: 'ADD_VENDOR'; payload: Vendor }
  | { type: 'UPDATE_VENDOR'; payload: { id: string; data: Partial<Vendor> } }
  | { type: 'DELETE_VENDOR'; payload: string }
  // Contracts
  | { type: 'SET_CONTRACTS'; payload: ContractDocument[] }
  | { type: 'ADD_CONTRACT'; payload: ContractDocument }
  | { type: 'UPDATE_CONTRACT'; payload: { id: string; data: Partial<ContractDocument> } }
  | { type: 'DELETE_CONTRACT'; payload: string }
  // Findings
  | { type: 'SET_FINDINGS'; payload: Finding[] }
  | { type: 'ADD_FINDINGS'; payload: Finding[] }
  | { type: 'UPDATE_FINDING'; payload: { id: string; data: Partial<Finding> } }
  // Controls
  | { type: 'SET_CONTROLS'; payload: Control[] }
  | { type: 'SET_CONTROL_INSTANCES'; payload: ControlInstance[] }
  | { type: 'UPDATE_CONTROL_INSTANCE'; payload: { id: string; data: Partial<ControlInstance> } }
  // Risk Assessments
  | { type: 'SET_RISK_ASSESSMENTS'; payload: RiskAssessment[] }
  | { type: 'UPDATE_RISK_ASSESSMENT'; payload: { id: string; data: Partial<RiskAssessment> } }
  // UI State
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_SELECTED_VENDOR'; payload: string | null }
  | { type: 'SET_SELECTED_ACTIVITY'; payload: string | null }
  | { type: 'SET_ACTIVE_TAB'; payload: string }

// ==========================================
// STATE MANAGEMENT - STATE
// ==========================================

export interface VendorComplianceState {
  // Data
  processingActivities: ProcessingActivity[]
  vendors: Vendor[]
  contracts: ContractDocument[]
  findings: Finding[]
  controls: Control[]
  controlInstances: ControlInstance[]
  riskAssessments: RiskAssessment[]

  // UI State
  isLoading: boolean
  error: string | null
  selectedVendorId: string | null
  selectedActivityId: string | null
  activeTab: string

  // Metadata
  lastModified: Date | null
}

// ==========================================
// STATISTICS INTERFACES
// ==========================================

export interface VendorStatistics {
  total: number
  byStatus: Record<VendorStatus, number>
  byRole: Record<VendorRole, number>
  byRiskLevel: Record<RiskLevel, number>
  pendingReviews: number
  withExpiredContracts: number
}

export interface ComplianceStatistics {
  averageComplianceScore: number
  findingsByType: Record<FindingType, number>
  findingsBySeverity: Record<FindingSeverity, number>
  openFindings: number
  resolvedFindings: number
  controlPassRate: number
}

export interface RiskOverview {
  averageInherentRisk: number
  averageResidualRisk: number
  highRiskVendors: number
  criticalFindings: number
  transfersToThirdCountries: number
}

// ==========================================
// CONTEXT VALUE
// ==========================================

export interface VendorComplianceContextValue extends VendorComplianceState {
  // Dispatch
  dispatch: React.Dispatch<VendorComplianceAction>

  // Computed
  vendorStats: VendorStatistics
  complianceStats: ComplianceStatistics
  riskOverview: RiskOverview

  // Actions - Processing Activities
  createProcessingActivity: (data: Omit<ProcessingActivity, 'id' | 'tenantId' | 'createdAt' | 'updatedAt'>) => Promise<ProcessingActivity>
  updateProcessingActivity: (id: string, data: Partial<ProcessingActivity>) => Promise<void>
  deleteProcessingActivity: (id: string) => Promise<void>
  duplicateProcessingActivity: (id: string) => Promise<ProcessingActivity>

  // Actions - Vendors
  createVendor: (data: Omit<Vendor, 'id' | 'tenantId' | 'createdAt' | 'updatedAt'>) => Promise<Vendor>
  updateVendor: (id: string, data: Partial<Vendor>) => Promise<void>
  deleteVendor: (id: string) => Promise<void>

  // Actions - Contracts
  uploadContract: (vendorId: string, file: File, metadata: Partial<ContractDocument>) => Promise<ContractDocument>
  updateContract: (id: string, data: Partial<ContractDocument>) => Promise<void>
  deleteContract: (id: string) => Promise<void>
  startContractReview: (contractId: string) => Promise<void>

  // Actions - Findings
  updateFinding: (id: string, data: Partial<Finding>) => Promise<void>
  resolveFinding: (id: string, resolution: string) => Promise<void>

  // Actions - Controls
  updateControlInstance: (id: string, data: Partial<ControlInstance>) => Promise<void>

  // Actions - Export
  exportVVT: (format: ExportFormat, activityIds?: string[]) => Promise<string>
  exportVendorAuditPack: (vendorId: string, format: ExportFormat) => Promise<string>
  exportRoPA: (format: ExportFormat) => Promise<string>

  // Data Loading
  loadData: () => Promise<void>
  refresh: () => Promise<void>
}

// ==========================================
// API RESPONSE TYPES
// ==========================================

export interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  timestamp: string
}

export interface PaginatedResponse<T> extends ApiResponse<T[]> {
  pagination: {
    page: number
    pageSize: number
    total: number
    totalPages: number
  }
}

// ==========================================
// FORM TYPES
// ==========================================

export interface ProcessingActivityFormData {
  vvtId: string
  name: LocalizedText
  responsible: ResponsibleParty
  dpoContact?: Contact
  purposes: LocalizedText[]
  dataSubjectCategories: DataSubjectCategory[]
  personalDataCategories: PersonalDataCategory[]
  recipientCategories: RecipientCategory[]
  thirdCountryTransfers: ThirdCountryTransfer[]
  retentionPeriod: RetentionPeriod
  technicalMeasures: string[]
  legalBasis: LegalBasis[]
  dataSources: DataSource[]
  systems: SystemReference[]
  dataFlows: DataFlow[]
  protectionLevel: ProtectionLevel
  dpiaRequired: boolean
  dpiaJustification?: string
  subProcessors: string[]
  owner: string
}

export interface VendorFormData {
  name: string
  legalForm?: string
  country: string
  address: Address
  website?: string
  role: VendorRole
  serviceDescription: string
  serviceCategory: ServiceCategory
  dataAccessLevel: DataAccessLevel
  processingLocations: ProcessingLocation[]
  transferMechanisms: TransferMechanismType[]
  certifications: Certification[]
  primaryContact: Contact
  dpoContact?: Contact
  securityContact?: Contact
  contractTypes: DocumentType[]
  reviewFrequency: ReviewFrequency
  notes?: string
}
