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_list_bloc.dart';
import 'package:baseproject/features/presentation/order/view/order_detail_screen.dart';
import 'package:baseproject/features/usecases/order/order_use_cases.dart';
import 'package:baseproject/features/repositories/hra_repository_models.dart';
import 'package:baseproject/features/repositories/hra_repository_enums.dart' as enums;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class OrderListScreen extends StatefulWidget {
  const OrderListScreen({Key? key}) : super(key: key);

  @override
  State<OrderListScreen> createState() => _OrderListScreenState();
}

class _OrderListScreenState extends State<OrderListScreen> {
  late final OrderListBloc _bloc = OrderListBloc(
    getItSuper<OrderUseCases>(),
  );

  @override
  void initState() {
    super.initState();
    _bloc.loadFirstPage();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<OrderListBloc>(
      create: (_) => _bloc,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Khóa học đã mua'),
        ),
        body: SafeArea(
          child: BlocBuilder<OrderListBloc, BaseStateBloc<OrderListViewModel>>(
            builder: (context, state) {
              final vm = state.model;
              final bool isLoading = state is LoadingState<OrderListViewModel> || vm.isLoading;

              return Column(
                children: <Widget>[
                  if (isLoading && vm.orders.isEmpty) const LinearProgressIndicator(),
                  Expanded(
                    child: CustomListView<OrderDto>(
                      totalItem: vm.totalRows,
                      items: vm.orders,
                      onRefresh: _bloc.refreshList,
                      onLoading: () async {
                        final List<OrderDto> newItems = await _bloc.loadMore();
                        return newItems;
                      },
                      itemBuilder: (BuildContext context, int index) {
                        if (index >= vm.orders.length) {
                          return const SizedBox.shrink();
                        }
                        final OrderDto order = vm.orders[index];
                        return _buildOrderItem(context, order);
                      },
                      separatorWidget: const Divider(height: 1),
                      padding: const EdgeInsets.all(16),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildOrderItem(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 _OrderStatusUI statusUI = _getStatusUI(order.status);

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: const Color(0xFFE3F2FD),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    dateText,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xFF1976D2),
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                  decoration: BoxDecoration(
                    color: statusUI.backgroundColor,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    statusUI.label,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              '$studentName  •  $phone',
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 8),
            Divider(
              height: 1,
              color: Colors.grey.shade300,
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const Text(
                      'Tổng tiền:',
                      style: TextStyle(fontSize: 13),
                    ),
                    if (order.totalAmount != null)
                      Text(
                        AppLocalizations.of(context)!.displayCurrency(order.totalAmount ?? 0),
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                          color: Colors.red,
                        ),
                      ),
                  ],
                ),
                InkWell(
                  onTap: () {
                    if (order.id != null) {
                      Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                          builder: (_) => OrderDetailScreen(
                            orderId: order.id!,
                          ),
                        ),
                      );
                    }
                  },
                  child: Text(
                    'Chi tiết →',
                    style: TextStyle(
                      fontSize: 13,
                      color: Theme.of(context).primaryColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  _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 _OrderStatusUI {
  const _OrderStatusUI({
    required this.label,
    required this.backgroundColor,
  });

  final String label;
  final Color backgroundColor;
}
