import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/context_extension.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/generic_attachment_model.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

class AssetDeliveryAttachmentView extends StatefulWidget {
  final int? tableItemId;
  final int? attachmentType;
  bool viewOnly = false;
  final List<GenericAttachmentModel> attachmentList;

  AssetDeliveryAttachmentView({
    super.key,
    required this.attachmentList,
    this.viewOnly = false,
    this.attachmentType,
    this.tableItemId,
  });

  @override
  State<AssetDeliveryAttachmentView> createState() => _AssetDeliveryAttachmentViewState();
}

class _AssetDeliveryAttachmentViewState extends State<AssetDeliveryAttachmentView> {
  List<GenericAttachmentModel> _attachments = [];
  bool isLoading = false;
  late AssetDeliveryProvider assetDeliveryProvider;

  @override
  void initState() {
    super.initState();
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
  }

  void getInitialData() async {
    ///get previoues Attachment from Apis.
    // isLoading = true;
    setState(() {});
    _attachments = widget.attachmentList;
    // await assetDeliveryProvider.getAttachments(tableItemId: widget.tableItemId, attachmentType: widget.attachmentType);
    // isLoading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    log('value ${widget.attachmentType}');
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: DefaultAppBar(
        title: 'Attachments'.addTranslation,
        onBackPress: () {
          Navigator.pop(context);
        },
      ),
      body: widget.attachmentList.isEmpty
          ? const NoDataFound().center
          : Column(
              children: [
                Flexible(
                  fit: FlexFit.loose, // ✅ expands only as much as needed
                  child: Column(
                    children: [
                      widget.attachmentType == 5 && !widget.viewOnly
                          ? AttachmentPicker(
                              label: context.translation.attachments,
                              attachment: _attachments,
                              buttonColor: AppColor.primary10,
                              onlyImages: false,
                              showAsListView: true,
                              buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10),
                              onChange: (attachment) {},
                            ).toShadowContainer(
                              context,
                              borderRadius: 20,
                              padding: 12,
                              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            )
                          : FilesList(images: _attachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []).toShadowContainer(
                              context,
                              borderRadius: 20,
                              padding: 12,
                              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            ),
                    ],
                  ),
                ),
                if (widget.attachmentType == 5 && !widget.viewOnly)
                  FooterActionButton.footerContainer(
                    context: context,
                    child: AppFilledButton(
                      buttonColor: AppColor.primary10,
                      label: 'Save'.addTranslation,
                      maxWidth: true,
                      onPressed: _onSavePressed,
                    ),
                  ),
              ],
            ),
    );
  }

  Future<void> _onSavePressed() async {
    final List<GenericAttachmentModel> attachmentPayload = _attachments.map((item) {
      final String name = CMRequestUtils.isLocalUrl(item.name ?? '') ? '${item.name?.split("/").last}|${base64Encode(File(item.name!).readAsBytesSync())}' : item.name ?? '';

      return GenericAttachmentModel(
        id: item.id ?? 0,
        name: name,
        documentType: item.documentType,

      );
    }).toList();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const AppLazyLoading(),
    );

    final payload = {
      'assetDeliveryExternalDeliveryId': widget.tableItemId,
      'attachments': attachmentPayload,
    };

    final status = await assetDeliveryProvider.saveAttachment(payload: payload);

    Navigator.pop(context);

    if (status) {
      Navigator.pop(context);
    }
  }
}
