export type ProjectStatus = 'planned' | 'active' | 'on_hold' | 'completed' | 'cancelled' | 'archived';

export interface ProjectPermissions {
  role: ProjectMemberRole | null;
  can_manage: boolean;
  can_update_work_items: boolean;
  can_plan_capacity: boolean;
}
export type SprintStatus =
  | 'draft'
  | 'planned'
  | 'active'
  | 'completed'
  | 'cancelled'
  | 'archived';

export type SprintLifecycleAction =
  | 'view'
  | 'edit'
  | 'manage_backlog'
  | 'capacity'
  | 'duplicate'
  | 'start'
  | 'complete'
  | 'cancel'
  | 'archive'
  | 'restore'
  | 'delete';

export interface SprintLifecyclePermissions {
  can_edit: boolean;
  can_delete: boolean;
  delete_blocked_reason: string | null;
  editable_fields: string[];
  read_only: boolean;
  can_restore: boolean;
  available_actions: SprintLifecycleAction[];
  warnings: string[];
}
export type ProjectMemberRole = 'owner' | 'manager' | 'member' | 'viewer';
export type WorkType =
  | 'helpdesk_ticket'
  | 'project_task'
  | 'bug'
  | 'improvement'
  | 'backlog_item'
  | 'story'
  | 'spike'
  | 'technical_task';

/** Sprint board column keys (internal API values; DB column remains `kanban_column`). */
export type SprintBoardColumnKey =
  | 'backlog'
  | 'in_progress'
  | 'review'
  | 'testing'
  | 'blocked'
  | 'done';

/** @deprecated Use SprintBoardColumnKey. Legacy `ready` is normalized server-side. */
export type KanbanColumnKey = SprintBoardColumnKey | 'ready';

export type ProjectHealthLevel = 'initializing' | 'healthy' | 'attention' | 'critical';
export type DependencyType = 'FS' | 'SS' | 'FF' | 'SF';

export interface ProjectActiveSprintSummary {
  id: string;
  name: string;
  status: SprintStatus;
  due_date: string | null;
  is_overdue?: boolean;
}

export interface ProjectSummary {
  id: string;
  company_id: string;
  department_id: string;
  department?: { id: string; name: string; code: string };
  owner_user_id: string;
  owner?: { id: string; name: string; email: string };
  name: string;
  key: string;
  description: string | null;
  status: ProjectStatus;
  start_date: string | null;
  due_date: string | null;
  completed_at: string | null;
  archived_at?: string | null;
  color: string | null;
  permissions?: ProjectPermissions;
  completion_percentage?: number;
  health_level?: ProjectHealthLevel;
  active_sprint?: ProjectActiveSprintSummary | null;
  is_overdue: boolean;
  created_at: string;
  updated_at: string;
}

export function isProjectSummary(value: unknown): value is ProjectSummary {
  if (typeof value !== 'object' || value === null) {
    return false;
  }

  const project = value as Record<string, unknown>;

  return (
    typeof project.id === 'string' &&
    typeof project.company_id === 'string' &&
    typeof project.department_id === 'string' &&
    typeof project.owner_user_id === 'string' &&
    typeof project.name === 'string' &&
    typeof project.key === 'string' &&
    typeof project.status === 'string' &&
    typeof project.is_overdue === 'boolean'
  );
}

export interface ProjectMember {
  id: string;
  project_id: string;
  user_id: string;
  role: ProjectMemberRole;
  user?: { id: string; name: string; email: string };
}

export type SprintHealth = 'on_track' | 'steady' | 'needs_attention' | 'at_risk' | 'overcommitted';

export type ExecutiveHealth = 'good' | 'warning' | 'at_risk' | 'critical';

export interface SprintHealthSummary {
  status: ExecutiveHealth;
  blocked_items: number;
  overdue_items: number;
  capacity_utilization_percent: number;
  sprint_progress_percent: number;
  recommendation: string;
}

export interface ProjectSprint {
  id: string;
  project_id: string;
  name: string;
  goal: string | null;
  status: SprintStatus;
  start_date: string;
  due_date: string;
  completed_at: string | null;
  sort_order: number;
  is_overdue: boolean;
  capacity_md?: number | null;
  committed_md?: number;
  completed_md?: number;
  velocity_md?: number | null;
  progress_percent?: number;
  utilization_percent?: number | null;
  health?: SprintHealth;
  executive_health?: ExecutiveHealth;
  executive_health_score?: number;
  executive_health_detail?: {
    score: number;
    status: string;
    classification: string;
    breakdown: Record<
      string,
      { score: number; weight: number; weighted_score: number; explanation: string }
    >;
    recommendations: string[];
  };
  health_summary?: SprintHealthSummary;
  archived_at?: string | null;
  cancelled_at?: string | null;
  lifecycle?: SprintLifecyclePermissions;
}

