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

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

/// 결재 감사 로그를 표 형태로 렌더링하는 위젯.
class ApprovalAuditLogTable extends StatelessWidget {
  const ApprovalAuditLogTable({
    super.key,
    required this.logs,
    required this.dateFormat,
    this.pagination,
    this.onPageChange,
    this.onPageSizeChange,
    this.isLoading = false,
  });

  /// 감사 로그 목록.
  final List<ApprovalHistory> logs;

  /// 날짜 포맷터.
  final DateFormat dateFormat;

  /// 페이지네이션 상태.
  final SuperportTablePagination? pagination;

  /// 페이지 변경 콜백.
  final ValueChanged<int>? onPageChange;

  /// 페이지 크기 변경 콜백.
  final ValueChanged<int>? onPageSizeChange;

  /// 로딩 여부.
  final bool isLoading;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    if (logs.isEmpty) {
      return Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 32),
        decoration: BoxDecoration(
          color: theme.colorScheme.secondary.withValues(alpha: 0.05),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: theme.colorScheme.border),
        ),
        child: Center(
          child: Text('선택한 결재의 감사 로그가 없습니다.', style: theme.textTheme.muted),
        ),
      );
    }

    return SuperportTable(
      columns: const [
        Text('행위'),
        Text('변경 상태'),
        Text('승인자'),
        Text('메모'),
        Text('일시'),
      ],
      rows: logs.map((log) {
        final statusLabel = _buildStatusLabel(log);
        final timestamp = dateFormat.format(log.actionAt.toLocal());
        return [
          ShadBadge.outline(child: Text(log.action.name)),
          ApprovalStatusBadge(label: statusLabel, colorHex: log.toStatus.color),
          ApprovalApproverCell(
            name: log.approver.name,
            employeeNo: log.approver.employeeNo,
          ),
          ApprovalNoteTooltip(note: log.note),
          Text(timestamp),
        ];
      }).toList(),
      rowHeight: 68,
      maxHeight: 420,
      columnSpanExtent: (index) {
        switch (index) {
          case 0:
            return const FixedTableSpanExtent(120);
          case 2:
            return const FixedTableSpanExtent(220);
          case 3:
            return const FixedTableSpanExtent(220);
          case 4:
            return const FixedTableSpanExtent(160);
          default:
            return const FixedTableSpanExtent(140);
        }
      },
      pagination: pagination,
      onPageChange: onPageChange,
      onPageSizeChange: onPageSizeChange,
      isLoading: isLoading,
    );
  }

  String _buildStatusLabel(ApprovalHistory log) {
    final from = log.fromStatus?.name ?? '시작';
    final to = log.toStatus.name;
    return '$from → $to';
  }
}
