import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:core_localization/core_localization.dart';

class CertificateCard extends StatelessWidget {
  final StaffDocument document;
  final VoidCallback? onUpload;
  final VoidCallback? onEditExpiry;
  final VoidCallback? onRemove;
  final VoidCallback? onView;

  const CertificateCard({
    super.key,
    required this.document,
    this.onUpload,
    this.onEditExpiry,
    this.onRemove,
    this.onView,
  });

  @override
  Widget build(BuildContext context) {
    // Determine UI state from document
    final bool isComplete = document.status == DocumentStatus.verified;
    // Todo: Better logic for expring. Assuming if expiryDate is close.
    // Prototype used 'EXPIRING' status. We map this logic:
    final bool isExpiring = _isExpiring(document.expiryDate);
    final bool isExpired = _isExpired(document.expiryDate);
    
    // Override isComplete if expiring or expired
    final bool showComplete = isComplete && !isExpired && !isExpiring;
    
    final bool isPending = document.status == DocumentStatus.pending;
    final bool isNotStarted = document.status == DocumentStatus.missing || document.status == DocumentStatus.rejected;

    // UI Properties helper
    final _CertificateUiProps uiProps = _getUiProps(document.documentId);

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: BorderRadius.circular(UiConstants.space4),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
        border: Border.all(color: UiColors.border),
      ),
      clipBehavior: Clip.hardEdge,
      child: Column(
        children: <Widget>[
          if (isExpiring || isExpired)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: const Color(0xFFF9E547).withOpacity(0.2), // Yellow tint
                border: const Border(
                  bottom: BorderSide(color: Color(0x66F9E547)),
                ),
              ),
              child: Row(
                children: <Widget>[
                   const Icon(
                    UiIcons.warning,
                    size: 16,
                    color: UiColors.textPrimary,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    isExpired
                        ? t.staff_certificates.card.expired
                        : t.staff_certificates.card.expires_in_days(days: _daysUntilExpiry(document.expiryDate)),
                    style: UiTypography.body3m.copyWith( // 12px Medium
                      color: UiColors.textPrimary,
                    ),
                  ),
                ],
              ),
            ),

