import 'dart:convert';

import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:iconify_flutter/iconify_flutter.dart';
import 'package:iconify_flutter/icons/mi.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

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

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

class _HomeScreenState extends State<HomeScreen> {
  // Slider
  final PageController _sliderController =
  PageController(viewportFraction: 0.95);
  int _currentSlider = 0;

  // Header data
  String _name = '';
  String _vertical = '';
  String? _profilePhoto; // store RAW value from API / prefs
  bool _loadingHeader = true;

  // Example slider image list - replace these with your real assets
  final List<String> _sliderImages = [
    'assets/sliders/1.jpg',
    'assets/sliders/2.jpg',
    'assets/sliders/3.jpg',
    'assets/sliders/4.jpg',
    'assets/sliders/5.jpg',
  ];

  // TODO: Replace with your real API endpoint
  static const String _profileApiUrl =
      'https://example.com/api/profile'; // change this

  @override
  void initState() {
    super.initState();
    _loadProfileFromApi();
  }

  /// Build full profile photo URL using base path
  String? _buildProfilePhotoUrl(String? photo) {
    if (photo == null) return null;
    photo = photo.trim();
    if (photo.isEmpty) return null;

    // If already full URL, return as is
    if (photo.startsWith('http://') || photo.startsWith('https://')) {
      return photo;
    }

    // If accidentally stored as file:///..., strip that
    if (photo.startsWith('file://')) {
      photo = photo.substring('file://'.length);
    }

    // Remove leading slashes
    photo = photo.replaceFirst(RegExp(r'^/+'), '');

    // Default: it's just filename, prepend uploads base
    return 'https://gelite.asia/uploads/$photo';
  }

  /// Call API, save to SharedPreferences, update UI (no debug prints)
  Future<void> _loadProfileFromApi() async {
    final prefs = await SharedPreferences.getInstance();

    // Example: read a stored userId (change key to your usage)
    final userId = prefs.getString('user_id') ?? '';

    final uri = Uri.parse(_profileApiUrl);
    final headers = <String, String>{
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };

    final bodyJson = jsonEncode(<String, dynamic>{
      'user_id': userId,
    });

    try {
      final response =
      await http.post(uri, headers: headers, body: bodyJson);

      if (response.statusCode == 200 && response.body.isNotEmpty) {
        final decoded = jsonDecode(response.body) as Map<String, dynamic>;

        // If your API wraps data inside "data", adjust here
        final data = (decoded['data'] is Map<String, dynamic>)
            ? decoded['data'] as Map<String, dynamic>
            : decoded;

        final name = data['name']?.toString() ?? '';
        final vertical = data['vertical']?.toString() ?? '';
        final rawPhoto = data['profile_photo']?.toString();

        // Save RAW values to SharedPreferences
        await prefs.setString('name', name);
        await prefs.setString('vertical', vertical);
        if (rawPhoto != null) {
          await prefs.setString('profile_photo', rawPhoto);
        }

        if (!mounted) return;
        setState(() {
          _name = name;
          _vertical = vertical;
          _profilePhoto = rawPhoto;
          _loadingHeader = false;
        });
      } else {
        // If API fails, fallback to local prefs
        await _loadFromPrefsOnly(prefs);
      }
    } catch (_) {
      await _loadFromPrefsOnly(prefs);
    }
  }

  /// Only read from SharedPreferences (used as fallback)
  Future<void> _loadFromPrefsOnly(SharedPreferences prefs) async {
    final name = prefs.getString('name') ?? '';
    final vertical = prefs.getString('vertical') ?? '';
    final storedPhoto = prefs.getString('profile_photo'); // raw

    if (!mounted) return;
    setState(() {
      _name = name;
      _vertical = vertical;
      _profilePhoto = storedPhoto;
      _loadingHeader = false;
    });
  }

