import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/button/second_button.dart';
import 'package:farm_tpf/presentation/screens/codes/bloc/stamp_bloc.dart';
import 'package:farm_tpf/presentation/screens/codes/cubit/detail_stamp_cubit.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp_timeline.dart';
import 'package:farm_tpf/presentation/screens/codes/update_activity_page.dart';
import 'package:farm_tpf/presentation/screens/codes/widgets/item_code_timeline.dart';
import 'package:farm_tpf/utils/helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:farm_tpf/utils/formatter.dart';

import '../../../themes/styles_text.dart';
import '../../custom_widgets/loading_list_page.dart';

class CodeDetailPage extends StatefulWidget {
  final int stampId;
  final String stampCode;
  const CodeDetailPage({
    super.key,
    required this.stampId,
    required this.stampCode,
  });

  @override
  State<CodeDetailPage> createState() => _CodeDetailPageState();
}

class _CodeDetailPageState extends State<CodeDetailPage> {
  var bloc = DetailStampCubit();
  @override
  void initState() {
    super.initState();
    bloc.preparedData(widget.stampId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            Expanded(
                child: BlocBuilder<DetailStampCubit, DetailStampState>(
              bloc: bloc,
              builder: (context, state) {
                if (state is DetailStampLoading) {
                  return Center(
                    child: LoadingListPage(),
                  );
                } else if (state is DetailStampFailure) {
                  return Center(child: Text(state.errorMessage));
                } else if (state is DetailStampSuccessful) {
                  var stamp = state.stamp;
                  return SingleChildScrollView(
                    child: Column(
                      children: [
                        _itemCodeDetail(
                          title: 'Tên sản phẩm',
                          detail: stamp.productName ?? '',
                          titleStyle: StylesText.body4,
                          detailStyle: StylesText.body4.copyWith(
                            color: Colors.blue,
                          ),
                        ),
                        _itemCodeDetail(title: 'Mô tả', detail: stamp.description ?? ''),
                        _itemCodeDetail(title: 'Số lượng tem', detail: stamp.quantity?.formatNumtoStringDecimal().toString() ?? ''),
                        _itemCodeDetail(title: 'Trạng thái', detail: Helpers.getStampStatus(stamp.status ?? '')),
                        _itemCodeDetail(title: 'Hạn sử dụng', detail: stamp.expiredDate?.format_DDMMYY().toString() ?? ''),
                        _itemCodeDetail(title: 'Mẫu tem', detail: stamp.stampType?.exampleStampName ?? ''),
                        const SizedBox(
                          height: 8,
                        ),
                        Text(
                          'Timeline hoạt động',
                          style: StylesText.body1,
                        ),
                        const SizedBox(
                          height: 8,
                        ),
                        _timelineWidget(state.timeline),
                      ],
                    ),
                  );
                }
                return const SizedBox.shrink();
              },
            )),
            const SizedBox(
              height: 8,
            ),
            _actionButtonWidget(),
          ],
        ),
      ),
    );
  }

  Widget _timelineWidget(StampTimeline timeline) {
    if ((timeline.content?.length ?? 0) == 0) return const SizedBox.shrink();
    return ListView.builder(
      itemBuilder: (context, index) {
        return ItemCodeTimeline(
          item: timeline.content![index],
          onPressed: () {},
        );
      },
      itemCount: timeline.content?.length ?? 0,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
    );
  }

  Widget _actionButtonWidget() {
    return Wrap(
      spacing: 8,
      children: [
        Row(
          children: [
            Expanded(
              child: SecondButton(
                onPressed: () {
                  bloc.updateStampStatus(
                    stampId: widget.stampId,
                    status: 'ACTIVE',
                  );
                },
                title: 'Kích hoạt toàn bộ',
                borderColor: Colors.blue,
                textColor: Colors.blue,
                width: double.infinity,
                height: 40,
              ),
            ),
            Expanded(
              child: SecondButton(
                onPressed: () {
                  bloc.updateStampStatus(
                    stampId: widget.stampId,
                    status: 'CANCELED',
                  );
                },
                title: 'Huỷ toàn bộ',
                borderColor: Colors.red,
                textColor: Colors.white,
                color: Colors.red,
                width: double.infinity,
                height: 40,
              ),
            ),
          ],
        ),
        const SizedBox(
          height: 8,
        ),
        Row(
          children: [
            Expanded(
              child: SecondButton(
                onPressed: () {
                  Get.to(
                    () => UpdateActivityPage(
                      stampCode: widget.stampCode,
                    ),
                  )?.then((value) {
                    if (value != null) {
                      bloc.preparedData(widget.stampId);
                    }
                  });
                },
                title: 'Cập nhật hoạt động',
                borderColor: Colors.green,
                textColor: Colors.green,
                width: double.infinity,
                height: 40,
              ),
            ),
            Expanded(
              child: SecondButton(
                onPressed: () {
                  bloc.downloadFile(widget.stampCode);
                },
                title: 'In / Xuất file',
                borderColor: Colors.cyan,
                textColor: Colors.white,
                color: Colors.cyan,
                width: double.infinity,
                height: 40,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _itemCodeDetail({
    required String title,
    required String detail,
    TextStyle? titleStyle,
    TextStyle? detailStyle,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      child: Row(
        children: [
          Expanded(
            child: Text(
              title,
              style: titleStyle ?? StylesText.body6,
            ),
          ),
          Text(
            detail,
            style: detailStyle ?? StylesText.body6,
          )
        ],
      ),
    );
  }
}
