import type { IconType } from 'react-icons';
import {
  HiChartBar,
  HiClock,
  HiCollection,
  HiExclamation,
  HiLink,
  HiTrendingUp,
  HiUserGroup,
} from 'react-icons/hi';
import { ROUTES } from '@/shared/constants/routes';
import type { ReportSummaryMetric } from '@/features/projects/components/ReportPageLayout';

export type ReportChartType = 'line' | 'bar' | 'pie' | 'doughnut';

export interface ReportDefinition {
  key: string;
  title: string;
  subtitle: string;
  apiPath: string;
  exportType?: string;
  chartType: ReportChartType;
  emptyMessage: string;
  supportsSprintFilter?: boolean;
  buildSummary?: (summary: Record<string, unknown>) => ReportSummaryMetric[];
}

function metric(
  label: string,
  value: string | number,
  icon?: IconType,
  accent?: ReportSummaryMetric['accent'],
): ReportSummaryMetric {
  return { label, value, icon, accent };
}

export const ENTERPRISE_REPORTS: ReportDefinition[] = [
  {
    key: 'velocity',
    title: 'Velocity Trend Report',
    subtitle: 'Track team velocity across sprints to understand delivery capacity',
    apiPath: 'velocity',
    exportType: 'velocity',
    chartType: 'line',
    emptyMessage: 'Complete at least one sprint to see velocity data',
    buildSummary: (s) => [
      metric('Avg Velocity', `${s.average_velocity_md ?? 0} MD`, HiTrendingUp),
      metric('Trend', String(s.trend ?? 'stable').replace(/^\w/, (c) => c.toUpperCase())),
      metric('Total Sprints', Number(s.total_sprints ?? 0), HiCollection),
      metric('Total Completed', Number(s.total_completed_items ?? 0)),
    ],
  },
  {
    key: 'burndown',
    title: 'Sprint Burndown Report',
    subtitle: 'Track remaining work throughout the sprint',
    apiPath: 'burndown',
    chartType: 'line',
    emptyMessage: 'Start a sprint to see burndown data',
    supportsSprintFilter: true,
    buildSummary: (s) => [
      metric('Sprint', String(s.sprint_name ?? '—'), HiClock),
      metric('Remaining', `${s.current_remaining_md ?? '—'} MD`, HiChartBar),
      metric('Expected', `${s.expected_remaining_md ?? '—'} MD`),
      metric('Days Left', Number(s.days_remaining ?? 0), HiClock),
    ],
  },
  {
    key: 'burnup',
    title: 'Sprint Burnup Report',
    subtitle: 'Compare completed work against total sprint scope',
    apiPath: 'burnup',
    chartType: 'line',
    emptyMessage: 'Start a sprint to see burnup data',
    supportsSprintFilter: true,
    buildSummary: (s) => [
      metric('Total Scope', `${s.total_scope_md ?? 0} MD`, HiCollection),
      metric('Completed', `${s.completed_md ?? 0} MD`),
      metric('Remaining', `${s.remaining_md ?? 0} MD`, HiChartBar),
    ],
  },
  {
    key: 'throughput',
    title: 'Throughput Report',
    subtitle: 'Items completed per day over the selected period',
    apiPath: 'throughput',
    chartType: 'bar',
    emptyMessage: 'Complete work items to see throughput',
    buildSummary: (s) => [
      metric('Total Completed', Number(s.total_completed ?? 0)),
      metric('Avg / Day', Number(s.average_per_day ?? 0), HiTrendingUp),
      metric('Days', Number(s.days ?? 0), HiClock),
    ],
  },
  {
    key: 'lead-time',
    title: 'Lead Time Report',
    subtitle: 'Time from creation to completion for work items',
    apiPath: 'lead-time',
    chartType: 'bar',
    emptyMessage: 'Complete work items to measure lead time',
    buildSummary: (s) => [
      metric('Average', `${s.average_days ?? 0} days`, HiClock),
      metric('Min', `${s.min_days ?? 0} days`),
      metric('Max', `${s.max_days ?? 0} days`),
      metric('Sample Size', Number(s.sample_size ?? 0)),
    ],
  },
  {
    key: 'cycle-time',
    title: 'Cycle Time Report',
    subtitle: 'Active work duration from start to completion',
    apiPath: 'cycle-time',
    chartType: 'bar',
    emptyMessage: 'Complete work items with start dates to measure cycle time',
    buildSummary: (s) => [
      metric('Average', `${s.average_days ?? 0} days`, HiClock),
      metric('Min', `${s.min_days ?? 0} days`),
      metric('Max', `${s.max_days ?? 0} days`),
      metric('Sample Size', Number(s.sample_size ?? 0)),
    ],
  },
  {
    key: 'sprint-health',
    title: 'Sprint Health Report',
    subtitle: 'Health scores across active and closed sprints',
    apiPath: 'sprint-health',
    chartType: 'line',
    emptyMessage: 'Create sprints to track sprint health',
    buildSummary: (s) => [
      metric('Active Sprint', String(s.active_sprint ?? 'None')),
      metric('Avg Score', Number(s.average_score ?? 0), HiChartBar),
      metric('At Risk', Number(s.at_risk_count ?? 0), HiExclamation, 'warning'),
      metric('Total Sprints', Number(s.total_sprints ?? 0), HiCollection),
    ],
  },
  {
    key: 'capacity-trend',
    title: 'Capacity Trend Report',
    subtitle: 'Team capacity vs assigned work across sprints',
    apiPath: 'capacity-trend',
    chartType: 'line',
    emptyMessage: 'Create sprints to see capacity trends',
    buildSummary: (s) => [
      metric('Sprints', Number(s.total_sprints ?? 0), HiCollection),
      metric('Total Capacity', `${s.total_capacity_md ?? 0} MD`),
      metric('Total Assigned', `${s.total_assigned_md ?? 0} MD`, HiChartBar),
    ],
  },
  {
    key: 'risk-trend',
    title: 'Risk Trend Report',
    subtitle: 'Open and critical risks across the project',
    apiPath: 'risk-trend',
    exportType: 'risk',
    chartType: 'doughnut',
    emptyMessage: 'Add risks to see risk trends',
    buildSummary: (s) => [
      metric('Total Risks', Number(s.total ?? 0), HiExclamation),
      metric('Open', Number(s.open ?? 0), HiExclamation, 'warning'),
      metric('Critical', Number(s.critical ?? 0), HiExclamation, 'error'),
      metric('Risk Score', Number(s.total_risk_score ?? 0)),
    ],
  },
  {
    key: 'dependency-trend',
    title: 'Dependency Trend Report',
    subtitle: 'Dependency types and blocking relationships',
    apiPath: 'dependency-trend',
    chartType: 'bar',
    emptyMessage: 'Create dependencies to see dependency trends',
    buildSummary: (s) => [
      metric('Total', Number(s.total_dependencies ?? 0), HiLink),
      metric('Blocking', Number(s.blocking_dependencies ?? 0), HiLink, 'error'),
      metric('Resolved', Number(s.resolved_dependencies ?? 0), HiLink, 'success'),
    ],
  },
  {
    key: 'work-distribution',
    title: 'Work Distribution Report',
    subtitle: 'How work is distributed across team members',
    apiPath: 'work-distribution',
    exportType: 'work_distribution',
    chartType: 'bar',
    emptyMessage: 'Assign work items to see distribution',
    buildSummary: (s) => [
      metric('Team Members', Number(s.total_assignees ?? 0), HiUserGroup),
      metric('Total Items', Number(s.total_items ?? 0), HiCollection),
    ],
  },
  {
    key: 'assignee-load',
    title: 'Assignee Load Report',
    subtitle: 'Capacity vs assigned man-days per team member',
    apiPath: 'assignee-load',
    chartType: 'bar',
    emptyMessage: 'Add sprint capacity allocations to see assignee load',
    supportsSprintFilter: true,
    buildSummary: (s) => [
      metric('Sprint', String(s.sprint_name ?? '—')),
      metric('Team Members', Number(s.team_members ?? 0), HiUserGroup),
      metric('Capacity', `${s.total_capacity_md ?? 0} MD`),
      metric('Assigned', `${s.total_assigned_md ?? 0} MD`, HiChartBar),
    ],
  },
  {
    key: 'epic-progress',
    title: 'Epic Progress Report',
    subtitle: 'Completion percentage for each epic',
    apiPath: 'epic-progress',
    exportType: 'epic',
    chartType: 'bar',
    emptyMessage: 'Create epics and link work items to see progress',
    buildSummary: (s) => [
      metric('Total Epics', Number(s.total_epics ?? 0), HiCollection),
      metric('Completed Epics', Number(s.completed_epics ?? 0)),
    ],
  },
  {
    key: 'release-progress',
    title: 'Release Progress Report',
    subtitle: 'Progress toward release milestones',
    apiPath: 'release-progress',
    chartType: 'bar',
    emptyMessage: 'Create releases and link work items to see progress',
    buildSummary: (s) => [
      metric('Total Releases', Number(s.total_releases ?? 0), HiCollection),
      metric('Completed', Number(s.completed_releases ?? 0)),
    ],
  },
];

