package com.toyshop.controller.user;

import com.toyshop.dto.*;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import com.toyshop.service.*;
import jakarta.validation.Valid;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
  private final UserService userService;
  private final UserRepository userRepository;
  private final AddressRepository addressRepository;
  private final CartService cartService;
  private final OrderService orderService;
  private final OrderRepository orderRepository;
  private final OrderItemRepository orderItemRepository;
  private final PasswordEncoder passwordEncoder;

  public UserController(UserService userService, UserRepository userRepository, AddressRepository addressRepository,
                        CartService cartService, OrderService orderService, OrderRepository orderRepository,
                        OrderItemRepository orderItemRepository, PasswordEncoder passwordEncoder) {
    this.userService = userService;
    this.userRepository = userRepository;
    this.addressRepository = addressRepository;
    this.cartService = cartService;
    this.orderService = orderService;
    this.orderRepository = orderRepository;
    this.orderItemRepository = orderItemRepository;
    this.passwordEncoder = passwordEncoder;
  }

  @GetMapping("/profile")
  public ApiResponse<User> profile() {
    User user = userService.getCurrentUser();
    user.setPassword("***");
    return ApiResponse.ok(user);
  }

  @PutMapping("/profile")
  public ApiResponse<User> updateProfile(@RequestBody User body) {
    User user = userService.getCurrentUser();
    user.setPhone(body.getPhone());
    user.setEmail(body.getEmail());
    user.setAvatar(body.getAvatar());
    userRepository.save(user);
    user.setPassword("***");
    return ApiResponse.ok(user);
  }

  @PutMapping("/password")
  public ApiResponse<?> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
    User user = userService.getCurrentUser();
    if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
      return ApiResponse.fail("原密码错误");
    }
    user.setPassword(passwordEncoder.encode(newPassword));
    userRepository.save(user);
    return ApiResponse.ok("修改成功", null);
  }

  @GetMapping("/addresses")
  public ApiResponse<List<Address>> addresses() {
    User user = userService.getCurrentUser();
    return ApiResponse.ok(addressRepository.findByUser(user));
  }

  @PostMapping("/addresses")
  public ApiResponse<Address> addAddress(@Valid @RequestBody AddressRequest request) {
    User user = userService.getCurrentUser();
    Address address = new Address();
    address.setUser(user);
    address.setReceiverName(request.getReceiverName());
    address.setReceiverPhone(request.getReceiverPhone());
    address.setDetail(request.getDetail());
    address.setDefault(request.isDefault());
    return ApiResponse.ok(addressRepository.save(address));
  }

  @PutMapping("/addresses/{id}")
  public ApiResponse<Address> updateAddress(@PathVariable Long id, @Valid @RequestBody AddressRequest request) {
    User user = userService.getCurrentUser();
    Address address = addressRepository.findById(id).orElseThrow();
    if (!address.getUser().getId().equals(user.getId())) {
      return ApiResponse.fail("无权限");
    }
    address.setReceiverName(request.getReceiverName());
    address.setReceiverPhone(request.getReceiverPhone());
    address.setDetail(request.getDetail());
    address.setDefault(request.isDefault());
    return ApiResponse.ok(addressRepository.save(address));
  }

  @DeleteMapping("/addresses/{id}")
  public ApiResponse<?> deleteAddress(@PathVariable Long id) {
    User user = userService.getCurrentUser();
    Address address = addressRepository.findById(id).orElseThrow();
    if (!address.getUser().getId().equals(user.getId())) {
      return ApiResponse.fail("无权限");
    }
    addressRepository.delete(address);
    return ApiResponse.ok("删除成功", null);
  }

  @GetMapping("/cart")
  public ApiResponse<List<CartItem>> cartList() {
    User user = userService.getCurrentUser();
    return ApiResponse.ok(cartService.list(user));
  }

  @PostMapping("/cart")
  public ApiResponse<?> addToCart(@Valid @RequestBody CartItemRequest request) {
    User user = userService.getCurrentUser();
    cartService.add(user, request.getProductId(), request.getQuantity());
    return ApiResponse.ok("加入成功", null);
  }

  @PutMapping("/cart/{itemId}")
  public ApiResponse<?> updateCart(@PathVariable Long itemId, @RequestBody CartItemRequest request) {
    User user = userService.getCurrentUser();
    cartService.update(user, itemId, request.getQuantity());
    return ApiResponse.ok("更新成功", null);
  }

  @DeleteMapping("/cart/{itemId}")
  public ApiResponse<?> deleteCart(@PathVariable Long itemId) {
    User user = userService.getCurrentUser();
    cartService.remove(user, itemId);
    return ApiResponse.ok("删除成功", null);
  }

  @PostMapping("/orders")
  public ApiResponse<Order> createOrder(@Valid @RequestBody OrderCreateRequest request) {
    User user = userService.getCurrentUser();
    return ApiResponse.ok(orderService.createOrder(user, request.getAddressId()));
  }

  @GetMapping("/orders")
  public ApiResponse<List<Order>> listOrders() {
    User user = userService.getCurrentUser();
    return ApiResponse.ok(orderService.listOrders(user));
  }

  @GetMapping("/orders/{id}")
  public ApiResponse<Map<String, Object>> orderDetail(@PathVariable Long id) {
    User user = userService.getCurrentUser();
    Order order = orderRepository.findById(id).orElseThrow();
    if (!order.getUser().getId().equals(user.getId())) {
      return ApiResponse.fail("无权限");
    }
    List<OrderItem> items = orderItemRepository.findByOrder(order);
    Map<String, Object> data = new HashMap<>();
    data.put("order", order);
    data.put("items", items);
    return ApiResponse.ok(data);
  }

  @PostMapping("/orders/{id}/pay")
  public ApiResponse<?> pay(@PathVariable Long id) {
    User user = userService.getCurrentUser();
    Order order = orderRepository.findById(id).orElseThrow();
    if (!order.getUser().getId().equals(user.getId())) {
      return ApiResponse.fail("无权限");
    }
    order.setStatus(OrderStatus.PENDING_SHIPMENT);
    orderRepository.save(order);
    return ApiResponse.ok("支付成功", null);
  }
}