  @override
  void dispose() {
    _sliderController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final profileUrl = _buildProfilePhotoUrl(_profilePhoto);

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: whiteColor,
        centerTitle: false,
        titleSpacing: 20.0,
        title: _loadingHeader
            ? const Text(
          "GELITE",
          style: medium20Primary,
        )
            : Row(
          children: [
            // Profile Photo
            CircleAvatar(
              radius: 18,
              backgroundColor: Colors.grey.shade200,
              backgroundImage: (profileUrl != null)
                  ? NetworkImage(profileUrl)
                  : null,
              child: (profileUrl == null)
                  ? const Icon(
                Icons.person,
                color: primaryColor,
              )
                  : null,
            ),
            const SizedBox(width: 10),
            // Name + Vertical
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _name.isNotEmpty
                        ? "Welcome, $_name"
                        : "Welcome,",
                    style: medium16Primary,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  if (_vertical.isNotEmpty)
                    Text(
                      _vertical,
                      style: regular12Grey,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          IconButton(
            padding: const EdgeInsets.symmetric(
                horizontal: fixPadding * 2.0),
            onPressed: () {
              Navigator.pushNamed(context, '/notification');
            },
            icon: const Iconify(
              Mi.notification,
              color: primaryColor,
            ),
          )
        ],
      ),
      body: ListView(
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.only(top: fixPadding * 2.0),
        children: [
          // Single Slider
          Padding(
            padding: const EdgeInsets.symmetric(
                horizontal: fixPadding * 2.0),
            child: sliderWidget(
              controller: _sliderController,
              images: _sliderImages,
              onPageChanged: (index) =>
                  setState(() => _currentSlider = index),
            ),
          ),
          heightSpace,
          community(size),
        ],
      ),
    );
  }

  /// Reusable slider widget with indicators
  Widget sliderWidget({
    required PageController controller,
    required List<String> images,
    required Function(int) onPageChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 150.0,
          child: PageView.builder(
            controller: controller,
            itemCount: images.length,
            onPageChanged: onPageChanged,
            itemBuilder: (context, index) {
              final image = images[index];
              return GestureDetector(
                onTap: () {
                  // Optional: handle slider tap
                },
                child: Container(
                  margin:
                  const EdgeInsets.only(right: fixPadding),
                  decoration: BoxDecoration(
                    color: whiteColor,
                    borderRadius:
                    BorderRadius.circular(12.0),
                    boxShadow: boxShadow2,
                    image: DecorationImage(
                      image: AssetImage(image),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        height5Space,
        // Indicators
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: List.generate(
            images.length,
                (i) {
              final bool active = i == _currentSlider;
              return AnimatedContainer(
                duration:
                const Duration(milliseconds: 250),
                margin: const EdgeInsets.symmetric(
                    horizontal: 4.0),
                width: active ? 18.0 : 8.0,
                height: 8.0,
                decoration: BoxDecoration(
                  color: active
                      ? primaryColor
                      : Colors.grey.shade300,
                  borderRadius:
                  BorderRadius.circular(8.0),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  /// Community section with working navigation for birthday & celebration
  Widget community(Size size) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(
              horizontal: fixPadding * 2.0),
          child: Text(
            tr(context, 'home.community'),
            style: medium16Black,
          ),
        ),
        heightSpace,
        heightSpace,
        Container(
          width: double.maxFinite,
          padding: const EdgeInsets.symmetric(
            horizontal: fixPadding * 2.0,
            vertical: fixPadding * 3.0,
          ),
          decoration: const BoxDecoration(
            color: whiteColor,
          ),
          child: Wrap(
            spacing: fixPadding * 2.0,
            runSpacing: fixPadding * 2.5,
            children: [
              // Members
              communityWidget(
                size,
                "assets/icons/group-line.png",
                tr(context, 'home.members'),
                    () {
                  Navigator.pushNamed(context, '/members');
                },
              ),
              // Birthday
              communityWidget(
                size,
                "assets/icons/shield-user.png",
                tr(context, 'home.birthday'),
                    () {
                  Navigator.pushNamed(context, '/birthday');
                },
              ),
              // Celebration (Wedding)
              communityWidget(
                size,
                "assets/icons/notice-board.png",
                tr(context, 'home.celebration'),
                    () {
                  Navigator.pushNamed(context, '/wedding');
                },
              ),
              // Events / Payments
              communityWidget(
                size,
                "assets/icons/payments.png",
                tr(context, 'home.events'),
                    () {
                  Navigator.pushNamed(
                      context, '/events');
                },
              ),
            ],
          ),
        )
      ],
    );
  }

  Widget communityWidget(
      Size size, String image, String title, Function() onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          vertical: fixPadding * 2.0,
          horizontal: fixPadding,
        ),
        width: (size.width - 60) / 2,
        decoration: BoxDecoration(
          color: whiteColor,
          borderRadius:
          BorderRadius.circular(10.0),
          boxShadow: boxShadow2,
        ),
        child: Column(
          children: [
            Center(
              child: Image.asset(
                image,
                height: 36.0,
                color: primaryColor,
                fit: BoxFit.contain,
              ),
            ),
            heightSpace,
            Text(
              title,
              style: medium16Primary,
              overflow: TextOverflow.ellipsis,
            )
          ],
        ),
      ),
    );
  }
}
