using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dealer
{
    public class DataManager
    {
        private List<Vehicle> vehicles = new List<Vehicle>();
        private List<Owner> owners = new List<Owner>();
        private List<Image> images = new List<Image>();

        // Vehicle CRUD
        public void AddVehicle(Vehicle vehicle)
        {
            vehicles.Add(vehicle);
        }

        public IEnumerable<Vehicle> GetAllVehicles()
        {
            return vehicles;
        }

        public void RemoveVehicle(Vehicle vehicle)
        {
            vehicles.Remove(vehicle);
        }

        // Owner CRUD
        public void AddOwner(Owner owner)
        {
            owners.Add(owner);
        }

        public IEnumerable<Owner> GetAllOwners()
        {
            return owners;
        }

        public Owner? GetOwnerById(Guid? id)
        {
            if (id == null) return null;
            return owners.FirstOrDefault(o => o.Id == id);
        }

        public void RemoveOwner(Owner owner)
        {
            // Remove owner reference from all vehicles
            foreach (var vehicle in vehicles.Where(v => v.VlastnikId == owner.Id))
            {
                vehicle.VlastnikId = null;
                vehicle.Vlastnik = null;
            }
            owners.Remove(owner);
        }

        public IEnumerable<Owner> SearchOwners(string searchText)
        {
            if (string.IsNullOrWhiteSpace(searchText))
                return owners;

            searchText = searchText.ToLower();
            return owners.Where(o =>
                (o.Jmeno?.ToLower().Contains(searchText) ?? false) ||
                (o.Prijmeni?.ToLower().Contains(searchText) ?? false) ||
                (o.Email?.ToLower().Contains(searchText) ?? false) ||
                (o.Telefon?.Contains(searchText) ?? false) ||
                (o.CeleJmeno?.ToLower().Contains(searchText) ?? false));
        }

        // Image CRUD
        public void AddImage(Image image)
        {
            images.Add(image);
        }

        public IEnumerable<Image> GetAllImages()
        {
            return images;
        }

        public Image? GetImageById(Guid? id)
        {
            if (id == null) return null;
            return images.FirstOrDefault(i => i.Id == id);
        }

        public void RemoveImage(Image image)
        {
            // Remove image reference from all vehicles
            foreach (var vehicle in vehicles.Where(v => v.FotografieId == image.Id))
            {
                vehicle.FotografieId = null;
                vehicle.Fotografie = null;
            }
            images.Remove(image);
        }

        // Link owners and images to vehicles after loading
        private void LinkRelationsToVehicles()
        {
            foreach (var vehicle in vehicles)
            {
                if (vehicle.VlastnikId.HasValue)
                {
                    vehicle.Vlastnik = GetOwnerById(vehicle.VlastnikId);
                }
                if (vehicle.FotografieId.HasValue)
                {
                    vehicle.Fotografie = GetImageById(vehicle.FotografieId);
                }
            }
        }

        public void Save()
        {
            // Save vehicles
            var vehiclesJson = System.Text.Json.JsonSerializer.Serialize(vehicles);
            System.IO.File.WriteAllText("vehicles.json", vehiclesJson);

            // Save owners
            var ownersJson = System.Text.Json.JsonSerializer.Serialize(owners);
            System.IO.File.WriteAllText("owners.json", ownersJson);

            // Save images
            var imagesJson = System.Text.Json.JsonSerializer.Serialize(images);
            System.IO.File.WriteAllText("images.json", imagesJson);
        }

        public void Load()
        {
            // Load owners first
            string ownersPath = "owners.json";
            if (System.IO.File.Exists(ownersPath))
            {
                var json = System.IO.File.ReadAllText(ownersPath);
                owners = System.Text.Json.JsonSerializer.Deserialize<List<Owner>>(json) ?? new List<Owner>();
            }

            // Load images
            string imagesPath = "images.json";
            if (System.IO.File.Exists(imagesPath))
            {
                var json = System.IO.File.ReadAllText(imagesPath);
                images = System.Text.Json.JsonSerializer.Deserialize<List<Image>>(json) ?? new List<Image>();
            }

            // Load vehicles
            string vehiclesPath = "vehicles.json";
            if (System.IO.File.Exists(vehiclesPath))
            {
                var json = System.IO.File.ReadAllText(vehiclesPath);
                vehicles = System.Text.Json.JsonSerializer.Deserialize<List<Vehicle>>(json) ?? new List<Vehicle>();
            }

            // Link relations to vehicles
            LinkRelationsToVehicles();

            // If no data exists, seed with sample data
            if (!vehicles.Any() && !owners.Any())
            {
                SeedData();
            }
        }

        private void SeedData()
        {
            // Seed owners
            var owner1 = new Owner
            {
                Id = Guid.NewGuid(),
                Jmeno = "Jan",
                Prijmeni = "Novak",
                Adresa = "Praha 1, Vaclavske namesti 1",
                Telefon = "+420 123 456 789",
                Email = "jan.novak@email.cz"
            };

            var owner2 = new Owner
            {
                Id = Guid.NewGuid(),
                Jmeno = "Marie",
                Prijmeni = "Svobodova",
                Adresa = "Brno, Husova 23",
                Telefon = "+420 987 654 321",
                Email = "marie.svobodova@email.cz"
            };

            var owner3 = new Owner
            {
                Id = Guid.NewGuid(),
                Jmeno = "Petr",
                Prijmeni = "Dvorak",
                Adresa = "Ostrava, Hlavni 45",
                Telefon = "+420 777 888 999",
                Email = "petr.dvorak@email.cz"
            };

            owners.Add(owner1);
            owners.Add(owner2);
            owners.Add(owner3);

            // Seed images (1x1 pixel placeholder images in different colors)
            var image1 = new Image
            {
                Id = Guid.NewGuid(),
                Data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPj/HwADBwIAMCbHYQAAAABJRU5ErkJggg==",
                FileName = "skoda_octavia.png",
                ContentType = "image/png"
            };

            var image2 = new Image
            {
                Id = Guid.NewGuid(),
                Data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg==",
                FileName = "bmw_x5.png",
                ContentType = "image/png"
            };

            var image3 = new Image
            {
                Id = Guid.NewGuid(),
                Data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
                FileName = "tesla_model3.png",
                ContentType = "image/png"
            };

            images.Add(image1);
            images.Add(image2);
            images.Add(image3);

            // Seed vehicles
            vehicles.Add(new Vehicle
            {
                Spz = "1A2 3456",
                Znacka = "Skoda",
                Model = "Octavia",
                Barva = "#0055AA",
                RokVyroby = 2020,
                Palivo = "Benzín",
                NajeteKm = 45000,
                Cena = 350000,
                VlastnikId = owner1.Id,
                Vlastnik = owner1,
                FotografieId = image1.Id,
                Fotografie = image1
            });

            vehicles.Add(new Vehicle
            {
                Spz = "7B8 9012",
                Znacka = "BMW",
                Model = "X5",
                Barva = "#000000",
                RokVyroby = 2019,
                Palivo = "Nafta",
                NajeteKm = 78000,
                Cena = 850000,
                VlastnikId = owner2.Id,
                Vlastnik = owner2,
                FotografieId = image2.Id,
                Fotografie = image2
            });

            vehicles.Add(new Vehicle
            {
                Spz = "3C4 5678",
                Znacka = "Tesla",
                Model = "Model 3",
                Barva = "#FFFFFF",
                RokVyroby = 2022,
                Palivo = "Elektro",
                NajeteKm = 15000,
                Cena = 1200000,
                VlastnikId = owner3.Id,
                Vlastnik = owner3,
                FotografieId = image3.Id,
                Fotografie = image3
            });

            // Save the seeded data
            Save();
        }
    }
}
