import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

import '../../../../approvals/domain/entities/approval.dart';
import '../../../../approvals/domain/entities/approval_flow.dart';
import '../../../shared/widgets/approval_ui_helpers.dart';

/// 결재 흐름의 상태 변화를 타임라인으로 표현하는 위젯.
class ApprovalFlowTimeline extends StatelessWidget {
  const ApprovalFlowTimeline({
    super.key,
    required this.flow,
    required this.dateFormat,
  });

  /// 표시할 결재 흐름.
  final ApprovalFlow flow;

  /// 일시 포맷터.
  final DateFormat dateFormat;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final histories = List<ApprovalHistory>.from(flow.histories)
      ..sort((a, b) => a.actionAt.compareTo(b.actionAt));
    final summary = flow.statusSummary;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSummary(theme, summary),
        const SizedBox(height: 16),
        if (histories.isEmpty)
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 20),
            decoration: BoxDecoration(
              color: theme.colorScheme.secondary.withValues(alpha: 0.06),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text('결재 상태 변경 이력이 없습니다.', style: theme.textTheme.muted),
          )
        else
          Column(
            children: [
              for (var index = 0; index < histories.length; index++)
                _TimelineEntry(
                  history: histories[index],
                  isFirst: index == 0,
                  isLast: index == histories.length - 1,
                  dateFormat: dateFormat,
                ),
            ],
          ),
      ],
    );
  }

  Widget _buildSummary(ShadThemeData theme, ApprovalFlowStatusSummary summary) {
    final requester = flow.requester;
    final finalApprover = flow.finalApprover;
    final status = flow.status;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            ApprovalStatusBadge(label: status.name, colorHex: status.color),
            const SizedBox(width: 12),
            Text(
              '총 ${summary.totalSteps}단계 · 완료 ${summary.completedSteps} · 대기 ${summary.pendingSteps}',
              style: theme.textTheme.small,
            ),
          ],
        ),
        const SizedBox(height: 12),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '상신자',
              style: theme.textTheme.small.copyWith(
                color: theme.colorScheme.mutedForeground,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              '${requester.name} (${requester.employeeNo})',
              style: theme.textTheme.p,
            ),
            if (finalApprover != null) ...[
              const SizedBox(height: 12),
              Text(
                '최종 승인자',
                style: theme.textTheme.small.copyWith(
                  color: theme.colorScheme.mutedForeground,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                '${finalApprover.name} (${finalApprover.employeeNo})',
                style: theme.textTheme.p,
              ),
            ],
            const SizedBox(height: 12),
            Text(
              '결재번호 ${flow.approvalNo}',
              style: theme.textTheme.small.copyWith(
                color: theme.colorScheme.mutedForeground,
              ),
            ),
          ],
        ),
      ],
    );
  }
}

class _TimelineEntry extends StatelessWidget {
  const _TimelineEntry({
    required this.history,
    required this.isFirst,
    required this.isLast,
    required this.dateFormat,
  });

  final ApprovalHistory history;
  final bool isFirst;
  final bool isLast;
  final DateFormat dateFormat;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final fromStatus = history.fromStatus?.name ?? '시작';
    final toStatus = history.toStatus.name;
    final timestamp = dateFormat.format(history.actionAt.toLocal());

    return Padding(
      padding: EdgeInsets.only(top: isFirst ? 0 : 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTimelineIndicator(theme),
          const SizedBox(width: 12),
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              decoration: BoxDecoration(
                color: theme.colorScheme.secondary.withValues(alpha: 0.05),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: theme.colorScheme.border),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        history.action.name,
                        style: theme.textTheme.small.copyWith(
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      Text(timestamp, style: theme.textTheme.muted),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Text('$fromStatus → $toStatus', style: theme.textTheme.small),
                  const SizedBox(height: 12),
                  ApprovalApproverCell(
                    name: history.approver.name,
                    employeeNo: history.approver.employeeNo,
                  ),
                  if (history.note?.trim().isNotEmpty == true) ...[
                    const SizedBox(height: 12),
                    ApprovalNoteTooltip(note: history.note),
                  ],
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTimelineIndicator(ShadThemeData theme) {
    final primary = theme.colorScheme.primary;
    return SizedBox(
      width: 20,
      child: Column(
        children: [
          Container(
            width: 12,
            height: 12,
            decoration: BoxDecoration(
              color: primary,
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          if (!isLast)
            Container(
              width: 2,
              height: 40,
              margin: const EdgeInsets.only(top: 4),
              decoration: BoxDecoration(color: primary.withValues(alpha: 0.4)),
            ),
        ],
      ),
    );
  }
}