export interface CapacityTeamMember {
  user_id: string;
  name: string;
  role?: string;
  capacity_md: number;
  assigned_md: number;
  remaining_md: number;
  utilization_percent: number;
  health: 'green' | 'yellow' | 'orange' | 'red';
  overload_md: number;
  recommendation?: string;
}

export interface CapacityPlanningDashboard {
  sprint: { id: string; name: string; start_date: string; due_date: string };
  has_participants?: boolean;
  message?: string | null;
  metrics: {
    total_capacity_md: number;
    assigned_md: number;
    remaining_md: number;
    overallocated_users: number;
  };
  team: CapacityTeamMember[];
}

export interface ProjectCommandCenter {
  project_health: ProjectHealth;
  progress_percent: number;
  open_work_count: number;
  completed_work_count: number;
  open_work_md: number;
  active_sprint: {
    sprint: { id: string; name: string; start_date: string; due_date: string };
    health: Record<string, unknown>;
    burndown: BurndownSeries;
  } | null;
  velocity: VelocityData;
  risks_open: number;
  dependencies_count: number;
  overdue_work_count: number;
  blocked_work_count: number;
  team_capacity: CapacityPlanningDashboard | null;
  upcoming_milestones: Array<{ id: string; name: string; due_date: string; status: string }>;
  recent_activity: Array<{ event: string; action: string | null; created_at: string }>;
}

export interface BacklogMetrics {
  total: number;
  ready_for_sprint: number;
  in_sprint: number;
  blocked: number;
  completed: number;
  overdue: number;
}

export interface BacklogEpicGroup {
  epic: { id: string; name: string; color: string | null } | null;
  items: ProjectWorkItem[];
}

export type BacklogEmptyState = 'no_items' | 'all_in_sprint' | 'no_backlog_items' | 'has_items';

export interface BacklogAnalytics {
  avg_business_value: number | null;
  labeled_items: number;
  epic_progress: Array<{
    epic_id: string;
    name: string;
    total: number;
    completed: number;
    progress_percent: number;
  }>;
  priority_distribution: Record<string, number>;
}

export interface BacklogDashboard {
  metrics: BacklogMetrics;
  analytics?: BacklogAnalytics;
  empty_state: BacklogEmptyState;
  items: ProjectWorkItem[];
  epic_groups: BacklogEpicGroup[];
  filters: Record<string, unknown>;
}

export interface RiskMatrixCell {
  probability: number;
  impact: number;
  score: number;
  count: number;
  risks: Array<{ id: string; title: string; category?: string; status: string }>;
}

export interface RiskMatrixData {
  cells: RiskMatrixCell[];
  total_open: number;
  critical: number;
}

export interface MilestoneTimelineItem {
  id: string;
  name: string;
  due_date: string;
  status: string;
  progress_percent: number;
  is_overdue: boolean;
  days_variance: number;
  health: string;
}

export interface ProjectEpic {
  id: string;
  name: string;
  color: string | null;
  description?: string | null;
}

export interface AcceptanceCriterion {
  id: string;
  description: string;
  sort_order: number;
  is_completed: boolean;
}

export interface WorkItemDetail {
  id: string;
  ticket_number: string;
  ticket_type: string;
  subject: string;
  description: string | null;
  work_type: string | null;
  project_id: string;
  sprint_id: string | null;
  epic_id: string | null;
  estimate_md: number;
  estimate_points: number | null;
  due_date: string | null;
  start_date: string | null;
  completed_at: string | null;
  is_overdue: boolean;
  status: { id: string; name_en: string; color: string } | null;
  priority: { id: string; name_en: string; color: string } | null;
  assignee: { id: string; name: string } | null;
  epic: { id: string; name: string; color: string | null } | null;
  sprint: { id: string; name: string; status: string } | null;
  acceptance_criteria: AcceptanceCriterion[];
  dependency_count: number;
  comment_count: number;
}

