import 'package:baseproject/core/common/index.dart';
import 'package:baseproject/core/components/index.dart';
import 'package:baseproject/core/language/app_localizations.dart';
import 'package:baseproject/features/presentation/order/bloc/order_detail_bloc.dart';
import 'package:baseproject/features/usecases/order/order_use_cases.dart';
import 'package:baseproject/features/repositories/hra_repository_enums.dart'
    as enums;
import 'package:baseproject/features/repositories/hra_repository_models.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class OrderDetailScreen extends StatefulWidget {
  const OrderDetailScreen({
    Key? key,
    required this.orderId,
  }) : super(key: key);

  final int orderId;

  @override
  State<OrderDetailScreen> createState() => _OrderDetailScreenState();
}

class _OrderDetailScreenState extends State<OrderDetailScreen> {
  late final OrderDetailBloc _bloc = OrderDetailBloc(
    getItSuper<OrderUseCases>(),
  );

  @override
  void initState() {
    super.initState();
    _bloc.loadDetail(widget.orderId);
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<OrderDetailBloc>(
      create: (_) => _bloc,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Chi tiết đơn hàng'),
        ),
        body: SafeArea(
          child: BlocBuilder<OrderDetailBloc,
              BaseStateBloc<OrderDetailViewModel>>(
            builder: (context, state) {
              final vm = state.model;
              final bool isLoading =
                  state is LoadingState<OrderDetailViewModel> || vm.isLoading;

              if (isLoading && vm.order == null) {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }

              if (vm.order == null) {
                return const Center(
                  child: Text('Không tìm thấy đơn hàng'),
                );
              }

              return _buildDetailContent(context, vm.order!);
            },
          ),
        ),
      ),
    );
  }

  Widget _buildDetailContent(BuildContext context, OrderDto order) {
    final appLoc = AppLocalizations.of(context)!;
    final DateTime? date = order.paidDate ?? order.createdDate;
    final String dateText =
        appLoc.displayDateTime(date, isFullTime: true, isDateOfMonth: true);

    final String studentName = order.fullName ?? '';
    final String phone = order.phone ?? '';
    final String address = order.address ?? '';

    final _OrderStatusUI statusUI = _getStatusUI(order.status);

    final String amountText = order.totalAmount != null
        ? appLoc.displayNumber(order.totalAmount)
        : '';

    final List<OrderItemDto> items = order.items ?? <OrderItemDto>[];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          _buildInfoRow(
            context,
            leftLabel: 'Ngày đặt',
            leftValue: dateText,
            rightLabel: 'Người nhận',
            rightValue: studentName,
          ),
          const SizedBox(height: 8),
          _buildInfoRow(
            context,
            leftLabel: 'Số điện thoại',
            leftValue: phone,
            rightLabel: 'Địa chỉ giao hàng',
            rightValue: address,
          ),
          const SizedBox(height: 8),
          _buildStatusRow(context, statusUI),
          const SizedBox(height: 16),
          ...items.map((e) => _buildItem(context, e)).toList(),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              gradient: const LinearGradient(
                colors: <Color>[
                  Color(0xFFFFF8E1),
                  Color(0xFFFFECB3),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const Text(
                  'Tổng tiền',
                  style: TextStyle(
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                if (amountText.isNotEmpty)
                  Text.rich(
                    TextSpan(
                      text: amountText,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.red,
                      ),
                      children: const <TextSpan>[
                        TextSpan(
                          text: ' đ',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.normal,
                            color: Colors.red,
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(
    BuildContext context, {
    required String leftLabel,
    required String leftValue,
    required String rightLabel,
    required String rightValue,
  }) {
    return Row(
      children: <Widget>[
        Expanded(
          child: _InfoBox(
            label: leftLabel,
            value: leftValue,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: _InfoBox(
            label: rightLabel,
            value: rightValue,
          ),
        ),
      ],
    );
  }

  Widget _buildStatusRow(BuildContext context, _OrderStatusUI statusUI) {
    return Row(
      children: <Widget>[
        Expanded(
          child: _InfoBox(
            label: 'Trạng thái',
            valueWidget: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: statusUI.backgroundColor),
              ),
              child: Text(
                statusUI.label,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w600,
                  color: statusUI.backgroundColor,
                ),
              ),
            ),
          ),
        ),
        const SizedBox(width: 8),
        const Expanded(child: SizedBox()),
      ],
    );
  }

  Widget _buildItem(BuildContext context, OrderItemDto item) {
    final appLoc = AppLocalizations.of(context)!;
    final String name = item.product?.name ?? 'Khóa học';
    final String image = item.product?.image ?? '';
    final int quantity = item.quantity ?? 1;
    final double? price = item.totalPrice ?? item.salePrice ?? item.unitPrice;
    final String priceText =
        price != null ? appLoc.displayNumber(price) : '';

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            CustomImage(
              imageUrl: image,
              width: 56,
              height: 56,
              fit: BoxFit.cover,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 4),
                  if (priceText.isNotEmpty)
                    Text.rich(
                      TextSpan(
                        text: '$quantity x ',
                        style: const TextStyle(
                          fontSize: 13,
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            text: priceText,
                            style: const TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.bold,
                              color: Colors.red,
                            ),
                          ),
                          const TextSpan(
                            text: ' đ',
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.normal,
                              color: Colors.red,
                            ),
                          ),
                        ],
                      ),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _OrderStatusUI _getStatusUI(enums.OrderStatusEnum? status) {
    if (status == enums.OrderStatusEnum.value_4 ||
        status == enums.OrderStatusEnum.value_5) {
      return const _OrderStatusUI(
        label: 'Thành công',
        backgroundColor: Colors.green,
      );
    }

    return const _OrderStatusUI(
      label: 'Chờ liên hệ',
      backgroundColor: Colors.blue,
    );
  }
}

class _InfoBox extends StatelessWidget {
  const _InfoBox({
    Key? key,
    required this.label,
    this.value,
    this.valueWidget,
  }) : super(key: key);

  final String label;
  final String? value;
  final Widget? valueWidget;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: const Color(0xFF1976D2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: Colors.black54,
            ),
          ),
          const SizedBox(height: 4),
          valueWidget ??
              Text(
                value ?? '',
                style: const TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),
        ],
      ),
    );
  }
}

class _OrderStatusUI {
  const _OrderStatusUI({
    required this.label,
    required this.backgroundColor,
  });

  final String label;
  final Color backgroundColor;
}

