// lib/screens/home/home.dart

import 'dart:convert';
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:iconify_flutter/iconify_flutter.dart';
import 'package:iconify_flutter/icons/carbon.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  /// From SharedPreferences
  String displayName = '';
  String? profileImageUrl; // this will hold photo_image (full URL)

  // Kural state
  String _kural = '';
  String _kuralDate = '';
  bool _loadingKural = false;
  String? _kuralError;

  static const String kuralApiUrl = 'https://rmbferodeunited.in/api/kural.php';

  final commumityList = [
    {
      "image": "assets/home/cele.png",
      "name": translate('home.celebrations'),
      "detail": translate('home.celebrations'),
      "route": "/celebrationtoday"
    },
    {
      "image": "assets/home/announcements.png",
      "name": translate('home.announcements'),
      "detail": translate('home.announcements'),
      "route": "/announcements"
    },
    {
      "image": "assets/home/meeting.png",
      "name": translate('home.meetingsevents'),
      "detail": translate('home.meetingsevents'),
      "route": "/visitors"
    },



    {
      "image": "assets/home/event.png",
      "name": translate('home.events'),
      "detail": translate('home.events'),
      "route": "/events"
    },


    {
      "image": "assets/home/collaborate.png",
      "name": translate('home.referrals'),
      "detail": translate("home.society_announcement"),
      "route": '/referrals'
    },

    {
      "image": "assets/home/leads.png",
      "name": translate('home.leads'),
      "detail": translate('home.leads'),
      "route": "/leaddisplay"
    },
    {
      "image": "assets/home/spec.png",
      "name": translate('home.specificasks'),
      "detail": translate("home.specificasks"),
      "route": '/SpecificAskList'
    },

    {
      "image": "assets/home/rtor.png",
      "name": translate('home.rtor'),
      "detail": translate('home.rtor'),
      "route": "/referral-to-referral"
    },
    {
      "image": "assets/home/helpDesk.png",
      "name": translate('home.testimonial'),
      "detail": translate('home.testimonial'),
      "route": '/helpDesk'
    },



    {
      "image": "assets/home/verticals.png",
      "name": translate('home.verticals'),
      "detail": translate("home.verticals"),
      "route": '/openvertical'
    },

    {
      "image": "assets/home/money.png",
      "name": translate('home.payment'),
      "detail": translate("home.payment"),
      "route": '/payment'
    },





  ];

  @override
  void initState() {
    super.initState();
    _loadUserFromPrefs();
    _loadCachedKuralThenFetch();
  }

  /// Very simple: just read `name` and `photo_image` keys.
  Future<void> _loadUserFromPrefs() async {
    final prefs = await SharedPreferences.getInstance();

    if (kDebugMode) {
      final keys = prefs.getKeys();
      debugPrint('DEBUG | SharedPrefs keys (${keys.length}):');
      for (final k in keys) {
        debugPrint('  $k: ${prefs.get(k)}');
      }
    }

    final name = (prefs.getString('name') ?? '').trim();
    final photo = (prefs.getString('photo_image') ?? '').trim();

    if (kDebugMode) {
      debugPrint('DEBUG | _loadUserFromPrefs -> name="$name", photo_image="$photo"');
    }

    if (!mounted) return;
    setState(() {
      displayName = name;
      profileImageUrl = photo.isNotEmpty ? photo : null;
    });

    if (kDebugMode) {
      debugPrint(
          'DEBUG | final displayName="$displayName", profileImageUrl="$profileImageUrl"');
    }
  }

  /// Load cached kural first (if any), then try network fetch.
  Future<void> _loadCachedKuralThenFetch() async {
    final prefs = await SharedPreferences.getInstance();
    final cachedKural = prefs.getString('daily_kural') ?? '';
    final cachedDate = prefs.getString('daily_kural_date') ?? '';
    if (mounted) {
      setState(() {
        _kural = cachedKural;
        _kuralDate = cachedDate;
      });
    }
    await _fetchDailyKural();
  }

  Future<void> _fetchDailyKural() async {
    setState(() {
      _loadingKural = true;
      _kuralError = null;
    });

    try {
      final uri = Uri.parse(kuralApiUrl);
      final response = await http.get(uri);

      if (response.statusCode != 200) {
        throw Exception('HTTP ${response.statusCode}');
      }

      final decoded = json
          .decode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;

      final kuralText = (decoded['kural'] ?? '').toString();
      final kuralDate = (decoded['date'] ?? '').toString();

      if (kuralText.isEmpty) {
        throw Exception('Empty kural in response');
      }

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('daily_kural', kuralText);
      await prefs.setString('daily_kural_date', kuralDate);

      if (mounted) {
        setState(() {
          _kural = kuralText;
          _kuralDate = kuralDate;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _kuralError = 'Failed to load kural';
        });
      }
      if (kDebugMode) debugPrint('DEBUG | _fetchDailyKural error: $e');
    } finally {
      if (mounted) {
        setState(() {
          _loadingKural = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      extendBody: true,
      appBar: AppBar(
        titleSpacing: 20.0,
        backgroundColor: whiteColor,
        elevation: 0,
        automaticallyImplyLeading: false,
        toolbarHeight: 65.0,
        title: header(),
        actions: [notificationButton(context)],
      ),
      body: ListView(
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.only(bottom: fixPadding * 9.5),
        children: [
          Container(
            padding: const EdgeInsets.fromLTRB(
              fixPadding * 2.0,
              0.0,
              fixPadding * 2.0,
              fixPadding * 2.0,
            ),
            color: whiteColor,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                banner(size),
                communityTitle(),
              ],
            ),
          ),
          communityListContent(size),
        ],
      ),
      floatingActionButton: kDebugMode
          ? FloatingActionButton(
        tooltip: 'Re-load SharedPrefs (debug)',
        child: const Icon(Icons.refresh),
        onPressed: () async {
          await _loadUserFromPrefs();
          final prefs = await SharedPreferences.getInstance();
          debugPrint('DEBUG | (on-demand) SharedPrefs snapshot:');
          for (final k in prefs.getKeys()) {
            debugPrint('   $k -> ${prefs.get(k)}');
          }
          if (!mounted) return;
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('SharedPrefs reloaded (check console)'),
            ),
          );
        },
      )
          : null,
    );
  }

  Widget notificationButton(BuildContext context) {
    return IconButton(
      onPressed: () {
        Navigator.pushNamed(context, '/notification');
      },
      icon: Stack(
        children: [
          const Iconify(Carbon.notification),
          Positioned(
            right: 1,
            top: 2,
            child: Container(
              height: 8,
              width: 8,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: redColor,
                border: Border.all(color: whiteColor, width: 1),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget communityListContent(Size size) {
    return Container(
      color: f6f3Color,
      child: GridView.builder(
        shrinkWrap: true,
        padding: const EdgeInsets.all(fixPadding * 2.0),
        physics: const NeverScrollableScrollPhysics(),
        itemCount: commumityList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: fixPadding * 2.0,
          crossAxisSpacing: fixPadding * 2.0,
          childAspectRatio: size.width / (size.height / 2.9),
        ),
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              if (commumityList[index]['route'] != null) {
                Navigator.pushNamed(
                  context,
                  commumityList[index]['route'].toString(),
                );
              }
            },
            child: Container(
              padding: const EdgeInsets.only(
                left: fixPadding,
                right: fixPadding,
                top: fixPadding,
              ),
              decoration: BoxDecoration(
                color: whiteColor,
                borderRadius: BorderRadius.circular(5.0),
                boxShadow: [
                  BoxShadow(
                    color: shadowColor.withOpacity(0.1),
                    blurRadius: 12.0,
                    offset: const Offset(0, 6),
                  )
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: fixPadding * 0.3,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          commumityList[index]['name'].toString(),
                          style: semibold16Black33,
                          overflow: TextOverflow.ellipsis,
                        ),
                        heightBox(2.0),
                        Text(
                          commumityList[index]['detail'].toString(),
                          style: medium12Grey.copyWith(height: 1.2),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  const Spacer(),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Image.asset(
                        commumityList[index]['image'].toString(),
                        height: size.width * 0.12,
                        width: size.width * 0.12,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget communityTitle() {
    return Text(
      getTranslate(context, 'home.community'),
      style: semibold16Primary,
    );
  }

  Widget banner(Size size) {
    return Container(
      height: 170,
      width: double.maxFinite,
      clipBehavior: Clip.hardEdge,
      margin: const EdgeInsets.only(
        bottom: fixPadding * 2.0,
        top: fixPadding,
      ),
      decoration: BoxDecoration(
        color: primaryColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: shadowColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 2),
          )
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 6.0,
            color: primaryColor,
          ),
          Expanded(
            child: Container(
              color: whiteColor,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      const Color(0xFF74ABCE),
                      const Color(0xFFADD3EB).withOpacity(0.5),
                    ],
                  ),
                  color: whiteColor,
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(fixPadding),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "திருக்குறள்",
                              style: semibold14White.copyWith(
                                decoration: TextDecoration.underline,
                                fontWeight: FontWeight.bold,
                                color: const Color(0xFF0B3D91),
                              ),
                            ),
                            heightBox(12.0),
                            _buildKuralArea(),
                          ],
                        ),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      /*children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: fixPadding * 1.3,
                            vertical: fixPadding * 0.4,
                          ),
                          color: primaryColor,
                          alignment: Alignment.center,
                          child: Text(
                            getTranslate(context, 'home.new'),
                            style: semibold12White,
                          ),
                        ),
                        const SizedBox(height: 12.0),
                        const SizedBox(height: 12.0),
                        const SizedBox(
                          height: 75,
                        ),
                      ],*/
                    )
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildKuralArea() {
    const Color kuralColor = Color(0xFF064E3B);

    if (_loadingKural) {
      return const SizedBox(
        height: 48,
        child: Center(child: CircularProgressIndicator()),
      );
    }

    if (_kural.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            _kural,
            style: medium14White.copyWith(
              color: kuralColor,
              fontWeight: FontWeight.bold,
            ),
            maxLines: 4,
            overflow: TextOverflow.ellipsis,
            textScaleFactor: 1.0,
          ),
          heightBox(12.0),
        ],
      );
    }

    const placeholder =
        "Rotary Means Business Fellowship Shortly Called as RMBF .";
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          placeholder,
          style: medium14White.copyWith(
            color: kuralColor,
            fontWeight: FontWeight.bold,
          ),
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ),
        heightBox(12.0),
        if (_kuralError != null)
          Text(
            _kuralError!,
            style: semibold12White.copyWith(color: Colors.yellowAccent),
          )
        else
          const SizedBox.shrink(),
      ],
    );
  }

  /// Header with Welcome & photo_image from SharedPreferences.
  Widget header() {
    final nameToShow = displayName.isNotEmpty ? displayName : 'Guest';
    final welcomeText = 'Welcome, $nameToShow';

    final ImageProvider<Object> profileImageProvider =
    (profileImageUrl != null && profileImageUrl!.isNotEmpty)
        ? NetworkImage(profileImageUrl!)
    as ImageProvider<Object> // use URL from photo_image
        : const AssetImage("assets/home/profile-image.png");

    return Row(
      children: [
        Container(
          height: 50.0,
          width: 50.0,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: whiteColor,
            border: Border.all(color: whiteColor, width: 2),
            boxShadow: [
              BoxShadow(
                color: shadowColor.withOpacity(0.2),
                blurRadius: 6.0,
              ),
            ],
            image: DecorationImage(
              image: profileImageProvider,
              fit: BoxFit.cover,
            ),
          ),
        ),
        widthSpace,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                welcomeText,
                style: semibold18Primary,
              ),
              height5Space,
              FutureBuilder(
                future: SharedPreferences.getInstance(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return const Text(
                      "",
                      style: medium14Grey,
                    );
                  }

                  final prefs = snapshot.data as SharedPreferences;
                  final team = prefs.getString('company_name') ?? '';
                  final position = prefs.getString('business_type') ?? '';

                  final combined = team.isNotEmpty && position.isNotEmpty
                      ? '$team - $position'
                      : team.isNotEmpty
                      ? team
                      : position;

                  return Text(
                    combined,
                    style: medium14Grey,
                  );
                },
              )
            ],
          ),
        ),
      ],
    );
  }
}
