import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../api/api_auth_provider.dart';

@RoutePage()
class LandingPage extends StatefulWidget {
  const LandingPage({super.key});

  @override
  State<LandingPage> createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();
  var data = {};
  var lic = {};
  var languages = [];
  var promo = [];
  bool isLoading = true;
  String accessCode = '';
  String locale = 'id';

  getData() async{
    try {
      lic = await U.getLicense();
      data = await _apiAuthProvider.getDataNoAuth('/api/landingPage/config');
      promo = await _apiAuthProvider.getDataNoAuth('/api/landingPage/promo');
      isLoading = false;
      setState((){});
    }catch(e){
      print(e.toString());
    }
  }

  setLang(List<dynamic> l){
    if(l.isNotEmpty){
      l.forEach((v){
        languages.add({
          "val": v,
          "icon": '$v.svg',
          'label': v.toUpperCase()
        });
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    accessCode = U.getAccessCode()!;
    getData().then((t){
      setLang(lic['_validLang']);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    locale = context.locale.toString();
    return isLoading ? Center(child: CircularProgressIndicator(),) : Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        title: Row(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(
                  horizontal: 8.0, vertical: 8.0),
              child: Image.network(getImageUrl(data['logo']), height: 36,),
            ),
            Text(data['title'], style: TextStyle(fontWeight: FontWeight.w600),),
          ],
        ),
        actions: [
          Container(
            decoration: BoxDecoration(
              // border: Border.all(),
                borderRadius: BorderRadius.all(Radius.circular(12))
            ),
            padding: EdgeInsets.only(right: 16),
            child: ddLang(context)
          )
        ],
      ),
      body: LayoutBuilder(
          builder: (BuildContext context, constraint) {
            return SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: constraint.maxWidth,
                    child: Image.network(getImageUrl(data['background-url'])),
                  ),
                  SizedBox(height: 24,),
                  container(label(data['content']['title'][locale])),
                  container(Text(data['content']['description'][locale])),
                  promos(promo),
                  cta(data['cta'], () => context.navigateToPath('/app/$accessCode/login')),
                  connectUs(data)
                ],
              ),
            );
          }
      ),
    );
  }

  getByLang(String label){
    String val = '';
    switch (locale){
      case 'id':
        val = label;
        break;
      case 'en':
        val = '${label}En';
        break;
      default:
        val = '_$label${locale[0].toUpperCase()}${locale.substring(1)}';
        break;
    }
    // print(val);
    return val;
  }

  ddLang(BuildContext context){
    String selectedValue = context.locale.toString();
    List<dynamic> items = languages;

    return DropdownButton<String>(
      value: selectedValue,
      elevation: 0,
      underline: SizedBox(),
      focusColor: Color(0x0000ffff),
      items: items.map((item) {
        return DropdownMenuItem<String>(
          value: item['val'],
          child: SizedBox(
            width: 52,
            child: Row(
              children: [
                SvgPicture.network(getImageUrl(item['icon']), width: 16, height: 16,),
                // Image.network(getImage(item['icon']), width: 24, height: 24,),
                SizedBox(width: 4,),
                Text(item['label']),
              ],
            ),
          ),
        );
      }).toList(),
      onChanged: (newValue) {
        // print(newValue);
        context.setLocale(Locale(newValue!));
        setState(() {
          selectedValue = newValue;
        });
      },
    );

  }

  getImageUrl<String>(String filename){
    return '${_apiAuthProvider.baseUrl}${U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))}/assets/landingPage/images/$filename';
  }

  frameImg(String img){
    return Container(
      height: 240,
      decoration: BoxDecoration(
          image: DecorationImage(image: NetworkImage(img), fit: BoxFit.cover),
          borderRadius: BorderRadius.all(Radius.circular(16))
      ),
    );
  }

  container(Widget child){
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 6,
        horizontal: 16,
      ),
      child: child,
    );
  }

  label(String txt, {double size = 24}){
    return Text(
      txt,
      style: TextStyle(
          fontWeight: FontWeight.w700,
          fontSize: size
      ),
    );
  }

  promos(data){
    return Column(
      children: List.generate(data.length, (i){
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 24,),
            container(frameImg(data[i]['image'])),
            container(label(data[i][getByLang('title')], size: 18)),
            container(Text(data[i][getByLang('description')])),
            SizedBox(height: 12,),
          ],
        );
      }),
    );
  }

  cta(d, cb){
    var h = 220.0;
    return Stack(
      children: [
        Container(
          height: h,
          decoration: BoxDecoration(
            image: DecorationImage(image: NetworkImage(getImageUrl(d['image'])), fit: BoxFit.cover),
          ),
          // color: Colors.black.withValues(alpha: 0.5),
        ),
        Container(
          height: h,
          color: Colors.black.withValues(alpha: 0.5),
        ),
        Container(
          padding: EdgeInsets.all(24.0),
          height: h,
          child: Column(
            spacing: 8,
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                d['title'][locale],
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.w600
                ),
              ),
              Text(d['description'][locale], style: TextStyle(color: Colors.white),),
              SizedBox(height: 16,),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.all(20),
                  backgroundColor: Color(0xFFFFA800), // Background color of the button
                  foregroundColor: Colors.white, // Color of the text and icon
                ),
                onPressed: cb,
                child: Text(d['label'][locale]),
              )
            ],
          ),
        )
      ],
    );
  }

  connectUs(data){
    var dt = data['link'];
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 24, horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            data['contact'][locale],
            style: TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.w700
            ),
          ),
          SizedBox(height: 24,),
          Wrap(
            runSpacing: 20.0,
            children: List.generate(dt.length, (i){
              return LayoutBuilder(builder: (BuildContext context, constraint){
                return SizedBox(
                  width: constraint.maxWidth/2-10,
                  child: GestureDetector(
                    onTap: dt[i]['url'] == '' ? (){} : () async {
                      var url = Uri.parse(dt[i]['url']);
                      await canLaunchUrl(url) ? await launchUrl(url) : print('Could not launch $url');
                    },
                    child: Row(
                      children: [
                        Image.network(getImageUrl(dt[i]['icon']), width: 24, height: 24,),
                        SizedBox(width: 12,),
                        Text(dt[i]['label'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),)
                      ],
                    ),
                  ),
                );
              });
            }),
          ),
          SizedBox(height: 24,),
          Divider(),
          Padding(
            padding: EdgeInsets.only(top: 8),
            child: Center(
              child: Text(data['footer']),
            ),
          )
        ],
      ),
    );
  }
}