export interface ProjectWorkItem {
  id: string;
  ticket_number: string;
  ticket_type?: string;
  subject: string;
  work_type: WorkType | string | null;
  project_id: string | null;
  sprint_id: string | null;
  epic_id?: string | null;
  release_id?: string | null;
  backlog_order: number | null;
  sprint_order: number | null;
  start_date: string | null;
  due_date: string | null;
  completed_at: string | null;
  estimate_md: number | null;
  estimate_points?: number | null;
  estimate_minutes?: number | null;
  is_overdue: boolean;
  dependency_count?: number;
  comment_count?: number;
  epic?: { id: string; name: string; color: string | null } | null;
  assignee?: { id: string; name: string } | null;
  collaborators?: Array<{ id: string; name: string }>;
  collaborator_count?: number;
  watcher_count?: number;
  status?: { id: string; name_en: string; color: string };
  priority?: { id: string; name_en: string; color: string };
}

export interface SprintBoardColumn {
  key: SprintBoardColumnKey;
  label: string;
  label_ar?: string;
  tickets: ProjectWorkItem[];
}

/** @deprecated Use SprintBoardColumn */
export type KanbanColumn = SprintBoardColumn;

export interface SprintBoard {
  columns: SprintBoardColumn[];
}

/** @deprecated Use SprintBoard */
export type KanbanBoard = SprintBoard;

export interface BoardTicket {
  id: string;
  ticket_number: string;
  subject: string;
  sprint_id: string | null;
  estimate_md: number | null;
  due_date: string | null;
  dependency_count: number;
  assignee?: { id: string; name: string } | null;
  collaborators?: Array<{ id: string; name: string }>;
  collaborator_count?: number;
  watcher_count?: number;
  status?: { id: string; name_en: string; color: string };
  priority?: { id: string; name_en: string; color: string };
}

export interface BoardColumn {
  key: SprintBoardColumnKey;
  label: string;
  label_ar?: string;
  ticket_status_id: string | null;
  tickets: BoardTicket[];
}

export type DependencyCompletionMode = 'warn' | 'require_override' | 'block';

export interface ProjectBoard {
  board_type?: 'scrum_sprint_board';
  methodology?: 'scrum';
  columns: BoardColumn[];
  sprints: Array<{ id: string; name: string; status: string }>;
  filters: Record<string, unknown>;
  active_sprint_id?: string | null;
  dependency_completion_mode?: DependencyCompletionMode;
}

export interface BurndownSeries {
  ideal_line: Array<{ date: string; value: number }>;
  actual_line: Array<{ date: string; value: number }>;
  remaining_md: Array<{ date: string; value: number }>;
  completed_md: Array<{ date: string; value: number }>;
  total_md?: number;
}

export interface ProjectHealth {
  score: number | null;
  level: ProjectHealthLevel;
  message?: string | null;
  ready?: boolean;
  components: Record<string, number>;
}

export interface SprintCapacitySummary {
  sprint_id: string;
  capacity_md: number | null;
  committed_md: number;
  completed_md: number;
  remaining_md: number;
  capacity_exceeded: boolean;
  warnings?: string[];
}

export interface VelocityData {
  sprints: Array<{
    sprint_id: string;
    sprint_name: string;
    completed_md: number;
  }>;
  average_velocity_md: number;
  best_sprint_md: number;
  worst_sprint_md: number;
  trend: string;
  windows: { last_3: number; last_5: number; last_10: number };
}

export interface WorkloadUser {
  user_id: string;
  name: string | null;
  assigned_tickets: number;
  assigned_md: number;
  capacity_md: number | null;
  overdue_count: number;
  load_percent: number;
  status: 'balanced' | 'overloaded' | 'underloaded';
}

export interface WorkloadData {
  sprint_id: string | null;
  capacity_md: number | null;
  users: WorkloadUser[];
}

export interface ProjectRisk {
  id: string;
  project_id: string;
  title: string;
  description: string | null;
  probability: number;
  impact: number;
  owner_user_id: string | null;
  status: 'open' | 'mitigating' | 'monitoring' | 'mitigated' | 'closed';
  mitigation_plan: string | null;
  category?: string | null;
  target_date?: string | null;
}

export interface RiskMetrics {
  open: number;
  critical: number;
  closed: number;
}

export interface PortfolioProjectCard {
  id: string;
  name: string;
  key: string;
  department: string | null;
  status: string;
  health: ProjectHealth;
  velocity_average: number;
  overdue_count: number;
  completion_percentage: number;
}

export interface PortfolioDashboard {
  projects: PortfolioProjectCard[];
  active_sprints_count: number;
  upcoming_releases: Array<{ id: string; name: string; version: string | null; release_date: string | null }>;
  filters: Record<string, unknown>;
}

export type GanttEntityType =
  | 'project'
  | 'epic'
  | 'release'
  | 'sprint'
  | 'milestone'
  | 'task'
  | 'dependency'
  | 'risk';

