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:http/http.dart' as http;

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

  @override
  State<EventsScreen> createState() => _EventsScreenState();
}

class _EventsScreenState extends State<EventsScreen> {
  final List<String> _images = [];

  bool _loading = true;
  String? _errorMessage;

  // ✅ UPDATE THIS TO YOUR REAL API PATH
  static const String _eventsApiUrl =
      'https://gelite.asia/api/events.php';

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

  /// ✅ Build full image URL using base uploads path
  String _buildImageUrl(String filename) {
    String photo = filename.trim();

    print("RAW IMAGE FROM API: $photo");

    if (photo.isEmpty) return '';

    if (photo.startsWith('http://') || photo.startsWith('https://')) {
      print("FULL IMAGE URL USED: $photo");
      return photo;
    }

    if (photo.startsWith('file://')) {
      photo = photo.substring('file://'.length);
    }

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

    final fullUrl = 'https://gelite.asia/api/uploads/events/$photo';

    print("BUILT IMAGE URL: $fullUrl");

    return fullUrl;
  }

  /// ✅ Fetch events with DEBUG PRINTS
  Future<void> _fetchEvents() async {
    print("---------- EVENTS API CALL START ----------");

    setState(() {
      _loading = true;
      _errorMessage = null;
    });

    try {
      final uri = Uri.parse(_eventsApiUrl);

      print("EVENTS API URL: $uri");

      final response = await http.get(uri);

      print("EVENTS STATUS CODE: ${response.statusCode}");
      print("EVENTS RESPONSE BODY: ${response.body}");

      if (response.statusCode == 200 && response.body.isNotEmpty) {
        final decoded = jsonDecode(response.body);

        if (decoded is Map<String, dynamic> &&
            decoded['status'] == 'success') {
          final List<dynamic> data = decoded['data'] ?? [];

          print("TOTAL EVENTS FOUND: ${data.length}");

          final List<String> imgs = [];

          for (final item in data) {
            if (item is Map<String, dynamic>) {
              final image = item['image']?.toString().trim() ?? '';

              if (image.isNotEmpty) {
                print("IMAGE FOUND: $image");
                imgs.add(image);
              }
            }
          }

          setState(() {
            _images
              ..clear()
              ..addAll(imgs);
            _loading = false;
          });
        } else {
          print("EVENTS API STATUS FAILED");

          setState(() {
            _loading = false;
            _errorMessage = 'Failed to load events';
          });
        }
      } else {
        print("SERVER ERROR: ${response.statusCode}");

        setState(() {
          _loading = false;
          _errorMessage =
          'Server error (${response.statusCode})';
        });
      }
    } catch (e) {
      print("EVENTS API ERROR: $e");

      setState(() {
        _loading = false;
        _errorMessage = 'Error loading events';
      });
    }

    print("---------- EVENTS API CALL END ----------");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: whiteColor,
        centerTitle: false,
        titleSpacing: 0.0,
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: const Icon(
            Icons.arrow_back,
            color: blackColor,
          ),
        ),
        title: Text(
          tr(context, 'event.event'),
          style: medium18Black,
        ),
      ),
      body: ListView(
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.only(bottom: fixPadding),
        children: [
          topImage(),
          heightSpace,

          /// ✅ Loading
          if (_loading)
            const Padding(
              padding: EdgeInsets.all(fixPadding * 2),
              child: Center(
                child: CircularProgressIndicator(),
              ),
            )

          /// ✅ Error
          else if (_errorMessage != null)
            Padding(
              padding: const EdgeInsets.all(fixPadding * 2),
              child: Center(
                child: Text(
                  _errorMessage!,
                  style: medium16Primary,
                  textAlign: TextAlign.center,
                ),
              ),
            )

          /// ✅ Empty
          else if (_images.isEmpty)
              Padding(
                padding: const EdgeInsets.all(fixPadding * 2),
                child: const Center(
                  child: Text(
                    'No events found',
                    style: medium16Primary,
                  ),
                ),
              )

            /// ✅ Image Gallery
            else
              _buildGallery(),
        ],
      ),
    );
  }

  /// ✅ Top banner image
  Widget topImage() {
    return Image.asset(
      "assets/community/events-top-image.png",
      height: 128.0,
      width: double.maxFinite,
      fit: BoxFit.cover,
    );
  }

  /// ✅ Image gallery grid
  Widget _buildGallery() {
    return Padding(
      padding: const EdgeInsets.symmetric(
          horizontal: fixPadding * 2),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _images.length,
        gridDelegate:
        const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: fixPadding * 1.5,
          mainAxisSpacing: fixPadding * 1.5,
        ),
        itemBuilder: (context, index) {
          final raw = _images[index];
          final url = _buildImageUrl(raw);

          if (url.isEmpty) {
            return _brokenImageTile();
          }

          return ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: AspectRatio(
              aspectRatio: 1,
              child: Image.network(
                url,
                fit: BoxFit.cover,
                errorBuilder: (_, __, ___) {
                  print("IMAGE LOAD ERROR: $url");
                  return _brokenImageTile();
                },
                loadingBuilder:
                    (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Container(
                    color: Colors.grey.shade100,
                    child: const Center(
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    ),
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }

  /// ✅ Broken Image Widget
  Widget _brokenImageTile() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(12),
      ),
      child: const Icon(
        Icons.broken_image_outlined,
        color: primaryColor,
      ),
    );
  }
}
