import 'package:flutter/cupertino.dart' hide LinearGradient;
import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/inventory/inventory_model.dart';
import 'package:rasadyar_chicken/data/models/response/kill_house_distribution_info/kill_house_distribution_info.dart';
import 'package:rasadyar_chicken/presentation/routes/routes.dart';
import 'package:rasadyar_chicken/presentation/widget/app_bar.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class PoultryScienceHomePage extends GetView<PoultryScienceHomeLogic> {
  const PoultryScienceHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bgLight,
      appBar: chickenAppBar(hasBack: false, hasFilter: false, hasSearch: false),
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          spacing: 8,
          children: [
            InkWell(
              onTap: () {
                controller.isExpanded.value = !controller.isExpanded.value;
              },
              child: Card(
                margin: EdgeInsetsGeometry.all(6),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                  side: BorderSide(width: 0.50, color: const Color(0xFFA9A9A9)),
                ),

                child: ObxValue((data) {
                  return AnimatedSize(
                    duration: Duration(milliseconds: 300),
                    child: data.value
                        ? Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Row(
                                  spacing: 8,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 40,
                                      height: 40,
                                      decoration: ShapeDecoration(
                                        image: DecorationImage(
                                          image: AssetImage(
                                            Assets.images.chicken.path,
                                          ),
                                          fit: BoxFit.cover,
                                        ),
                                        shape: RoundedRectangleBorder(
                                          side: BorderSide(
                                            width: 0.25,
                                            color: const Color(0xFFB0B0B0),
                                          ),
                                          borderRadius: BorderRadius.circular(
                                            4,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Text(
                                      'مرغ گرم',
                                      textAlign: TextAlign.right,
                                      style: AppFonts.yekan16.copyWith(
                                        color: AppColor.darkGreyDarkActive,
                                      ),
                                    ),
                                    Spacer(),
                                    AnimatedRotation(
                                      turns: 180,
                                      duration: Duration(milliseconds: 3000),
                                      child: Icon(
                                        CupertinoIcons.chevron_up,
                                        size: 18,
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: 8),
                                _todayShipmentWidget(),
                                Row(
                                  children: [
                                    Text(
                                      'اطلاعات جوجه ریزی',
                                      textAlign: TextAlign.right,
                                      style: AppFonts.yekan16,
                                    ),
                                  ],
                                ),
                                _inventoryWidget(),
                                killsShipment(),
                                ageWidget(),
                              ],
                            ),
                          )
                        : Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Row(
                                  spacing: 8,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 40,
                                      height: 40,
                                      decoration: ShapeDecoration(
                                        image: DecorationImage(
                                          image: AssetImage(
                                            Assets.images.chicken.path,
                                          ),
                                          fit: BoxFit.cover,
                                        ),
                                        shape: RoundedRectangleBorder(
                                          side: BorderSide(
                                            width: 0.25,
                                            color: const Color(0xFFB0B0B0),
                                          ),
                                          borderRadius: BorderRadius.circular(
                                            4,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Text(
                                      'مرغ گرم',
                                      textAlign: TextAlign.right,
                                      style: AppFonts.yekan16.copyWith(
                                        color: AppColor.darkGreyDarkActive,
                                      ),
                                    ),
                                    Spacer(),
                                    Icon(CupertinoIcons.chevron_down, size: 18),
                                  ],
                                ),
                                _todayShipmentWidget(),
                                _inventoryWidget(),
                              ],
                            ),
                          ),
                  );
                }, controller.isExpanded),
              ),
            ),

            widelyWidget(),
            SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget ageWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 8, 0, 13),
      child: ObxValue((data) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          spacing: 8,
          children: [
            _informationIconCard(
              title: 'کمترین سن جوجه ریزیط',
              isLoading: data.value == null,

              description:
                  '${data.value?.hatchingMinAge.separatedByComma} روز' ?? '0',
              iconPath: Assets.vec.homeTrendUpSvg.path,
              iconColor: const Color.fromRGBO(85, 97, 93, 1),
              bgDescriptionColor: const Color(0xFFE6FAF5),
              bgLabelColor: const Color(0xFFB0EFDF),
            ),
            _informationIconCard(
              title: 'بیشترین سن جوجه ریزی',
              description:
                  '${data.value?.hatchingMaxAge.separatedByComma} روز' ?? '0',
              iconPath: Assets.vec.homeTrendUpSvg.path,
              iconColor: const Color(0xFF6F6164),
              bgDescriptionColor: const Color(0xFFEDDCE0),
              bgLabelColor: const Color(0xFFE0BCC5),
            ),
          ],
        );
      }, controller.homeInformation),
    );
  }

  Widget killsShipment() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 8, 0, 13),
      child: ObxValue((data) {
        return Row(
          spacing: 8,
          children: [
            Expanded(
              child: _informationLabelCard(
                title: 'تلفات',
                isLoading: data.value == null,
                unit: 'قطعه',
                description:
                    data.value?.hatchingLosses?.separatedByComma ?? '0',
                iconPath: Assets.vec.boxRemoveSvg.path,
                iconColor: const Color(0xFF6C5D60),
                bgDescriptionColor: const Color(0xFFEDDCE0),
                bgLabelColor: const Color(0xFFDDC0C7),
              ),
            ),
            Expanded(
              child: _informationLabelCard(
                title: 'حجم کشتار شده',
                unit: 'قطعه',
                isLoading: data.value == null,
                description:
                    data.value?.hatchingKilledQuantity.separatedByComma ?? '0',
                iconPath: Assets.vec.closeSquareFilledSvg.path,
                iconColor: Color(0xFF2D5FFF),
                bgLabelColor: const Color(0xFFAFCBFF),
                bgDescriptionColor: const Color(0xFFCEDFFF),
              ),
            ),
          ],
        );
      }, controller.homeInformation),
    );
  }

  Widget _inventoryWidget() {
    return ObxValue((data) {
      return Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 13),
        child: Row(
          spacing: 8,
          children: [
            Expanded(
              child: _informationLabelCard(
                title: 'حجم جوجه ریزی',
                isLoading: data.value == null,
                unit: 'قطعه',
                description:
                    data.value?.hatchingQuantity.separatedByComma ?? '0',
                iconPath: Assets.vec.hashtagSvg.path,
                iconColor: const Color(0xFF426060),
                bgDescriptionColor: const Color(0xFFC7DFE0),
                bgLabelColor: const Color(0xFFA5D1D2),
              ),
            ),
            Expanded(
              child: _informationLabelCard(
                title: 'مانده در سالن',
                unit: 'قطعه',
                isLoading: data.value == null,
                description:
                    data.value?.hatchingLeftOver.separatedByComma ?? '0',
                iconPath: Assets.vec.homeHashtagSvg.path,
                iconColor: Color(0xFF5C4D64),
                bgLabelColor: Color(0xFFC8B8D1),
                bgDescriptionColor: Color(0xFFDAD4DD),
              ),
            ),
          ],
        ),
      );
    }, controller.homeInformation);
  }

  Widget _todayShipmentWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 10, 0, 13),
      child: Row(
        spacing: 8,
        children: [
          Expanded(
            child: ObxValue(
              (data) => _informationLabelCard(
                title: 'کل فارم ها',
                isLoading: data.value == null,
                description: data.value?.farmCount?.separatedByComma ?? '0',
                iconPath: Assets.vec.cubeSearchSvg.path,
                iconColor: AppColor.blueNormal,
                bgDescriptionColor: Colors.white,
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [AppColor.blueLight, Colors.white],
                ),
              ),
              controller.homeInformation,
            ),
          ),

          Expanded(
            child: ObxValue((data) {
              return _informationLabelCard(
                title: 'تعداد جوجه ریزی',
                isLoading: data.value == null,
                description: data.value?.hatchingCount.separatedByComma ?? '0',
                iconPath: Assets.vec.cubeCardSvg.path,
                bgDescriptionColor: Colors.white,
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [AppColor.greenLightHover, Colors.white],
                ),
              );
            }, controller.homeInformation),
          ),
        ],
      ),
    );
  }

  Container _informationLabelCard({
    required String title,
    required String description,
    required String iconPath,
    required Color bgDescriptionColor,
    String? unit,
    bool isLoading = false,
    Color? iconColor,
    Color? titleColor,
    Color? bgLabelColor,
    LinearGradient? gradient,
  }) {
    return Container(
      height: 82,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
      clipBehavior: Clip.hardEdge,
      child: Row(
        children: [
          // Left side with icon and title
          Expanded(
            child: Container(
              height: 82,
              decoration: BoxDecoration(
                color: gradient == null ? bgLabelColor : null,
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(8),
                  bottomRight: Radius.circular(8),
                ),
                gradient: gradient,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 4,
                children: [
                  SvgGenImage.vec(iconPath).svg(
                    width: 24,
                    height: 24,
                    colorFilter: iconColor != null
                        ? ColorFilter.mode(iconColor, BlendMode.srcIn)
                        : null,
                  ),
                  Text(
                    title,
                    textAlign: TextAlign.right,
                    style: AppFonts.yekan10.copyWith(
                      color: titleColor ?? AppColor.mediumGreyDarkActive,
                    ),
                  ),
                ],
              ),
            ),
          ),
          // Right side with description and unit
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                color: bgDescriptionColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(8),
                  bottomLeft: Radius.circular(8),
                ),
              ),
              child: isLoading
                  ? Center(child: CupertinoActivityIndicator())
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      spacing: 4,
                      children: [
                        Text(
                          description,
                          textAlign: TextAlign.right,
                          style: AppFonts.yekan12.copyWith(
                            color: AppColor.mediumGreyDarkActive,
                          ),
                        ),
                        Visibility(
                          visible: unit != null,
                          child: Text(
                            unit ?? '',
                            textAlign: TextAlign.center,
                            style: AppFonts.yekan12.copyWith(
                              color: AppColor.mediumGreyDarkActive,
                            ),
                          ),
                        ),
                      ],
                    ),
            ),
          ),
        ],
      ),
    );
  }

  Container _informationIconCard({
    required String title,
    required String description,
    String? unit,
    bool isLoading = false,
    required String iconPath,
    required Color iconColor,
    required Color bgDescriptionColor,
    required Color bgLabelColor,
  }) {
    return Container(
      height: 100.h,
      width: 145.w,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
      clipBehavior: Clip.hardEdge,
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          Positioned(
            bottom: 0,
            right: 0,
            left: 0,
            child: Container(
              height: 91,
              decoration: BoxDecoration(
                color: bgDescriptionColor,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(width: 0.25, color: const Color(0xFFB4B4B4)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 4,
                children: [
                  Text(
                    title,
                    textAlign: TextAlign.right,
                    style: AppFonts.yekan14.copyWith(
                      color: AppColor.mediumGreyDarkActive,
                    ),
                  ),

                  isLoading
                      ? Center(child: CupertinoActivityIndicator())
                      : Text(
                          description,
                          textAlign: TextAlign.right,
                          style: AppFonts.yekan16.copyWith(
                            color: AppColor.mediumGreyDarkActive,
                          ),
                        ),

                  Visibility(
                    visible: unit != null,
                    child: Text(
                      unit ?? '',
                      textAlign: TextAlign.center,
                      style: AppFonts.yekan12.copyWith(
                        color: AppColor.mediumGreyDarkActive,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            top: 0,
            child: Container(
              width: 32,
              height: 32,
              decoration: ShapeDecoration(
                color: bgLabelColor,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                  side: BorderSide(width: 0.25, color: const Color(0xFFD5D5D5)),
                ),
              ),
              child: Center(
                child: SvgGenImage.vec(iconPath).svg(
                  width: 24,
                  height: 24,
                  colorFilter: ColorFilter.mode(iconColor, BlendMode.srcIn),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget inventoryItem({
    required bool isExpanded,
    required int index,
    required InventoryModel model,
  }) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      spacing: 8,
      children: [
        buildRow('نام محصول', model.name ?? ''),
        Visibility(
          visible: isExpanded,
          child: Column(
            spacing: 8,
            children: [
              buildRow('وزن خریدهای دولتی داخل استان (کیلوگرم)', '0326598653'),
              buildRow(
                'وزن خریدهای آزاد داخل استان (کیلوگرم)',
                model.receiveFreeCarcassesWeight.toString(),
              ),
              buildRow(
                'وزن خریدهای خارج استان (کیلوگرم)',
                model.freeBuyingCarcassesWeight.toString(),
              ),
              buildRow(
                'کل ورودی به انبار (کیلوگرم)',
                model.totalFreeBarsCarcassesWeight.toString(),
              ),
              buildRow(
                'کل فروش (کیلوگرم)',
                model.realAllocatedWeight.toString(),
              ),
              buildRow(
                'مانده انبار (کیلوگرم)',
                model.totalRemainWeight.toString(),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget buildRow(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible(
            flex: 2,
            child: Text(
              title,
              textAlign: TextAlign.right,
              style: AppFonts.yekan14.copyWith(
                color: AppColor.darkGreyDarkHover,
              ),
            ),
          ),
          Flexible(
            flex: 1,
            child: Text(
              value,
              textAlign: TextAlign.center,
              style: AppFonts.yekan14.copyWith(
                color: AppColor.darkGreyDarkHover,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget broadcastInformationWidget(KillHouseDistributionInfo? model) {
    return Container(
      height: 140,
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: AppColor.blueNormal, width: 1),
      ),
      child: model != null
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              spacing: 10,
              children: [
                Text(
                  'اطلاعات ارسالی',
                  textAlign: TextAlign.right,
                  style: AppFonts.yekan16Bold.copyWith(
                    color: AppColor.blueNormal,
                  ),
                ),
                const SizedBox(height: 12),
                buildRow(
                  'فروش و توزیع داخل استان (کیلوگرم)',
                  model.stewardAllocationsWeight!.toInt().toString(),
                ),
                buildRow(
                  'فروش و توزیع خارج استان (کیلوگرم)',
                  model.freeSalesWeight!.toInt().toString(),
                ),
              ],
            )
          : const Center(child: CircularProgressIndicator()),
    );
  }

  Widget cardWidget({
    required String title,
    required String iconPath,
    required VoidCallback onTap,
  }) {
    return Container(
      width: Get.width / 4,
      height: 130,
      child: GestureDetector(
        onTap: onTap,
        child: Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
            side: BorderSide(width: 1, color: AppColor.blueNormal),
          ),
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SvgGenImage(iconPath).svg(width: 50, height: 50),
                SizedBox(height: 4),
                Text(
                  title,
                  textAlign: TextAlign.center,
                  style: AppFonts.yekan12.copyWith(color: AppColor.blueNormal),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget widelyWidget() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsetsGeometry.all(6),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'پر کاربرد ها',
                textAlign: TextAlign.right,
                style: AppFonts.yekan16,
              ),
            ],
          ),
        ),

        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 2.0, vertical: 2),
          child: Wrap(
            spacing: 15,
            runSpacing: 8,
            children: [
              widelyUsed(
                title: 'بازرسی',
                iconPath: Assets.vec.cubeSearchSvg.path,
                isOnEdit: false,

                cardColor: AppColor.greenLightActive,
                labelColor: AppColor.greenNormal,
                textColor: AppColor.greenDarkHover,
                onTap: () async {
                  controller.rootLogic.currentPage.value = 0;
                  controller.rootLogic.currentPage.refresh();
                  await Future.delayed(Duration(milliseconds: 100));
                  Get.toNamed(ChickenRoutes.inspectionPoultryScience, id: 0);
                },
              ),

              widelyUsed(
                title: 'ثبت کشتار',
                iconPath: Assets.vec.noteRemoveSvg.path,

                onTap: () async {
                  controller.rootLogic.currentPage.value = 0;
                  controller.rootLogic.currentPage.refresh();
                  await Future.delayed(Duration(milliseconds: 100));
                  //Get.toNamed(ChickenRoutes.inspectionPoultryScience, id: 0);
                },
                isOnEdit: false,
              ),
              widelyUsed(
                title: 'فارم ها',
                iconPath: Assets.vec.a3dCubeSquareSvg.path,
                isOnEdit: false,
                onTap: () async {
                  controller.rootLogic.currentPage.value = 1;
                  controller.rootLogic.currentPage.refresh();
                  await Future.delayed(Duration(milliseconds: 100));
                  // Get.toNamed(ChickenRoutes.salesOutOfProvinceSteward, id: 1);
                },
              ),

              widelyUsed(
                title: 'جوجه ریزی فعال',
                iconPath: Assets.vec.boxTickSvg.path,
                isOnEdit: false,
                onTap: () async {
                  controller.rootLogic.currentPage.value = 1;
                  controller.rootLogic.currentPage.refresh();
                  await Future.delayed(Duration(milliseconds: 100));
                  //  Get.toNamed(ChickenRoutes.salesInProvinceSteward, id: 1);
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget widelyUsed({
    required String title,
    required String iconPath,
    required VoidCallback onTap,
    required bool isOnEdit,
    Color? cardColor,
    Color? labelColor,
    Color? textColor,
  }) {
    return GestureDetector(
      onTap: !isOnEdit ? onTap : null,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        spacing: 4,
        children: [
          Stack(
            clipBehavior: Clip.none,
            children: [
              Container(
                width: 48,
                height: 48,
                padding: EdgeInsets.all(4),
                decoration: ShapeDecoration(
                  color: cardColor ?? Color(0xFFBECDFF),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: ShapeDecoration(
                    color: labelColor ?? AppColor.blueNormal,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: SvgGenImage.vec(iconPath).svg(
                    width: 24,
                    height: 24,
                    colorFilter: ColorFilter.mode(
                      Colors.white,
                      BlendMode.srcIn,
                    ),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Visibility(
                visible: isOnEdit,
                child: Container(
                  width: 48,
                  height: 48,
                  padding: EdgeInsets.all(4),
                  decoration: ShapeDecoration(
                    color: Colors.white60,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
              ),

              Visibility(
                visible: isOnEdit,
                child: Positioned(
                  top: -15,
                  left: -12,
                  child: SizedBox(
                    width: 32.w,
                    height: 32.h,
                    child: GestureDetector(
                      onTap: () {},
                      behavior: HitTestBehavior.translucent,
                      child: Center(
                        child: Container(
                          width: 16,
                          height: 16,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.white,
                          ),
                          alignment: Alignment.center,
                          child: Icon(
                            CupertinoIcons.minus,
                            color: AppColor.error,
                            size: 15,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Text(
            title,
            style: AppFonts.yekan10.copyWith(
              color: textColor ?? AppColor.blueNormal,
            ),
          ),
        ],
      ),
    );
  }
}