export interface GanttTimelineItem {
  id: string;
  entity_id: string;
  entity_type: GanttEntityType;
  title: string;
  start_date: string | null;
  end_date: string | null;
  progress_percentage: number;
  status: string;
  parent_id: string | null;
  depends_on: string[];
  blocked_by: string[];
  owner?: string | null;
  priority?: string | null;
  color?: string | null;
  tooltip?: string;
  is_delayed: boolean;
  is_blocked: boolean;
  is_milestone?: boolean;
}

export interface ProjectGanttTimeline {
  project: {
    id: string;
    name: string;
    key?: string;
    status: string;
    health: string;
    progress_percentage: number;
  };
  timeline: GanttTimelineItem[];
  dependencies: Array<{ id?: string; from: string; to: string; type?: DependencyType }>;
  milestones: GanttTimelineItem[];
  summary: {
    total_items: number;
    completed_items: number;
    blocked_items: number;
    delayed_items: number;
    upcoming_milestones: number;
  };
}

export interface PortfolioTimelineMilestone {
  id: string;
  name: string;
  due_date: string;
  completed?: boolean;
}

export interface PortfolioFilterOption {
  id: string;
  name: string;
}

export interface PortfolioHealthTrend {
  previous_score: number | null;
  trend_percent: number | null;
  direction: 'up' | 'down' | 'stable';
}

export interface PortfolioDepartmentExposure {
  department_id: string;
  name: string;
  project_count: number;
  at_risk_count: number;
  delayed_count: number;
}

export interface PortfolioOwnerRiskExposure {
  owner_user_id: string;
  name: string;
  project_count: number;
  risk_score: number;
}

export interface PortfolioHealthContributors {
  blocked: number;
  delayed: number;
  risks: number;
  capacity: number;
}

export interface PortfolioHealthDrivers {
  at_risk_projects: number;
  delayed_projects: number;
  blocked_dependencies: number;
  critical_projects: number;
  healthy_projects: number;
}

export interface PortfolioForecastSummary {
  planned_finish: string | null;
  forecast_finish: string | null;
  variance_days: number | null;
  confidence_percent: number;
  label: string;
}

export interface DeliveryConfidence {
  percent: number;
  level: 'high' | 'low';
}

export interface ProjectHealthExplanation {
  project_id: string;
  project_name: string;
  health_score: number | null;
  status: string;
  reasons: string[];
  impacts: string[];
  recommended_actions: string[];
  risk_contributors: {
    blocked_dependencies: number;
    overdue_milestones: number;
    open_risks: number;
  };
  sprint_health_score: number | null;
  forecast_variance_days: number | null;
}

export interface PortfolioTimelineRow {
  id: string;
  project_id: string;
  title: string;
  owner: string | null;
  owner_user_id?: string | null;
  department: string | null;
  department_id?: string | null;
  planned_finish?: string | null;
  forecast_finish?: string | null;
  forecast_variance_days?: number | null;
  start_date: string | null;
  end_date: string | null;
  planned_start_date: string | null;
  planned_end_date: string | null;
  actual_start_date: string | null;
  actual_end_date: string | null;
  progress_percentage: number;
  status: string;
  health: string;
  current_sprint: string | null;
  next_milestone: string | null;
  delayed_milestones_count: number;
  milestones_count: number;
  open_risks_count: number;
  blocked_dependencies_count: number;
  open_coordination_dependencies_count?: number;
  is_delayed: boolean;
  is_blocked: boolean;
  is_at_risk?: boolean;
  milestones?: PortfolioTimelineMilestone[];
}

export interface PortfolioGanttTimeline {
  range?: string;
  year?: number;
  range_start: string;
  range_end: string;
  summary: {
    total_projects: number;
    active_projects: number;
    completed_projects: number;
    delayed_projects: number;
    blocked_projects: number;
    at_risk_projects: number;
    portfolio_health_score?: number;
    portfolio_health_class?: string;
    health_trend?: PortfolioHealthTrend;
    portfolio_health_contributors?: PortfolioHealthContributors;
    portfolio_health_drivers?: PortfolioHealthDrivers;
    portfolio_forecast?: PortfolioForecastSummary;
    delivery_confidence?: DeliveryConfidence;
    department_exposure?: PortfolioDepartmentExposure[];
    owner_risk_exposure?: PortfolioOwnerRiskExposure[];
  };
  timeline: PortfolioTimelineRow[];
  cross_project_dependencies: CrossProjectDependency[];
  filter_options?: {
    departments: PortfolioFilterOption[];
    owners: PortfolioFilterOption[];
  };
}

