using esoft.Class;
using esoft.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace esoft.Pages
{
    public partial class AddEditServicePage : Page
    {
        ActualContext actualContext = new ActualContext();
        List<TaskFill> taskContext = new List<TaskFill>();
        private TaskFill selectedTask;
        private bool isEditing = false;

        public AddEditServicePage(TaskFill task)
        {
            InitializeComponent();
            selectedTask = task;
            if (selectedTask.Title != null)
            {
                isEditing = true;
            }
            FillForm();
            LoadUserRule();
        }

        private void FillForm()
        {
            cbStatus.ItemsSource = StatusTask.FillStatus();
            DPickerDateCreate.SelectedDate = DateTime.Today;

            if (isEditing && selectedTask != null)
            {
                TBoxTitle.Text = selectedTask.Title;
                cbExecutor.SelectedItem = selectedTask.FioUser;
                cbManager.SelectedItem = selectedTask.FioManager;
                if (cbStatus.ItemsSource is IEnumerable<StatusTask> statusList)
                {
                    cbStatus.SelectedItem = statusList.FirstOrDefault(status => status.Name == selectedTask.Status);
                }
                IUDComplexityTask.Value = (int)selectedTask.Difficulty;
                IUDTimeTask.Value = selectedTask.Time;
                cbNatureTask.Text = selectedTask.WorkType;
                TBoxDescription.Text = selectedTask.Description;
                DPickerDateCreate.SelectedDate = selectedTask.CreateDateTime;
                DPickerDateDeadLine.SelectedDate = selectedTask.Deadline;
                DPickerDateCompleted.SelectedDate = selectedTask.CompletedDateTime;
            }

            var usersExecutor = actualContext.Users.Where(user => actualContext.Executor.Any(ex => ex.ID == user.ID)).ToList();
            cbExecutor.ItemsSource = UserInFIO.GroupUser(usersExecutor);

            var usersManager = actualContext.Users.Where(user => actualContext.Manager.Any(manager => manager.ID == user.ID)).ToList();
            cbManager.ItemsSource = UserInFIO.GroupUser(usersManager);
        }

        private void LoadUserRule()
        {
            taskContext = Class.TaskFill.TaskFills();

            var currentUser = GetCurrent.CurrentUser; // Получаем текущего пользователя
            var isManager = actualContext.Manager.Any(manager => manager.ID == currentUser.ID);

            // Проверка роли пользователя
            if (isManager)
            {
                cbExecutor.IsEnabled = true;
                cbManager.IsEnabled = true;
            }
            else
            {
                cbExecutor.IsEnabled = false;
                cbManager.IsEnabled = false;
            }
        }

        private void BtnSaveTask_Click(object sender, RoutedEventArgs e)
        {
            string title = TBoxTitle.Text;
            string executorName = cbExecutor.SelectedItem?.ToString();
            string managerName = cbManager.SelectedItem?.ToString();
            string status = cbStatus.Text;
            int complexity = (int)IUDComplexityTask.Value;
            int time = (int)IUDTimeTask.Value;
            string nature = cbNatureTask.Text;
            string description = TBoxDescription.Text;
            DateTime createDate = DPickerDateCreate.SelectedDate ?? DateTime.Now;
            DateTime deadline = DPickerDateDeadLine.SelectedDate ?? DateTime.Now;

            if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(executorName) || string.IsNullOrWhiteSpace(managerName) || string.IsNullOrWhiteSpace(status))
            {
                MessageBox.Show("Пожалуйста, заполните все обязательные поля!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                var context = esoftEntities.GetContext();
                var executorID = actualContext.Users.FirstOrDefault(u => UserInFIO.SoloUser(u) == executorName)?.ID;
                var managerID = actualContext.Users.FirstOrDefault(u => UserInFIO.SoloUser(u) == managerName)?.ID;

                if (executorID == null || managerID == null)
                {
                    MessageBox.Show("Исполнитель или менеджер не найден!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (isEditing)
                {
                    var existingTask = context.Task.FirstOrDefault(t => t.ID == selectedTask.ID);

                    if (existingTask != null)
                    {
                        existingTask.Title = title;
                        existingTask.ExecutorID = executorID.Value;
                        existingTask.Status = status;
                        existingTask.Difficulty = complexity;
                        existingTask.Time = time;
                        existingTask.WorkType = nature;
                        existingTask.Description = description;
                        existingTask.CreateDateTime = createDate;
                        existingTask.Deadline = deadline.Date;

                        if (status == "выполнена")
                        {
                            existingTask.CompletedDateTime = DateTime.Today;
                        }
                        else
                        {
                            existingTask.CompletedDateTime = null;
                        }

                        context.SaveChanges();

                        MessageBoxResult result = MessageBox.Show("Задача успешно изменена!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                        if (result == MessageBoxResult.OK)
                        {
                            NavigationService.GoBack();
                        }
                    }
                }
                else // Добавление новой задачи
                {
                    esoft.Entities.Task newTask = new esoft.Entities.Task
                    {
                        Title = title,
                        ExecutorID = executorID.Value,
                        Status = status,
                        Difficulty = complexity,
                        Time = time,
                        WorkType = nature,
                        Description = description,
                        CreateDateTime = DateTime.Today,
                        Deadline = deadline.Date,
                    };

                    context.Task.Add(newTask);
                    context.SaveChanges();

                    MessageBoxResult result = MessageBox.Show("Задача успешно добавлена!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                    if (result == MessageBoxResult.OK)
                    {
                        NavigationService.GoBack();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка при обработке задачи: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
