import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hub/features/module/index.dart';
import 'package:hub/flutter_flow/custom_functions.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/features/local/index.dart';

class LocalProfileComponentWidget extends StatefulWidget {
  const LocalProfileComponentWidget({super.key});

  @override
  State<LocalProfileComponentWidget> createState() =>
      _LocalProfileComponentWidgetState();
}

class _LocalProfileComponentWidgetState
    extends State<LocalProfileComponentWidget> {
  bool _isLoading = false;

  Future retrieveProfileInfo() async {
    setState(() {
      _isLoading = true;
    });
    await LocalsRepositoryImpl().select(context);
    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<LicenseStatus>(
      stream: LocalsRepositoryImpl.stream,
      builder: (context, snapshot) {
        final textScaler = MediaQuery.textScalerOf(context);
        final double baseFontSize = 14.0;
        final double scaledFontSize = baseFontSize * textScaler.scale(1);
        final double limitedFontSize =
            scaledFontSize > 20 ? 12 : scaledFontSize;
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data! == false) {
          return BlocBuilder<LocalProfileBloc, LocalProfileState>(
            builder: (context, state) {
              return _buildDefaultLocalProfile(context, limitedFontSize);
            },
          );
        }

        return BlocBuilder<LocalProfileBloc, LocalProfileState>(
          builder: (context, state) {
            return _buildAsyncLocalProfile(context, state, limitedFontSize);
          },
        );
      },
    );
  }

  Container _buildDefaultLocalProfile(
      BuildContext context, double limitedFontSize) {
    return Container(
      decoration: const BoxDecoration(),
      child: Align(
        alignment: const AlignmentDirectional(0.0, -1.0),
        child: Material(
          color: Colors.transparent,
          elevation: 0.0,
          child: Container(
            width: double.infinity,
            height: 119.0,
            decoration: BoxDecoration(
              color: FlutterFlowTheme.of(context).primary,
              border: Border.all(
                color: FlutterFlowTheme.of(context).primary,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Align(
                  alignment: const AlignmentDirectional(-1.0, 0.0),
                  child: Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: InkWell(
                        key: const Key(
                            'DefaultLocalProfileComponentWidget_InkWell'),
                        splashColor: Colors.transparent,
                        focusColor: Colors.transparent,
                        hoverColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        onTap: _isLoading ? null : retrieveProfileInfo,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(200.0),
                          child: CachedNetworkImage(
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            imageUrl: 'assets/images/home.png',
                            width: 80.0,
                            height: 80.0,
                            fit: BoxFit.cover,
                            alignment: const Alignment(0.0, 0.0),
                            placeholder: (context, url) =>
                                Image.asset('assets/images/home.png'),
                            errorListener: (_) =>
                                Image.asset('assets/images/home.png'),
                            errorWidget: (_, __, ___) =>
                                Image.asset('assets/images/home.png'),
                          ),
                        )),
                  ),
                ),
                Expanded(
                  child: Tooltip(
                    message: FFLocalizations.of(context).getVariableText(
                      ptText: 'SEM LOCAL VINCULADO',
                      enText: 'NO LINKED LOCAL',
                    ),
                    child: Text(
                      FFLocalizations.of(context).getVariableText(
                        ptText: 'SEM LOCAL VINCULADO',
                        enText: 'NO LINKED LOCAL',
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: FlutterFlowTheme.of(context).labelMedium.override(
                            fontFamily: 'Nunito',
                            color: FlutterFlowTheme.of(context).info,
                            fontSize: limitedFontSize,
                            letterSpacing: 0.0,
                            fontWeight: FontWeight.w500,
                            useGoogleFonts:
                                GoogleFonts.asMap().containsKey('Nunito'),
                          ),
                    ),
                  ),
                ),
              ]
                  .divide(const SizedBox(width: 20.0))
                  .addToStart(const SizedBox(width: 20.0))
                  .addToEnd(const SizedBox(width: 20.0)),
            ),
          ),
        ),
      ),
    );
  }

  Container _buildAsyncLocalProfile(
      BuildContext context, LocalProfileState state, double limitedFontSize) {
    return Container(
      decoration: const BoxDecoration(),
      child: Align(
        alignment: const AlignmentDirectional(0.0, -1.0),
        child: Material(
          color: Colors.transparent,
          elevation: 0.0,
          child: Container(
            width: double.infinity,
            height: 119.0,
            decoration: BoxDecoration(
              color: FlutterFlowTheme.of(context).primary,
              border: Border.all(
                color: FlutterFlowTheme.of(context).primary,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Align(
                  alignment: const AlignmentDirectional(-1.0, 0.0),
                  child: Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: InkWell(
                        key: const Key(
                            'AsyncLocalProfileComponentWidget_InkWell'),
                        splashColor: Colors.transparent,
                        focusColor: Colors.transparent,
                        hoverColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        onTap: _isLoading ? null : retrieveProfileInfo,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(200.0),
                          child: CachedNetworkImage(
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            imageUrl: valueOrDefault(
                                'https://freaccess.com.br/freaccess/Images/Clients/${state.cliUUID}.png',
                                'assets/images/home.png'),
                            width: 80.0,
                            height: 80.0,
                            fit: BoxFit.cover,
                            alignment: const Alignment(0.0, 0.0),
                            placeholder: (context, url) =>
                                Image.asset('assets/images/home.png'),
                            errorListener: (_) =>
                                Image.asset('assets/images/home.png'),
                            errorWidget: (_, __, ___) =>
                                Image.asset('assets/images/home.png'),
                          ),
                        )),
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Tooltip(
                        message: valueOrDefault<String>(
                          convertToUppercase(state.cliName),
                          FFLocalizations.of(context).getVariableText(
                            ptText: 'SEM LOCAL VINCULADO',
                            enText: 'NO LINKED LOCAL',
                          ),
                        ),
                        child: Text(
                          valueOrDefault<String>(
                            convertToUppercase(state.cliName),
                            FFLocalizations.of(context).getVariableText(
                              ptText: 'SEM LOCAL VINCULADO',
                              enText: 'NO LINKED LOCAL',
                            ),
                          ),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          style: FlutterFlowTheme.of(context)
                              .labelMedium
                              .override(
                                fontFamily: 'Nunito',
                                color: FlutterFlowTheme.of(context).info,
                                fontSize: limitedFontSize,
                                letterSpacing: 0.0,
                                fontWeight: FontWeight.w500,
                                useGoogleFonts:
                                    GoogleFonts.asMap().containsKey('Nunito'),
                              ),
                        ),
                      ),
                      Tooltip(
                        message:
                            valueOrDefault<String>(' ' + state.ownerName, ''),
                        child: Text(
                          valueOrDefault<String>(
                              state.ownerName.length > 30
                                  ? '${state.ownerName.substring(0, 20)}...'
                                  : state.ownerName,
                              ''),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          style: FlutterFlowTheme.of(context)
                              .labelMedium
                              .override(
                                fontFamily: 'Nunito',
                                color: FlutterFlowTheme.of(context).info,
                                fontSize: limitedFontSize,
                                letterSpacing: 0.0,
                                fontWeight: FontWeight.w500,
                                useGoogleFonts:
                                    GoogleFonts.asMap().containsKey('Nunito'),
                              ),
                        ),
                      ),
                    ],
                  ),
                ),
              ]
                  .divide(const SizedBox(width: 20.0))
                  .addToStart(const SizedBox(width: 20.0))
                  .addToEnd(const SizedBox(width: 20.0)),
            ),
          ),
        ),
      ),
    );
  }
}
