using System.Text.Json;
using eSPJ.Models;

namespace eSPJ.Services
{
    public class DetailPenjemputanService
    {
        private readonly string _dataFilePath;
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<DetailPenjemputanService> _logger;

        public DetailPenjemputanService(
            IWebHostEnvironment env,
            ILogger<DetailPenjemputanService> logger)
        {
            _env = env;
            _logger = logger;
            _dataFilePath = Path.Combine(_env.ContentRootPath, "Data", "detail-penjemputan.json");
        }

        public async Task<List<TpsData>> GetAllTpsDataAsync()
        {
            try
            {
                if (!File.Exists(_dataFilePath))
                {
                    return new List<TpsData>();
                }

                var json = await File.ReadAllTextAsync(_dataFilePath);
                var data = JsonSerializer.Deserialize<List<TpsData>>(json);
                return data ?? new List<TpsData>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error reading TPS data from JSON");
                return new List<TpsData>();
            }
        }

        public async Task<bool> SaveTpsDataAsync(List<TpsData> data)
        {
            try
            {
                var directory = Path.GetDirectoryName(_dataFilePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };

                var json = JsonSerializer.Serialize(data, options);
                await File.WriteAllTextAsync(_dataFilePath, json);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error saving TPS data to JSON");
                return false;
            }
        }

        public async Task<DetailPenjemputanResponse> SubmitPenjemputanAsync(DetailPenjemputanRequest request)
        {
            try
            {
                // Validate request
                if (string.IsNullOrEmpty(request.TpsName))
                {
                    return new DetailPenjemputanResponse
                    {
                        Success = false,
                        Message = "Nama TPS harus diisi"
                    };
                }

                if (request.FotoKedatangan == null || !request.FotoKedatangan.Any())
                {
                    return new DetailPenjemputanResponse
                    {
                        Success = false,
                        Message = "Foto kedatangan harus diupload"
                    };
                }

                if (request.FotoTimbangan == null || !request.FotoTimbangan.Any())
                {
                    return new DetailPenjemputanResponse
                    {
                        Success = false,
                        Message = "Foto timbangan harus diupload"
                    };
                }

                if (request.FotoPetugas == null || !request.FotoPetugas.Any())
                {
                    return new DetailPenjemputanResponse
                    {
                        Success = false,
                        Message = "Foto petugas harus diupload"
                    };
                }

                if (string.IsNullOrEmpty(request.NamaPetugas))
                {
                    return new DetailPenjemputanResponse
                    {
                        Success = false,
                        Message = "Nama petugas harus diisi"
                    };
                }

                // Save files
                var uploadPath = Path.Combine(_env.WebRootPath, "uploads", "penjemputan", DateTime.Now.ToString("yyyy-MM-dd"));
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                var tpsData = new TpsData
                {
                    Name = request.TpsName,
                    Latitude = request.Latitude,
                    Longitude = request.Longitude,
                    AlamatJalan = request.AlamatJalan,
                    WaktuKedatangan = request.WaktuKedatangan,
                    TotalTimbangan = request.TotalTimbangan,
                    TotalOrganik = request.TotalOrganik,
                    TotalAnorganik = request.TotalAnorganik,
                    TotalResidu = request.TotalResidu,
                    NamaPetugas = request.NamaPetugas,
                    Submitted = true,
                    FotoKedatanganUploaded = true,
                    FotoPetugasUploaded = true
                };

                // Save foto kedatangan
                foreach (var file in request.FotoKedatangan)
                {
                    var fileName = $"kedatangan_{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                    var filePath = Path.Combine(uploadPath, fileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    tpsData.FotoKedatangan.Add(fileName);
                }

                // Save foto timbangan
                if (request.BeratTimbangan != null && request.JenisSampahList != null)
                {
                    for (int i = 0; i < request.FotoTimbangan.Count; i++)
                    {
                        var file = request.FotoTimbangan[i];
                        var fileName = $"timbangan_{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                        var filePath = Path.Combine(uploadPath, fileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }

                        var jenisSampah = JenisSampah.Residu;
                        if (i < request.JenisSampahList.Count && Enum.TryParse<JenisSampah>(request.JenisSampahList[i], out var parsed))
                        {
                            jenisSampah = parsed;
                        }

                        tpsData.Timbangan.Add(new TimbanganItem
                        {
                            FotoFileName = fileName,
                            Berat = i < request.BeratTimbangan.Count ? request.BeratTimbangan[i] : 0,
                            JenisSampah = jenisSampah,
                            IsUploaded = true,
                            WaktuUpload = DateTime.Now
                        });
                    }
                }

                // Save foto petugas
                foreach (var file in request.FotoPetugas)
                {
                    var fileName = $"petugas_{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                    var filePath = Path.Combine(uploadPath, fileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    tpsData.FotoPetugas.Add(fileName);
                }

                // Load existing data and append
                var allData = await GetAllTpsDataAsync();
                allData.Add(tpsData);
                await SaveTpsDataAsync(allData);

                return new DetailPenjemputanResponse
                {
                    Success = true,
                    Message = "Data penjemputan berhasil disimpan",
                    Data = tpsData
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error submitting penjemputan data");
                return new DetailPenjemputanResponse
                {
                    Success = false,
                    Message = $"Terjadi kesalahan: {ex.Message}"
                };
            }
        }

        public async Task<OcrTimbanganResponse> ProcessOcrTimbanganAsync(IFormFile foto)
        {
            try
            {
                // TODO: Integrate with OpenRouter API
                // For now, return mock response
                await Task.Delay(500); // Simulate API call

                return new OcrTimbanganResponse
                {
                    Success = true,
                    Weight = "54.50",
                    Raw = "54.50 kg",
                    Message = "OCR processed successfully (mock)"
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing OCR timbangan");
                return new OcrTimbanganResponse
                {
                    Success = false,
                    Message = $"Terjadi kesalahan: {ex.Message}"
                };
            }
        }
    }
}
