using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Haoliang.Core.Services;
using Haoliang.Models.Models.System;
using Haoliang.Models.Models.Production;
using Haoliang.Models.Models.Template;
using Haoliang.Models.Common;

namespace Haoliang.Api.Controllers
{
    [Route("api/v1/config")]
    [ApiController]
    public class ConfigController : ControllerBase
    {
        private readonly ISystemConfigService _systemService;
        private readonly ITemplateService _templateService;
        private readonly IRulesService _rulesService;
        private readonly IProductionStatisticsService _statisticsService;

        public ConfigController(
            ISystemConfigService systemService,
            ITemplateService templateService,
            IRulesService rulesService,
            IProductionStatisticsService statisticsService)
        {
            _systemService = systemService;
            _templateService = templateService;
            _rulesService = rulesService;
            _statisticsService = statisticsService;
        }

        /// <summary>
        /// Get all system configuration
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<ApiResponse<SystemConfiguration>>> GetSystemConfiguration()
        {
            try
            {
                var config = await _systemService.GetSystemConfigurationAsync();
                return Ok(ApiResponse<SystemConfiguration>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<SystemConfiguration>.InternalServerError($"Error getting system configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update system configuration
        /// </summary>
        [HttpPut]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateSystemConfiguration([FromBody] SystemConfiguration configuration)
        {
            try
            {
                var result = await _systemService.UpdateSystemConfigurationAsync(configuration);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating system configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get production target configuration
        /// </summary>
        [HttpGet("production-targets")]
        public async Task<ActionResult<ApiResponse<List<ProductionTargetConfig>>>> GetProductionTargets()
        {
            try
            {
                var targets = await _systemService.GetProductionTargetsAsync();
                return Ok(ApiResponse<List<ProductionTargetConfig>>.Success(targets));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<List<ProductionTargetConfig>>.InternalServerError($"Error getting production targets: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update production targets
        /// </summary>
        [HttpPut("production-targets")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateProductionTargets([FromBody] List<ProductionTargetConfig> targets)
        {
            try
            {
                var result = await _systemService.UpdateProductionTargetsAsync(targets);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating production targets: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get working hours configuration
        /// </summary>
        [HttpGet("working-hours")]
        public async Task<ActionResult<ApiResponse<WorkingHoursConfig>>> GetWorkingHoursConfig()
        {
            try
            {
                var config = await _systemService.GetWorkingHoursConfigAsync();
                return Ok(ApiResponse<WorkingHoursConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<WorkingHoursConfig>.InternalServerError($"Error getting working hours config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update working hours configuration
        /// </summary>
        [HttpPut("working-hours")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateWorkingHoursConfig([FromBody] WorkingHoursConfig config)
        {
            try
            {
                var result = await _systemService.UpdateWorkingHoursConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating working hours config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get alert configuration
        /// </summary>
        [HttpGet("alerts")]
        public async Task<ActionResult<ApiResponse<AlertConfiguration>>> GetAlertConfiguration()
        {
            try
            {
                var config = await _systemService.GetAlertConfigurationAsync();
                return Ok(ApiResponse<AlertConfiguration>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<AlertConfiguration>.InternalServerError($"Error getting alert configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update alert configuration
        /// </summary>
        [HttpPut("alerts")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateAlertConfiguration([FromBody] AlertConfiguration config)
        {
            try
            {
                var result = await _systemService.UpdateAlertConfigurationAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating alert configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get business rules configuration
        /// </summary>
        [HttpGet("rules")]
        public async Task<ActionResult<ApiResponse<List<BusinessRuleConfig>>>> GetBusinessRules()
        {
            try
            {
                var rules = await _rulesService.GetAllRulesAsync();
                return Ok(ApiResponse<List<BusinessRuleConfig>>.Success(rules));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<List<BusinessRuleConfig>>.InternalServerError($"Error getting business rules: {ex.Message}"));
            }
        }

        /// <summary>
        /// Create or update business rule
        /// </summary>
        [HttpPost("rules")]
        public async Task<ActionResult<ApiResponse<BusinessRuleConfig>>> CreateOrUpdateBusinessRule([FromBody] BusinessRuleConfig rule)
        {
            try
            {
                var result = await _rulesService.CreateOrUpdateRuleAsync(rule);
                return Ok(ApiResponse<BusinessRuleConfig>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<BusinessRuleConfig>.InternalServerError($"Error creating/updating business rule: {ex.Message}"));
            }
        }

        /// <summary>
        /// Delete business rule
        /// </summary>
        [HttpDelete("rules/{ruleId}")]
        public async Task<ActionResult<ApiResponse<bool>>> DeleteBusinessRule(int ruleId)
        {
            try
            {
                var result = await _rulesService.DeleteRuleAsync(ruleId);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error deleting business rule: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get statistical analysis rules
        /// </summary>
        [HttpGet("statistics-rules")]
        public async Task<ActionResult<ApiResponse<List<StatisticsRuleConfig>>>> GetStatisticsRules()
        {
            try
            {
                var rules = await _rulesService.GetStatisticsRulesAsync();
                return Ok(ApiResponse<List<StatisticsRuleConfig>>.Success(rules));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<List<StatisticsRuleConfig>>.InternalServerError($"Error getting statistics rules: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update statistics rules
        /// </summary>
        [HttpPut("statistics-rules")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateStatisticsRules([FromBody] List<StatisticsRuleConfig> rules)
        {
            try
            {
                var result = await _rulesService.UpdateStatisticsRulesAsync(rules);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating statistics rules: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get data retention configuration
        /// </summary>
        [HttpGet("data-retention")]
        public async Task<ActionResult<ApiResponse<DataRetentionConfig>>> GetDataRetentionConfig()
        {
            try
            {
                var config = await _systemService.GetDataRetentionConfigAsync();
                return Ok(ApiResponse<DataRetentionConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<DataRetentionConfig>.InternalServerError($"Error getting data retention config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update data retention configuration
        /// </summary>
        [HttpPut("data-retention")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateDataRetentionConfig([FromBody] DataRetentionConfig config)
        {
            try
            {
                var result = await _systemService.UpdateDataRetentionConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating data retention config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get dashboard configuration
        /// </summary>
        [HttpGet("dashboard")]
        public async Task<ActionResult<ApiResponse<DashboardConfig>>> GetDashboardConfig()
        {
            try
            {
                var config = await _systemService.GetDashboardConfigAsync();
                return Ok(ApiResponse<DashboardConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<DashboardConfig>.InternalServerError($"Error getting dashboard config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update dashboard configuration
        /// </summary>
        [HttpPut("dashboard")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateDashboardConfig([FromBody] DashboardConfig config)
        {
            try
            {
                var result = await _systemService.UpdateDashboardConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating dashboard config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get export configuration
        /// </summary>
        [HttpGet("export")]
        public async Task<ActionResult<ApiResponse<ExportConfig>>> GetExportConfig()
        {
            try
            {
                var config = await _systemService.GetExportConfigAsync();
                return Ok(ApiResponse<ExportConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<ExportConfig>.InternalServerError($"Error getting export config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update export configuration
        /// </summary>
        [HttpPut("export")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateExportConfig([FromBody] ExportConfig config)
        {
            try
            {
                var result = await _systemService.UpdateExportConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating export config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get collection configuration
        /// </summary>
        [HttpGet("collection")]
        public async Task<ActionResult<ApiResponse<CollectionConfig>>> GetCollectionConfig()
        {
            try
            {
                var config = await _systemService.GetCollectionConfigAsync();
                return Ok(ApiResponse<CollectionConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<CollectionConfig>.InternalServerError($"Error getting collection config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update collection configuration
        /// </summary>
        [HttpPut("collection")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateCollectionConfig([FromBody] CollectionConfig config)
        {
            try
            {
                var result = await _systemService.UpdateCollectionConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating collection config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get notification configuration
        /// </summary>
        [HttpGet("notifications")]
        public async Task<ActionResult<ApiResponse<NotificationConfig>>> GetNotificationConfig()
        {
            try
            {
                var config = await _systemService.GetNotificationConfigAsync();
                return Ok(ApiResponse<NotificationConfig>.Success(config));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<NotificationConfig>.InternalServerError($"Error getting notification config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Update notification configuration
        /// </summary>
        [HttpPut("notifications")]
        public async Task<ActionResult<ApiResponse<bool>>> UpdateNotificationConfig([FromBody] NotificationConfig config)
        {
            try
            {
                var result = await _systemService.UpdateNotificationConfigAsync(config);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error updating notification config: {ex.Message}"));
            }
        }

        /// <summary>
        /// Validate configuration
        /// </summary>
        [HttpPost("validate")]
        public async Task<ActionResult<ApiResponse<ValidationResult>>> ValidateConfiguration([FromBody] object configuration)
        {
            try
            {
                var result = await _systemService.ValidateConfigurationAsync(configuration);
                return Ok(ApiResponse<ValidationResult>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<ValidationResult>.InternalServerError($"Error validating configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Export configuration
        /// </summary>
        [HttpGet("export")]
        public async Task<ActionResult<FileContentResult>> ExportConfiguration()
        {
            try
            {
                var config = await _systemService.GetSystemConfigurationAsync();
                var json = System.Text.Json.JsonSerializer.Serialize(config, new System.Text.Json.JsonSerializerOptions
                {
                    WriteIndented = true
                });
                
                return File(System.Text.Encoding.UTF8.GetBytes(json), "application/json", "system-configuration.json");
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = $"Error exporting configuration: {ex.Message}" });
            }
        }

        /// <summary>
        /// Import configuration
        /// </summary>
        [HttpPost("import")]
        public async Task<ActionResult<ApiResponse<bool>>> ImportConfiguration([FromBody] SystemConfiguration configuration)
        {
            try
            {
                var result = await _systemService.ImportConfigurationAsync(configuration);
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error importing configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Reset to default configuration
        /// </summary>
        [HttpPost("reset")]
        public async Task<ActionResult<ApiResponse<bool>>> ResetToDefault()
        {
            try
            {
                var result = await _systemService.ResetToDefaultConfigurationAsync();
                return Ok(ApiResponse<bool>.Success(result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.InternalServerError($"Error resetting configuration: {ex.Message}"));
            }
        }

        /// <summary>
        /// Get configuration change history
        /// </summary>
        [HttpGet("history")]
        public async Task<ActionResult<ApiResponse<List<ConfigurationChange>>>> GetConfigurationHistory([FromQuery] DateTime? startDate = null, [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var history = await _systemService.GetConfigurationChangeHistoryAsync(startDate, endDate);
                return Ok(ApiResponse<List<ConfigurationChange>>.Success(history));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<List<ConfigurationChange>>.InternalServerError($"Error getting configuration history: {ex.Message}"));
            }
        }
    }
}