          Padding(
            padding: const EdgeInsets.all(20),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Stack(
                  clipBehavior: Clip.none,
                  children: <Widget>[
                    Container(
                      width: 64,
                      height: 64,
                      decoration: BoxDecoration(
                        color: uiProps.color.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Center(
                        child: Icon(
                          uiProps.icon,
                          color: uiProps.color,
                          size: 28,
                        ),
                      ),
                    ),
                    if (showComplete)
                      const Positioned(
                        bottom: -4,
                        right: -4,
                        child: CircleAvatar(
                          radius: 12,
                          backgroundColor: UiColors.primary,
                          child: Icon(
                            UiIcons.success,
                            color: UiColors.white,
                            size: 16,
                          ),
                        ),
                      ),
                    if (isPending)
                      const Positioned(
                        bottom: -4,
                        right: -4,
                        child: CircleAvatar(
                          radius: 12,
                          backgroundColor: UiColors.textPrimary,
                          child: Icon(
                            UiIcons.clock,
                            color: UiColors.white,
                            size: 16,
                          ),
                        ),
                      ),
                  ],
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  document.name,
                                  style: UiTypography.body1m.copyWith( // 16px Medium
                                    color: UiColors.textPrimary,
                                  ),
                                ),
                                const SizedBox(height: 2),
                                Text(
                                  document.description ?? '', // Optional description
                                  style: UiTypography.body3r.copyWith( // 12px Regular
                                    color: UiColors.textSecondary,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const Icon(
                            UiIcons.chevronRight,
                            color: UiColors.textSecondary,
                            size: 20,
                          ),
                        ],
                      ),
                      const SizedBox(height: 16),

                      if (showComplete) _buildCompleteStatus(document.expiryDate),

                      if (isExpiring || isExpired) _buildExpiringStatus(context, document.expiryDate),

                      if (isNotStarted)
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: onUpload,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: UiColors.primary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              elevation: 0,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                const Icon(
                                  UiIcons.upload,
                                  size: 16,
                                  color: UiColors.white,
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  t.staff_certificates.card.upload_button,
                                  style: UiTypography.body2m.copyWith( // 14px Medium
                                    color: UiColors.white,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

                      if (showComplete || isExpiring || isExpired) ...<Widget>[
                        const SizedBox(height: 12),
                        SizedBox(
                          width: double.infinity,
                          child: OutlinedButton.icon(
                            onPressed: onEditExpiry,
                            icon: const Icon(UiIcons.edit, size: 16),
                            label: Text(t.staff_certificates.card.edit_expiry),
                            style: OutlinedButton.styleFrom(
                              foregroundColor: UiColors.textPrimary,
                              side: const BorderSide(color: UiColors.border),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              padding: const EdgeInsets.symmetric(vertical: 12),
                            ),
                          ),
                        ),
                        const SizedBox(height: 8),
                        SizedBox(
                          width: double.infinity,
                          child: TextButton.icon(
                            onPressed: onRemove,
                            icon: const Icon(UiIcons.delete, size: 16),
                            label: Text(t.staff_certificates.card.remove),
                            style: TextButton.styleFrom(
                              foregroundColor: UiColors.destructive,
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCompleteStatus(DateTime? expiryDate) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: 8,
              height: 8,
              decoration: const BoxDecoration(
                color: UiColors.primary,
                shape: BoxShape.circle,
              ),
            ),
            const SizedBox(width: 8),
            Text(
              t.staff_certificates.card.verified,
              style: UiTypography.body2m.copyWith(
                color: UiColors.primary,
              ),
            ),
          ],
        ),
        if (expiryDate != null)
          Text(
            t.staff_certificates.card.exp(date: DateFormat('MMM d, yyyy').format(expiryDate)),
            style: UiTypography.body3r.copyWith(color: UiColors.textSecondary),
          ),
      ],
    );
  }

  Widget _buildExpiringStatus(BuildContext context, DateTime? expiryDate) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  width: 8,
                  height: 8,
                  decoration: const BoxDecoration(
                    color: UiColors.primary,
                    shape: BoxShape.circle,
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  t.staff_certificates.card.expiring_soon,
                  style: UiTypography.body2m.copyWith(
                    color: UiColors.primary,
                  ),
                ),
              ],
            ),
            if (expiryDate != null)
              Padding(
                padding: const EdgeInsets.only(top: 4),
                child: Text(
                  t.staff_certificates.card.exp(date: DateFormat('MMM d, yyyy').format(expiryDate)),
                  style: UiTypography.body3r.copyWith(
                    color: UiColors.textSecondary,
                  ),
                ),
              ),
          ],
        ),
        Row(
          children: <Widget>[
            _buildIconButton(UiIcons.eye, onView),
            const SizedBox(width: 8),
            _buildSmallOutlineButton(
              t.staff_certificates.card.renew,
              onUpload,
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildIconButton(IconData icon, VoidCallback? onTap) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(16),
      child: Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.transparent,
          border: Border.all(
            color: Colors.transparent,
          ),
        ),
        child: Center(
          child: Icon(icon, size: 16, color: UiColors.textSecondary),
        ),
      ),
    );
  }

  Widget _buildSmallOutlineButton(String label, VoidCallback? onTap) {
    return OutlinedButton(
      onPressed: onTap,
      style: OutlinedButton.styleFrom(
        side: const BorderSide(color: Color(0x660A39DF)), // Primary with opacity
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
        minimumSize: const Size(0, 32),
      ),
      child: Text(
        label,
        style: UiTypography.body3m.copyWith(color: UiColors.primary),
      ),
    );
  }

  bool _isExpiring(DateTime? expiry) {
    if (expiry == null) return false;
    final int days = expiry.difference(DateTime.now()).inDays;
    return days >= 0 && days <= 30; // Close to expiry but not expired
  }

  bool _isExpired(DateTime? expiry) {
    if (expiry == null) return false;
    return expiry.difference(DateTime.now()).inDays < 0;
  }

  int _daysUntilExpiry(DateTime? expiry) {
    if (expiry == null) return 0;
    return expiry.difference(DateTime.now()).inDays;
  }

  // Mock mapping for UI props based on ID
  _CertificateUiProps _getUiProps(String id) {
    switch (id) {
      case 'background':
        return _CertificateUiProps(UiIcons.fileCheck, const Color(0xFF0A39DF));
      case 'food_handler':
        return _CertificateUiProps(UiIcons.utensils, const Color(0xFF0A39DF));
      case 'rbs':
        return _CertificateUiProps(UiIcons.wine, const Color(0xFF121826));
      default:
        // Default generic icon
        return _CertificateUiProps(UiIcons.award, UiColors.primary);
    }
  }
}

class _CertificateUiProps {
  final IconData icon;
  final Color color;
  _CertificateUiProps(this.icon, this.color);
}
