import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class OpenVertical extends StatefulWidget {
  const OpenVertical({Key? key}) : super(key: key);

  @override
  State<OpenVertical> createState() => _OpenVerticalState();
}

class _OpenVerticalState extends State<OpenVertical> {
  bool isLoading = false;
  List<Map<String, dynamic>> verticals = [];

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

  Future<void> fetchVerticals() async {
    setState(() {
      isLoading = true;
    });

    final uri = Uri.parse('https://rmbferodeunited.in/api/get_verticals.php');

    try {
      final response = await http.get(uri);
      debugPrint('API Raw Response: ${response.body}');

      if (response.statusCode == 200) {
        final decoded = json.decode(response.body);

        if (decoded['status'] == true && decoded['data'] != null) {
          setState(() {
            verticals = List<Map<String, dynamic>>.from(decoded['data']);
          });
        } else {
          debugPrint('API Message: ${decoded['message']}');
        }
      } else {
        debugPrint('HTTP Error Code: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Exception: $e');
    }

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        title: const Text(
          'Open Verticals',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: false,
        elevation: 1,
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : verticals.isEmpty
          ? const Center(child: Text('No verticals available'))
          : ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: verticals.length,
        itemBuilder: (context, index) {
          final verticalName = verticals[index]['vertical_name'];

          return Container(
            margin: const EdgeInsets.only(bottom: 12),
            child: OutlinedButton(
              style: OutlinedButton.styleFrom(
                side: BorderSide(
                  color: Theme.of(context).primaryColor,
                ),
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              onPressed: () {
                debugPrint('Selected Vertical: $verticalName');
              },
              child: Text(
                verticalName,
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
          );
        },
      ),
    );
  }
}
