import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/modules/asset_inventory_module/models/session_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';

class AssetInventoryDetailView extends StatefulWidget {
  SessionModel sessionModel;

  AssetInventoryDetailView({Key? key, required this.sessionModel}) : super(key: key);

  @override
  State<AssetInventoryDetailView> createState() => _AssetInventoryDetailViewState();
}

class _AssetInventoryDetailViewState extends State<AssetInventoryDetailView> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return widget.sessionModel.id == null
        ? const NoDataFound()
        : ListView(
            padding: const EdgeInsets.all(16),
            children: [
              requestDetailCard(context, widget.sessionModel),
              16.height,
              siteListCard(context, widget.sessionModel),
            ],
          );
  }

  TextStyle infoTextStyle(context) => AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral120);

  Widget requestDetailCard(BuildContext context, SessionModel sessionModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            StatusLabel(
              label: sessionModel.statusName,
              id: sessionModel.statusId,
              radius: 4,
              textColor: AppColor.getRequestStatusTextColorByName(context, sessionModel.statusName),
              backgroundColor: AppColor.getRequestStatusColorByName(context, sessionModel.statusName),
            ),
            InfoDateWidget(sessionModel.createdDate?.toString() ?? ""),
          ],
        ),
        8.height,
        InfoHeader16Widget('Session Details'.addTranslation),
        InfoTextWidget(label: 'Session Name'.addTranslation, value: sessionModel.sessionName?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'),
        InfoTextWidget(label: 'Session Type'.addTranslation, value: sessionModel.sessionTypeName ?? '-'),
        InfoTextWidget(label: 'Start Date'.addTranslation, value: sessionModel.startDate?.toServiceRequestDetailsFormat ?? '-'),
        InfoTextWidget(label: 'End Date'.addTranslation, value: sessionModel.endDate?.toServiceRequestDetailsFormat ?? '-'),
      ],
    ).toShadowContainer(context, borderRadius: 20);
  }

  Widget siteListCard(BuildContext context, SessionModel sessionModel) {
    final sites = sessionModel.assetInventorySites ?? [];

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Sites Information"),
        SiteHierarchyView(
          sites: sites,
        ),
      ],
    ).toShadowContainer(context, borderRadius: 20);
  }
}



class SiteHierarchyView extends StatelessWidget {
  final List<Site> sites;

  const SiteHierarchyView({super.key, required this.sites});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: sites.length,
      itemBuilder: (context, index) {
        final site = sites[index];
        return HierarchyTile(
          title: site.name ?? '-',
          children: (site.buildings ?? [])
              .map((b) => HierarchyTile(
            title: b.name ?? '-',
            children: (b.floors ?? [])
                .map((f) => HierarchyTile(
              title: f.name ?? '-',
              children: (f.departments ?? [])
                  .map((d) => HierarchyTile(
                title: d.name ?? '-',
                children: (d.rooms ?? [])
                    .map((r) => LeafTile(title: r.name ?? '-'))
                    .toList(),
              ))
                  .toList(),
            ))
                .toList(),
          ))
              .toList(),
        );
      },
    );
  }
}
class HierarchyTile extends StatefulWidget {
  final String title;
  final List<Widget> children;
  final double indent;

  const HierarchyTile({
    super.key,
    required this.title,
    this.children = const [],
    this.indent = 0,
  });

  @override
  State<HierarchyTile> createState() => _HierarchyTileState();
}

class _HierarchyTileState extends State<HierarchyTile> {
  bool expanded = false;

  @override
  Widget build(BuildContext context) {
    final hasChildren = widget.children.isNotEmpty;
    return Padding(
      padding: EdgeInsets.only(left: widget.indent,top: 10.toScreenHeight),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: hasChildren ? () => setState(() => expanded = !expanded) : null,
            child: Row(
              children: [
                if (hasChildren)
          // expanded? 'expended_arrow_icon'.toSvgAsset(color: AppColor.neutral50,width: 8,height:13): 'collesped_arrow_icon'.toSvgAsset(color: AppColor.neutral50,width: 8,height:13)
                  Icon(
                    expanded ? Icons.expand_more : Icons.chevron_right,
                    size: 25.toScreenHeight,
                    color: AppColor.neutral50,
                  )
                else
                   SizedBox(width: 18.toScreenWidth),
                 SizedBox(width: 15.toScreenWidth),
                Text(
                  widget.title,
                  style:AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
                ),
              ],
            ),
          ),
          if (expanded)
            Padding(
              padding: const EdgeInsets.only(left: 20, top: 6),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: widget.children
                    .map((child) => child is HierarchyTile
                    ? HierarchyTile(
                  title: (child).title,
                  indent: 0,
                  children: (child).children,
                )
                    : child)
                    .toList(),
              ),
            ),
        ],
      ),
    );
  }
}
class LeafTile extends StatelessWidget {
  final String title;

  const LeafTile({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 22, top: 4, bottom: 4),
      child: Text(
        title,
        style: const TextStyle(fontSize: 13, color: Colors.black87),
      ),
    );
  }
}