export type DependencyRiskLevel = 'low' | 'medium' | 'high' | 'critical';
export type CoordinationHealthClass = 'excellent' | 'healthy' | 'at_risk' | 'critical';
export type ExposureLevel = 'low' | 'medium' | 'high' | 'critical';

export interface CrossProjectDependency {
  id: string;
  source_project_id: string;
  source_project_name?: string;
  source_item_type: string;
  source_item_id: string | null;
  target_project_id: string;
  target_project_name?: string;
  target_item_type: string;
  target_item_id: string | null;
  dependency_type: string;
  status: string;
  due_date: string | null;
  owner_id: string | null;
  owner_name?: string | null;
  owner_required?: boolean;
  responsible_team?: string | null;
  department?: string | null;
  notes: string | null;
  is_critical?: boolean;
  is_escalated?: boolean;
  risk_level?: DependencyRiskLevel;
  days_remaining?: number | null;
  last_updated?: string | null;
  resolved_at?: string | null;
  attention_priority?: number;
}

export interface PortfolioCoordinationHealth {
  score: number;
  classification: CoordinationHealthClass;
  label: string;
}

export interface PortfolioCoordinationSummary {
  total: number;
  open: number;
  at_risk: number;
  resolved_this_month: number;
  projects_involved: number;
  health: PortfolioCoordinationHealth;
  health_trend: {
    current_score: number;
    previous_score: number;
    delta: number;
    resolved_current_month: number;
    resolved_previous_month: number;
  };
}

export interface PortfolioDependencyChain {
  projects: Array<{ id: string; name: string }>;
  length: number;
  projects_affected: number;
  earliest_deadline: string | null;
  risk_score: number;
}

export interface PortfolioProjectExposure {
  project_id: string;
  project_name: string;
  incoming: number;
  outgoing: number;
  open: number;
  risk_score: number;
  total_links: number;
  exposure_level: ExposureLevel;
}

export interface PortfolioCoordinationAnalytics {
  status_distribution: Array<{ label: string; count: number }>;
  type_distribution: Array<{ label: string; count: number }>;
  department_exposure: Array<{ label: string; count: number }>;
  health_trend: Array<{ month: string; label: string; value: number }>;
  resolution_trend: Array<{ month: string; label: string; value: number }>;
}

export interface PortfolioCoordinationDashboard {
  summary: PortfolioCoordinationSummary;
  attention_items: CrossProjectDependency[];
  attention_total: number;
  chains: {
    chains: PortfolioDependencyChain[];
    longest: PortfolioDependencyChain | null;
    highest_risk: PortfolioDependencyChain | null;
  };
  project_exposure: PortfolioProjectExposure[];
  analytics: PortfolioCoordinationAnalytics;
  commitments: {
    within_7_days: CrossProjectDependency[];
    within_14_days: CrossProjectDependency[];
    within_30_days: CrossProjectDependency[];
  };
}

export interface PaginatedDependencies {
  data: CrossProjectDependency[];
  meta: {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
}

/** @deprecated Use ProjectGanttTimeline */
export interface GanttPayload {
  id: string;
  name: string;
  key?: string;
  status: string;
  start_date: string | null;
  due_date: string | null;
  completion_percentage: number;
  is_overdue: boolean;
  epics?: Array<{
    id: string;
    name: string;
    start_date: string | null;
    due_date: string | null;
    status: string;
    color: string | null;
  }>;
  releases?: Array<{
    id: string;
    name: string;
    version: string | null;
    start_date: string | null;
    release_date: string | null;
    status: string;
  }>;
  milestones: Array<{ id: string; name: string; due_date: string; status: string; is_overdue: boolean }>;
  sprints: Array<{
    id: string;
    name: string;
    status: string;
    start_date: string;
    due_date: string;
    is_overdue: boolean;
  }>;
  work_items: Array<{
    id: string;
    ticket_number: string;
    subject: string;
    work_type: string | null;
    start_date: string | null;
    due_date: string | null;
    sprint_id: string | null;
    epic_id?: string | null;
    release_id?: string | null;
    is_overdue: boolean;
  }>;
  dependencies: Array<{ id?: string; from: string; to: string; type?: DependencyType }>;
}

export type ProjectListScope = 'active' | 'archived' | 'all';

export interface ProjectListFilters {
  status?: ProjectStatus;
  department_id?: string;
  search?: string;
  page?: number;
  per_page?: number;
  include_archived?: boolean;
  scope?: ProjectListScope;
}
