import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';

import '../../api/api_auth_provider.dart';
import '../../utils/extensions.dart';
import '../components/widgets.dart';

// State
class AssetState extends Equatable {
  final int idSelected;
  final List<dynamic> data;
  final List<dynamic> result;
  final String keyword;
  final int page;
  final bool isLoading;

  const AssetState({
    this.idSelected = -1,
    this.data = const [],
    this.result = const [],
    this.keyword = '',
    this.page = 0,
    this.isLoading = true,
  });

  AssetState copyWith({
    int? idSelected,
    List<dynamic>? data,
    List<dynamic>? result,
    String? keyword,
    int? page,
    bool? isLoading,
  }) {
    return AssetState(
      idSelected: idSelected ?? this.idSelected,
      data: data ?? this.data,
      result: result ?? this.result,
      keyword: keyword ?? this.keyword,
      page: page ?? this.page,
      isLoading: isLoading ?? this.isLoading,
    );
  }

  @override
  List<Object?> get props => [idSelected, data, result, keyword, page, isLoading];
}

// Cubit
class AssetCubit extends Cubit<AssetState> {
  AssetCubit() : super(const AssetState());

  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();

  void getData({String keyword = '', int page = 0}) async {
    String filter = keyword == '' ? '{"f":["1","EQ","1"]}' : '{"or":[{"f":["name","LIKE","%$keyword%"]},{"f":["description","LIKE","%$keyword%"]}]}';
    final params = {
      "select": "id, code, name, description, image, status",
      "sort": "name:ASC",
      "filter": filter,
      "size": "10",
      "page": "$page"
    };
    final rawData = await _apiAuthProvider.getData('/api/assets/findData', params);
    final data = rawData['_embedded']['assets'];

    if (data.isEmpty && page != 0) return;
    var finalData = page == 0 ? data : state.data + data;

    emit(state.copyWith(data: finalData, keyword: keyword, page: page, isLoading: false));
  }

  void toggleSelection(int id) {
    final newID = id;
    final res = state.data.where((element) => element['id'] == newID).toList();

    emit(state.copyWith(idSelected: newID, result: res));
  }

  void search(String keyword) {
    getData(keyword: keyword, page: 0);

    emit(state.copyWith(isLoading: true, data: []));
  }

  void loadNextPage() {
    getData(keyword: state.keyword, page: state.page + 1);
  }
}

class PickupAsset extends StatefulWidget {
  final bool web;
  const PickupAsset({super.key, required this.web});

  @override
  State<PickupAsset> createState() => _PickupAssetState();
}

class _PickupAssetState extends State<PickupAsset> {
  final ScrollController _scrollController = ScrollController();

  @override
  initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }
  void _onScroll(){
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      context.read<AssetCubit>().loadNextPage();
    }
  }
  @override
  dispose() {
    _scrollController.dispose();
    _scrollController.removeListener(_onScroll);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var result = [];
    EdgeInsets padding = EdgeInsets.symmetric(vertical: 10.0);
    if (widget.web) padding = EdgeInsets.symmetric(vertical: 25.0, horizontal: 100.0);

    return Scaffold(
      appBar: !widget.web ? appBarTemplate(context: context, title: "assetList".tr()) : PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: SafeArea(
        child: Column(
          children: [
            if(widget.web) Container(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('assetList'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                  GestureDetector(
                    child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                    onTap: ()=>navigateBack(context),
                  ).withHover()
                ],
              ),
            ),
            divider(),
            Expanded(
              child: BlocBuilder<AssetCubit, AssetState>(
                builder: (context, state) {
                  result = state.result;
                  return Column(
                    children: [
                      Container(
                        color: Colors.white,
                        child: Padding(
                          padding: padding,
                          child: WidgetComponent.searchBar(initialValue: state.keyword, onSearch: (val) {
                            context.read<AssetCubit>().search(val);
                          }),
                        ),
                      ),
                      if(state.isLoading) Expanded(child: Center(child: const CircularProgressIndicator(),)),
                      if(state.data.isEmpty && state.page == 0 && !state.isLoading) Center(child: Text('noDataText'.tr()),),
                      if(state.data.isNotEmpty) Expanded(
                        child: Padding(
                          padding: padding,
                          child: ListView.builder(
                              controller: _scrollController,
                              shrinkWrap: true,
                              itemCount: state.data.length,
                              itemBuilder: (context, index) {
                                final asset = state.data[index];
                                String imgUrl = asset['image'] != null ? asset['_mobileImage'] : '';

                                return ImageRadioTile(
                                  title: asset['name'],
                                  description: asset['description'] ?? '-',
                                  imageUrl: imgUrl,
                                  isSelected: asset['id'] == state.idSelected,
                                  onTap: () => context.read<AssetCubit>().toggleSelection(asset['id']),
                                );
                              }
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            Container(
              child: WidgetComponent.bottomButtonGroup(
                actionSave: () {
                  if(result.isNotEmpty) {
                    Navigator.pop(context, result);
                  } else {
                    WidgetComponent.alert('noDataSelected'.tr(), true, context);
                  }
                },
                actionCancel: () => Navigator.pop(context),
                submitLabel: 'selectAsset'.tr(),
                cancelLabel: 'textCancel'.tr(),
                padding: widget.web ? EdgeInsets.symmetric(horizontal: 100, vertical: 15) : EdgeInsets.symmetric(horizontal: 15, vertical: 15)
              ),
            ),
          ],
        ),
      ),
    );
  }
}


// Here ImageRadioTile
class ImageRadioTile extends StatelessWidget {
  final String title;
  final String description;
  final String imageUrl;
  final bool isSelected;
  final VoidCallback onTap;

  const ImageRadioTile({
    super.key,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.isSelected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      spacing: 5,
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white
            ),
            padding: const EdgeInsets.all(15.0),
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.0),
                  child: imageUrl != '' ? Image.network(
                    imageUrl,
                    width: 80,
                    height: 64,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) =>
                    const Icon(Icons.broken_image, size: 60, color: Colors.grey),
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return const SizedBox(
                        width: 80,
                        height: 64,
                        child: Center(child: CupertinoActivityIndicator()),
                      );
                    },
                  ) : const Icon(Icons.broken_image, size: 80, color: Colors.grey),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        description,
                        style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 12),
                Icon(
                  isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
                  color: isSelected ? primaryColor : Colors.grey.shade400,
                ),
              ],
            ),
          ),
        ).withHover(),
        SizedBox(height: 5,),
        // WidgetComponent.boxSeparator(),
      ],
    );
  }
}
