import 'package:flutter/cupertino.dart';
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_core/core.dart';

import 'logic.dart';

class HomePage extends GetView<HomeLogic> {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bgLight,
      appBar: RAppBar(
        title: 'رصدطیور',
        iconTitle: Assets.vec.chickenSvg.path,
        titleTextStyle: AppFonts.yekan16Bold.copyWith(color: Colors.white),
        centerTitle: true,
        hasBack: false,
        leading: Row(
          children: [Text('مباشر', style: AppFonts.yekan16Bold.copyWith(color: Colors.white))],
        ),
      ),
      body: Column(
        spacing: 8,
        children: [
          Card(
            margin: EdgeInsetsGeometry.all(6),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
              side: BorderSide(width: 0.50, color: const Color(0xFFA9A9A9)),
            ),

            child: 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(),

                  _inventoryWidget(),

                  Row(
                    children: [Text('اطلاعات بارها', textAlign: TextAlign.right, style: AppFonts.yekan16)],
                  ),

                  _informationShipment(),

                  Row(
                    children: [Text('اطلاعات توزیع', textAlign: TextAlign.right, style: AppFonts.yekan16)],
                  ),

                  distributionInformationWidget(),
                ],
              ),
            ),
          ),

          Padding(
            padding: EdgeInsetsGeometry.all(6),
            child: Row(
              children: [Text('پر کاربرد ها', textAlign: TextAlign.right, style: AppFonts.yekan16)],
            ),
          ),

          SizedBox(
            height: 70,
            child: ListView(
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(horizontal: 12),
              physics: BouncingScrollPhysics(),
              children: [
                widelyUsed(
                  title: 'خرید خارج استان',
                  iconPath: Assets.vec.cubeSearchSvg.path,
                  onTap:() async{
                    iLog('on tap :خرید خارج استان  ');
                    controller.rootLogic.currentPage.value =1;
                    controller.rootLogic.currentPage.refresh();
                    await Future.delayed(Duration(milliseconds: 100));
                    Get.toNamed(ChickenRoutes.salesOutOfProvince, id: 1);
                  },
                ),
                SizedBox(width: 15),
                widelyUsed(
                  title: 'عمده فروشی',
                  iconPath: Assets.vec.truckFastSvg.path,
                  onTap: () {
                    //Get.toNamed(ChickenRoutes.salesWithinProvince);
                  },
                ),
                SizedBox(width: 15),
                widelyUsed(
                  title: 'ثبت قطعه بندی',
                  iconPath: Assets.vec.convertCubeSvg.path,
                  onTap: () {
                    //  Get.toNamed(ChickenRoutes.salesWithOutProvince);
                  },
                ),
                SizedBox(width: 15),
                addWidelyUsed(onTap: () {}),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget distributionInformationWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 8, 0, 13),
      child: ObxValue((data) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          spacing: 8,
          children: [
            Expanded(
              child: _informationIconCard(
                title: 'توزیع داخل استان',
                isLoading: data.value == null,
                description: data.value?.freeSalesWeight.separatedByComma ?? '0',
                iconPath: Assets.vec.truckSvg.path,
                iconColor: const Color.fromRGBO(85, 97, 93, 1),
                bgDescriptionColor: const Color(0xFFE6FAF5),
                bgLabelColor: const Color(0xFFB0EFDF),
              ),
            ),
            Expanded(
              child: _informationIconCard(
                title: 'توزیع خارج استان',
                isLoading: data.value == null,
                description: data.value?.stewardAllocationsWeight.separatedByComma ?? '0',
                iconPath: Assets.vec.truckFastSvg.path,
                iconColor: Color(0xFF647379),
                bgDescriptionColor: const Color(0xFFEAEFFF),
                bgLabelColor: const Color(0xFFD4DEFF),
              ),
            ),
            Expanded(
              child: _informationIconCard(
                title: 'قطعه بندی',
                description: '2،225،256',
                iconPath: Assets.vec.convertCubeSvg.path,
                iconColor: const Color(0xFF6F6164),
                bgDescriptionColor: const Color(0xFFEDDCE0),
                bgLabelColor: const Color(0xFFE0BCC5),
              ),
            ),
          ],
        );
      }, controller.killHouseDistributionInfo),
    );
  }

  Widget _informationShipment() {
    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,
                description: data.value != null
                    ? ((data.value?.provinceGovernmentalCarcassesWeight ?? 0) +
                    (data.value?.provinceFreeCarcassesWeight ?? 0))
                    .separatedByComma
                    : '0',
                iconPath: Assets.vec.a3dCubeSquareSvg.path,
                iconColor: const Color(0xFF6C5D60),
                bgDescriptionColor: const Color(0xFFEDDCE0),
                bgLabelColor: const Color(0xFFDDC0C7),
              ),
            ),
            Expanded(
              child: _informationLabelCard(
                title: 'خارج استان',
                isLoading: data.value == null,
                description: data.value?.freeBuyingCarcassesWeight.separatedByComma ?? '0',
                iconPath: Assets.vec.cubeSearchSvg.path,
                iconColor: Color(0xFF2D5FFF),
                bgLabelColor: const Color(0xFFAFCBFF),
                bgDescriptionColor: const Color(0xFFCEDFFF),
              ),
            ),
          ],
        );
      }, controller.inventoryModel),
    );
  }

  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,
                description: data.value?.totalRemainWeight.separatedByComma ?? '0',
                iconPath: Assets.vec.cubeSearchSvg.path,
                iconColor: const Color(0xFF426060),
                bgDescriptionColor: const Color(0xFFC7DFE0),
                bgLabelColor: const Color(0xFFA5D1D2),
              ),
            ),
            Expanded(
              child: _informationLabelCard(
                title: 'توزیع شده',
                isLoading: data.value == null,
                description: data.value?.realAllocatedWeight.separatedByComma ?? '0',
                iconPath: Assets.vec.cubeRotateSvg.path,
                iconColor: Color(0xFF5C4D64),
                bgLabelColor: Color(0xFFC8B8D1),
                bgDescriptionColor: Color(0xFFDAD4DD),
              ),
            ),
          ],
        ),
      );
    }, controller.inventoryModel);
  }

  Widget _todayShipmentWidget() {
    return ObxValue((data) {
      return Container(
        height: 70,
        width: Get.width / 2,
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
        clipBehavior: Clip.hardEdge,
        child: Row(
          children: [
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [const Color(0xFFEAEFFF), Colors.white],
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  spacing: 4,
                  children: [
                    Assets.icons.cubeScan.svg(width: 30, height: 30),
                    Text(
                      'بارهای امروز',
                      textAlign: TextAlign.right,
                      style: AppFonts.yekan14.copyWith(color: AppColor.blueNormal),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: data.value == null
                  ? CupertinoActivityIndicator()
                  : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 4,
                children: [
                  Text(
                    data.value.separatedByComma,
                    textAlign: TextAlign.right,
                    style: AppFonts.yekan16.copyWith(color: AppColor.textColor),
                  ),
                  Text(
                    'کیلوگرم',
                    textAlign: TextAlign.center,
                    style: AppFonts.yekan12.copyWith(color: AppColor.textColor),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }, controller.totalWeightTodayBars);
  }

  Container _informationLabelCard({
    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: 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: bgLabelColor,
                borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomRight: Radius.circular(8)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 4,
                children: [
                  SvgGenImage.vec(
                    iconPath,
                  ).svg(width: 24, height: 24, colorFilter: ColorFilter.mode(iconColor, BlendMode.srcIn)),
                  Text(
                    title,
                    textAlign: TextAlign.right,
                    style: AppFonts.yekan14.copyWith(color: 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.yekan16.copyWith(color: AppColor.mediumGreyDarkActive),
                  ),
                  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: 110,
      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),
                  ),
                  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 widelyUsed({required String title, required String iconPath, required VoidCallback onTap}) {
    return GestureDetector(
        onTap: onTap,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          spacing: 4,
          children: [
            Container(
              width: 48,
              height: 48,
              padding: EdgeInsets.all(4),
              decoration: ShapeDecoration(
                color: const Color(0xFFBECDFF),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
              child: Container(
                width: 40,
                height: 40,
                decoration: ShapeDecoration(
                  color: 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,
                ),
              ),
            ),
            Text(title, style: AppFonts.yekan10.copyWith(color: AppColor.blueNormal)),
          ],
        ));
  }

  Widget addWidelyUsed({required VoidCallback onTap}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      spacing: 4,
      children: [
        Container(
          width: 48,
          height: 48,
          padding: EdgeInsets.all(4),
          decoration: ShapeDecoration(
            color: const Color(0xFFD9F7F0),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          child: Assets.vec.messageAddSvg.svg(
            width: 40,
            height: 40,
            colorFilter: ColorFilter.mode(AppColor.greenNormal, BlendMode.srcIn),
            fit: BoxFit.cover,
          ),
        ),
        Text('افزودن', style: AppFonts.yekan10.copyWith(color: AppColor.greenDarkHover)),
      ],
    );
  }

  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),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
