import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:hub/src/features/hub/presentation/state/hub_view_model.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:legacy_shared/legacy_shared.dart';
import 'package:navigation/navigation.dart';
import 'package:sf_localizations/sf_localizations.dart';
import 'package:utils/utils.dart';

class HubScreen extends ConsumerWidget {
  final NavigationContract navigationContract;
  final GoRouterState routerState;

  const HubScreen({
    super.key,
    required this.navigationContract,
    required this.routerState
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = ref.watch(themePortProvider);

    final viewState = ref.watch(hubViewModelProvider);
    final viewModel = ref.read(hubViewModelProvider.notifier);

    return Scaffold(
      backgroundColor: theme.getColorFor(ThemeCode.backgroundPrimary),
      body: SafeArea(
        child: Container(
        padding: EdgeInsets.symmetric(horizontal: 14),
          child: Column(
            children: [
              SizedBox(height: SizeUtils.getByScreen(small: 8, big: 4)),
              Stack(
                children: [
                  SizedBox(
                    height: SizeUtils.getByScreen(small: 36, big: 36),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Image.asset('assets/images/ui/iso_sf.png',
                          height: SizeUtils.getByScreen(small: 18, big: 18)),
                        SizedBox(width: SizeUtils.getByScreen(small: 8, big: 4)),
                        SizedBox(
                          width: SizeUtils.getByScreen(small: 104, big: 100),
                          height: 32,
                          child: CustomDropdown(
                            items: viewState.devices.map((DeviceEntity device)=>
                                Text(device.carrierName)
                              ).toList(),
                            values: viewState.devices,
                            value: viewState.selectedDevice,
                            onChanged: (device){viewModel.setSelectedDevice(device);},
                            height: 32,
                            color: Colors.transparent,
                            padding: EdgeInsets.zero,
                          ),
                        ),
                      ]
                    )
                  ),
                  Center(
                    child: SvgPicture.asset('assets/images/ui/logo_sf.svg',
                      height: SizeUtils.getByScreen(small: 36, big: 36))
                  ),
                ],
              ),
              SizedBox(height: SizeUtils.getByScreen(small: 12, big: 14)),
              Expanded(child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AppSectionButton(
                      onPressed: (){navigationContract.pushTo(AppRoutes.customerService);},
                      icon: SFIcons.customerService,
                      text: I18n.customerService),
                    SizedBox(height: SizeUtils.getByScreen(small: 8, big: 7)),
                    AppSectionButton(
                      onPressed: (){navigationContract.pushTo(AppRoutes.dashboardHome);},
                      icon: SFIcons.payments,
                      text: I18n.sfPay),
                    SizedBox(height: SizeUtils.getByScreen(small: 8, big: 7)),
                    AppSectionButton(
                      onPressed: (){navigationContract.pushTo(AppRoutes.dashboardFunctions);},
                      icon: SFIcons.functions,
                      text: I18n.functions),
                    SizedBox(height: SizeUtils.getByScreen(small: 8, big: 7)),
                    AppSectionButton(
                      onPressed: (){navigationContract.pushTo(AppRoutes.accountSettings);},
                      icon: Icons.manage_accounts_outlined,
                      text: I18n.accountSettings),
                    SizedBox(height: SizeUtils.getByScreen(small: 8, big: 7)),
                    AppSectionButton(
                      onPressed: (){},
                      icon: Icons.settings_outlined,
                      text: I18n.deviceSettings),

                    SizedBox(height: SizeUtils.getByScreen(small: 16, big: 22)),
                    Text(context.translate(I18n.watchesOnMap),
                      style: TextStyle(
                        fontSize: SizeUtils.getByScreen(small: 20, big: 19),
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF588EA5),
                      ),
                    ),
                    SizedBox(height: SizeUtils.getByScreen(small: 4, big: 8)),
                    SizedBox(
                      height: SizeUtils.getByScreen(small: 200, big: 300),
                      child: Minimap(),
                    ),
                    SizedBox(height: SizeUtils.getByScreen(small: 14, big: 13)),
                  ],
                ),
              ))
            ],
          ),
        ),
      ),
    );
  }
}

class AppSectionButton extends ConsumerWidget {

  final GestureTapCallback onPressed;
  final IconData icon;
  final String text;

