import 'package:flutter/material.dart';
import 'package:em2rp/models/maintenance_model.dart';
import 'package:intl/intl.dart';
import 'package:em2rp/utils/colors.dart';

/// Widget pour afficher l'historique des maintenances
class EquipmentMaintenanceHistorySection extends StatelessWidget {
  final List<MaintenanceModel> maintenances;
  final bool isLoading;
  final bool hasManagePermission;
  final VoidCallback? onAddMaintenance;

  const EquipmentMaintenanceHistorySection({
    super.key,
    required this.maintenances,
    required this.isLoading,
    required this.hasManagePermission,
    this.onAddMaintenance,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.build, color: AppColors.rouge),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Historique des maintenances',
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                ),
                if (hasManagePermission && onAddMaintenance != null)
                  IconButton(
                    icon: const Icon(Icons.add_circle, color: AppColors.bleuFonce),
                    tooltip: 'Planifier une maintenance',
                    onPressed: onAddMaintenance,
                  ),
              ],
            ),
            const Divider(height: 24),
            if (isLoading)
              const Center(child: CircularProgressIndicator())
            else if (maintenances.isEmpty)
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    const Center(
                      child: Text(
                        'Aucune maintenance enregistrée',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                    if (hasManagePermission && onAddMaintenance != null) ...[
                      const SizedBox(height: 16),
                      Center(
                        child: ElevatedButton.icon(
                          onPressed: onAddMaintenance,
                          icon: const Icon(Icons.add),
                          label: const Text('Planifier une maintenance'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.bleuFonce,
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
              )
            else
              ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: maintenances.length,
                separatorBuilder: (context, index) => const Divider(),
                itemBuilder: (context, index) {
                  return _buildMaintenanceItem(maintenances[index], hasManagePermission);
                },
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildMaintenanceItem(MaintenanceModel maintenance, bool showCost) {
    final isCompleted = maintenance.completedDate != null;
    final typeInfo = _getMaintenanceTypeInfo(maintenance.type);

    return ListTile(
      contentPadding: const EdgeInsets.symmetric(vertical: 8),
      leading: CircleAvatar(
        backgroundColor: isCompleted ? Colors.green.withValues(alpha: 0.2) : Colors.orange.withValues(alpha: 0.2),
        child: Icon(
          isCompleted ? Icons.check_circle : Icons.schedule,
          color: isCompleted ? Colors.green : Colors.orange,
        ),
      ),
      title: Text(
        maintenance.name,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 4),
          Row(
            children: [
              Icon(typeInfo.$2, size: 16, color: Colors.grey[600]),
              const SizedBox(width: 4),
              Text(typeInfo.$1, style: TextStyle(color: Colors.grey[600], fontSize: 12)),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            isCompleted
                ? 'Effectuée le ${DateFormat('dd/MM/yyyy').format(maintenance.completedDate!)}'
                : 'Planifiée le ${DateFormat('dd/MM/yyyy').format(maintenance.scheduledDate)}',
            style: TextStyle(fontSize: 12, color: Colors.grey[700]),
          ),
          if (showCost && maintenance.cost != null) ...[
            const SizedBox(height: 4),
            Text(
              'Coût: ${maintenance.cost!.toStringAsFixed(2)} €',
              style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
            ),
          ],
        ],
      ),
    );
  }

  (String, IconData) _getMaintenanceTypeInfo(MaintenanceType type) {
    switch (type) {
      case MaintenanceType.preventive:
        return ('Préventive', Icons.schedule);
      case MaintenanceType.corrective:
        return ('Corrective', Icons.build);
      case MaintenanceType.inspection:
        return ('Inspection', Icons.search);
    }
  }
}