export const REPORT_ROUTE_BY_KEY: Record<string, (id: string) => string> = {
  velocity: ROUTES.PROJECT_REPORT_VELOCITY,
  burndown: ROUTES.PROJECT_REPORT_BURNDOWN,
  burnup: ROUTES.PROJECT_REPORT_BURNUP,
  throughput: ROUTES.PROJECT_REPORT_THROUGHPUT,
  'lead-time': ROUTES.PROJECT_REPORT_LEAD_TIME,
  'cycle-time': ROUTES.PROJECT_REPORT_CYCLE_TIME,
  'sprint-health': ROUTES.PROJECT_REPORT_SPRINT_HEALTH,
  'capacity-trend': ROUTES.PROJECT_REPORT_CAPACITY_TREND,
  'risk-trend': ROUTES.PROJECT_REPORT_RISK_TREND,
  'dependency-trend': ROUTES.PROJECT_REPORT_DEPENDENCY_TREND,
  'work-distribution': ROUTES.PROJECT_REPORT_WORK_DISTRIBUTION,
  'assignee-load': ROUTES.PROJECT_REPORT_ASSIGNEE_LOAD,
  'epic-progress': ROUTES.PROJECT_REPORT_EPIC_PROGRESS,
  'release-progress': ROUTES.PROJECT_REPORT_RELEASE_PROGRESS,
};

export function getReportByKey(key: string): ReportDefinition | undefined {
  return ENTERPRISE_REPORTS.find((r) => r.key === key);
}