  const AppSectionButton({
    required this.onPressed,
    required this.icon,
    required this.text,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = ref.read(themePortProvider);

    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: SizeUtils.getByScreen(
          small: EdgeInsets.symmetric(horizontal: 22, vertical: 10),
          big: EdgeInsets.symmetric(horizontal: 21, vertical: 8)
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(SizeUtils.getByScreen(small: 12, big: 18))),
          color: theme.getColorFor(ThemeCode.backgroundSecondary),
        ),
        child: Row(
          children: [
            Container(
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: theme.getColorFor(ThemeCode.backgroundPrimary),
              ),
              padding: EdgeInsets.all(SizeUtils.getByScreen(small: 4, big: 12)),
              child: Icon(icon,
                size: SizeUtils.getByScreen(small: 40, big: 44),
                color: Color(0xFF588EA5),
                weight: 30,
              ),
            ),
            SizedBox(width: SizeUtils.getByScreen(small: 16, big: 15)),
            Expanded(
              child: Text(context.translate(text),
                style: TextStyle(
                  fontSize: SizeUtils.getByScreen(small: 18, big: 19),
                  fontWeight: FontWeight.w500
                )
              )
            )
          ],
        ),
      )
    );
  }

}

class Minimap extends ConsumerWidget {

  IconData batteryToIcon(int battery) {
    if (battery < 15) return Icons.battery_0_bar;
    if (battery < 30) return Icons.battery_1_bar;
    if (battery < 45) return Icons.battery_2_bar;
    if (battery < 60) return Icons.battery_3_bar;
    if (battery < 75) return Icons.battery_4_bar;
    if (battery < 90) return Icons.battery_5_bar;
    return Icons.battery_6_bar;
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = ref.watch(themePortProvider);

    final viewState = ref.watch(hubViewModelProvider);
    final viewModel = ref.read(hubViewModelProvider.notifier);

    final battery = viewState.selectedPosition?.ncell ?? 0;
    final IconData batteryIcon = batteryToIcon(battery);

    final positionDate = DateTime.fromMillisecondsSinceEpoch(viewState.selectedPosition?.positionDate ?? 0);

    return FlutterMap(
      mapController: viewModel.mapController,
      options: MapOptions(
        initialCenter: LatLng(45.32833189648895, -3.0830872665435085),
        initialZoom: 15,
        keepAlive: true,
      ),
      children: [
        TileLayer(
          urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
          userAgentPackageName: 'com.savefamily.sf_platform',
        ),
        MarkerLayer(markers: [if (viewState.selectedPosition != null)
          Marker(
            point: LatLng(viewState.selectedPosition!.latitude, viewState.selectedPosition!.longitude),
            width:  200,
            height: 145,
            child: Align(
              alignment: Alignment.topCenter,
              child: SvgPicture.asset('assets/images/ui/location.svg',
                height: 80)
            ),
            rotate: true,
          )
        ]),
        if (viewState.selectedPosition != null)
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: SizeUtils.getByScreen(small: 60, big: 58),
              width: SizeUtils.getByScreen(small: 300, big: 298),
              margin: EdgeInsets.only(bottom: SizeUtils.getByScreen(small: 20, big: 16)),
              decoration: BoxDecoration(
                color: theme.getColorFor(ThemeCode.backgroundPrimary),
                borderRadius: BorderRadius.all(Radius.circular(SizeUtils.getByScreen(small: 9, big: 8)))
              ),
              child: Row(
                children: [
                  Icon(SFIcons.location,
                    size: SizeUtils.getByScreen(small: 40, big: 38),
                    color: Color(0xFF588EA5),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: SizeUtils.getByScreen(small: 250, big: 248),
                        child: Text('${viewState.selectedPosition!.address?.street}, '
                            '${viewState.selectedPosition!.address?.province}, '
                            '${viewState.selectedPosition!.address?.country}',
                          overflow: TextOverflow.ellipsis,
                        )
                      ),
                      Row(
                        children: [
                          Text('${positionDate.month.toString().padLeft(2, '0')}-'
                              '${positionDate.day.toString().padLeft(2, '0')} '
                              '${positionDate.hour.toString().padLeft(2, '0')}:'
                              '${positionDate.minute.toString().padLeft(2, '0')}:'
                              '${positionDate.second.toString().padLeft(2, '0')}',
                            style: TextStyle(
                              fontSize: SizeUtils.getByScreen(small: 12, big: 11)
                            ),
                          ),
                          if (viewState.selectedPosition!.networks.isNotEmpty)
                            Text(' | ${viewState.selectedPosition!.networks.first.signal}',
                              style: TextStyle(
                                  fontSize: SizeUtils.getByScreen(small: 12, big: 11)
                              ),
                            ),
                          Icon(batteryIcon),
                          Text('${viewState.selectedPosition!.ncell ?? 0}%',
                            style: TextStyle(
                              fontSize: SizeUtils.getByScreen(small: 12, big: 11)
                            ),
                          )
                        ],
                      )
                    ],
                  )
                ],
              ),
            ),
          )
      ],
    );
  }
}