using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TodoList.Models;

namespace TodoList.Services
{
    public class FileDataService : IDataService
    {
        private readonly string _filePath;

        public FileDataService()
        {
            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var folder = Path.Combine(appData, "TodoListApp");
            Directory.CreateDirectory(folder);
            _filePath = Path.Combine(folder, "tasks.json");
        }

        public async Task<List<TodoItem>> LoadTasksAsync(bool? completed = null)
        {
            if (!File.Exists(_filePath))
            {
                return new List<TodoItem>();
            }

            try
            {
                using var stream = File.OpenRead(_filePath);
                var items = await JsonSerializer.DeserializeAsync<List<TodoItem>>(stream);
                var tasks = items ?? new List<TodoItem>();
                
                if (completed.HasValue)
                {
                    return tasks.Where(t => t.IsCompleted == completed.Value).ToList();
                }
                return tasks;
            }
            catch
            {
                return new List<TodoItem>();
            }
        }

        public async Task<TodoItem> SaveTaskAsync(TodoItem task)
        {
            var tasks = await LoadTasksAsync();
            var existing = tasks.Find(t => t.Id == task.Id);
            if (existing != null)
            {
                tasks.Remove(existing);
            }
            tasks.Add(task);
            await SaveAllAsync(tasks);
            return task;
        }

        public async Task<TodoItem> UpdateTaskAsync(TodoItem task)
        {
            var tasks = await LoadTasksAsync();
            var existing = tasks.Find(t => t.Id == task.Id);
            if (existing != null)
            {
                tasks.Remove(existing);
                tasks.Add(task);
                await SaveAllAsync(tasks);
            }
            return task;
        }

        public async Task<TodoItem> ToggleCompleteAsync(string id)
        {
            var tasks = await LoadTasksAsync();
            var task = tasks.Find(t => t.Id == id);
            if (task != null)
            {
                task.IsCompleted = !task.IsCompleted;
                task.CompletedAt = task.IsCompleted ? DateTime.Now : null;
                task.SyncStatus = SyncStatus.Pending;
                await SaveAllAsync(tasks);
            }
            return task;
        }

        public async Task SaveAllAsync(List<TodoItem> tasks)
        {
            using var stream = File.Create(_filePath);
            await JsonSerializer.SerializeAsync(stream, tasks, new JsonSerializerOptions { WriteIndented = true });
        }

        public async Task DeleteTaskAsync(string id)
        {
            var tasks = await LoadTasksAsync();
            var existing = tasks.Find(t => t.Id == id);
            if (existing != null)
            {
                tasks.Remove(existing);
                await SaveAllAsync(tasks);
            }
        }
    }
}
