import 'dart:convert';

import 'package:flutter/material.dart';

class StoreSelector extends StatefulWidget {
  @override
  _StoreSelectorState createState() => _StoreSelectorState();
}

class _StoreSelectorState extends State<StoreSelector> {
  List<Store> stores = [];
  List<String> regions = [];
  List<String> storeNames = [];
  String? selectedRegion;
  String? selectedStore;

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

  void fetchStores() {
    const jsonData = '''
    {
      "STORES": [
        {"region": "KARNATAKA", "storename": "KLM JAYANAGAR"},
        {"region": "KARNATAKA", "storename": "KLM HSR"},
        {"region": "ANDHRA PRADESH", "storename": "KLM GAJUWAKA"},
        {"region": "TELANGANA", "storename": "KLM AMEERPET"},
        {"region": "TELANGANA", "storename": "KLM DILSUKHNAGAR"},
        {"region": "TELANGANA", "storename": "KLM KHAMMAM"},
        {"region": "TELANGANA", "storename": "KLM AS RAO NAGAR"},
        {"region": "TELANGANA", "storename": "KLM BODUPPAL"},
        {"region": "ANDHRA PRADESH", "storename": "KLM BHIMAVARAM"},
        {"region": "ANDHRA PRADESH", "storename": "KLM NELLORE"},
        {"region": "ANDHRA PRADESH", "storename": "KLM VIZAG"},
        {"region": "TELANGANA", "storename": "KLM VANASTHALIPURAM"},
        {"region": "KARNATAKA", "storename": "KLM MARATHAHALLI"},
        {"region": "TELANGANA", "storename": "KLM KUKATPALLY"},
        {"region": "TELANGANA", "storename": "KLM PATNY"},
        {"region": "TELANGANA", "storename": "KLM SUCHITRA"},
        {"region": "TELANGANA", "storename": "MANDIR BANJARA HILLS"},
        {"region": "TELANGANA", "storename": "KM-NEW-AMPT"},
        {"region": "TELANGANA", "storename": "KM NEW PATNY"}
      ]
    }
    ''';

    final Map<String, dynamic> jsonResponse = json.decode(jsonData);
    stores = (jsonResponse['STORES'] as List)
        .map((data) => Store.fromJson(data))
        .toList();
    // Get unique regions
    regions = stores.map((store) => store.region).toSet().toList();
    
    setState(() {});
  }

  void updateStoreNames(String region) {
    storeNames = stores
        .where((store) => store.region == region)
        .map((store) => store.storename)
        .toList();
    selectedStore = null; // Reset the selected store
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Store Selector'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            DropdownButton<String>(
              hint: Text('Select Region'),
              value: selectedRegion,
              isExpanded: true,
              onChanged: (newValue) {
                setState(() {
                  selectedRegion = newValue;
                  updateStoreNames(newValue!);
                });
              },
              items: regions.map((region) {
                return DropdownMenuItem<String>(
                  value: region,
                  child: Text(region),
                );
              }).toList(),
            ),
            SizedBox(height: 20),
            DropdownButton<String>(
              hint: Text('Select Store'),
              value: selectedStore,
              isExpanded: true,
              onChanged: (newValue) {
                setState(() {
                  selectedStore = newValue;
                });
              },
              items: storeNames.map((store) {
                return DropdownMenuItem<String>(
                  value: store,
                  child: Text(store),
                );
              }).toList(),
            ),
          ],
        ),
      ),
    );
  }
}

class Store {
  final String region;
  final String storename;

  Store({required this.region, required this.storename});

  factory Store.fromJson(Map<String, dynamic> json) {
    return Store(
      region: json['region'],
      storename: json['storename'],
    );
  }
}