using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using TaxBaik.Application.DTOs;
using TaxBaik.Application.Services;

namespace TaxBaik.Web.Controllers;

[ApiController]
[Route("api/[controller]")]
public class InquiryController : ControllerBase
{
    private readonly InquiryService _inquiryService;
    private readonly ClientService _clientService;

    public InquiryController(InquiryService inquiryService, ClientService clientService)
    {
        _inquiryService = inquiryService;
        _clientService = clientService;
    }

    [HttpPost]
    public async Task<IActionResult> Submit([FromBody] SubmitInquiryDto request)
    {
        if (string.IsNullOrWhiteSpace(request.Name) || string.IsNullOrWhiteSpace(request.Phone))
            return BadRequest(new ProblemDetails { Title = "이름과 전화번호를 입력하세요.", Status = StatusCodes.Status400BadRequest });

        try
        {
            await _inquiryService.SubmitAsync(
                request.Name,
                request.Phone,
                request.ServiceType,
                request.Message,
                request.Email,
                HttpContext.Connection.RemoteIpAddress?.ToString(),
                request.SuppressNotification);
            return Ok(new { message = "상담 신청이 접수되었습니다." });
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetPaged([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        var (inquiries, total) = await _inquiryService.GetPagedAsync(page, pageSize);
        return Ok(new { data = inquiries, total, page, pageSize });
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetById(int id)
    {
        var inquiry = await _inquiryService.GetByIdAsync(id);
        if (inquiry == null)
            return NotFound(new ProblemDetails { Title = "문의를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });
        return Ok(inquiry);
    }

    [HttpPut("{id}/status")]
    [Authorize]
    public async Task<IActionResult> UpdateStatus(int id, [FromBody] UpdateStatusRequest request)
    {
        var inquiry = await _inquiryService.GetByIdAsync(id);
        if (inquiry == null)
            return NotFound(new ProblemDetails { Title = "문의를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

        try
        {
            var changedBy = User.FindFirstValue(ClaimTypes.Name) ?? User.Identity?.Name;
            await _inquiryService.UpdateStatusAsync(id, request.Status, changedBy);
            return Ok(new { message = "상태가 변경되었습니다." });
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpPut("{id}/memo")]
    [Authorize]
    public async Task<IActionResult> UpdateAdminMemo(int id, [FromBody] UpdateAdminMemoRequest request)
    {
        var inquiry = await _inquiryService.GetByIdAsync(id);
        if (inquiry == null)
            return NotFound(new ProblemDetails { Title = "문의를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

        try
        {
            await _inquiryService.UpdateAdminMemoAsync(id, request.AdminMemo);
            return Ok(new { message = "메모가 저장되었습니다." });
        }
        catch (Exception ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpPut("{id}")]
    [Authorize]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateInquiryDto request)
    {
        try
        {
            var result = await _inquiryService.UpdateAsync(id, request);
            if (result == null)
                return NotFound(new ProblemDetails { Title = "문의를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });
            return Ok(result);
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpPost("{id}/convert-to-client")]
    [Authorize]
    public async Task<IActionResult> ConvertToClient(int id, [FromBody] ConvertToClientRequest request)
    {
        var inquiry = await _inquiryService.GetByIdAsync(id);
        if (inquiry == null)
            return NotFound(new ProblemDetails { Title = "문의를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

        if (inquiry.ClientId != null)
            return BadRequest(new ProblemDetails { Title = "이미 고객 카드가 연결되어 있습니다.", Status = StatusCodes.Status400BadRequest });

        try
        {
            var clientId = await _clientService.CreateFromInquiryAsync(
                request.Name ?? inquiry.Name,
                request.Phone ?? inquiry.Phone,
                request.ServiceType ?? inquiry.ServiceType);

            await _inquiryService.LinkClientAsync(inquiry.Id, clientId);
            await _inquiryService.UpdateStatusAsync(inquiry.Id, "consulting", User.FindFirstValue(ClaimTypes.Name) ?? "system");

            return Ok(new { clientId, message = "고객 카드가 생성되었습니다." });
        }
        catch (Exception ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }
}

public class UpdateStatusRequest
{
    public string Status { get; set; } = string.Empty;
}

public class UpdateAdminMemoRequest
{
    public string? AdminMemo { get; set; }
}

public class ConvertToClientRequest
{
    public string? Name { get; set; }
    public string? Phone { get; set; }
    public string? ServiceType { get; set; }
}
