import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:convert'; // For JSON encoding/decoding

Future<void> main() async {
  runApp(UnixApp());
}

// Model class for City
class City {
  final int id;
  final String name;

  City({required this.id, required this.name});
}

class UnixApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'UNIX App',
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      routes: {
        '/': (context) => WelcomePage(),
        '/selection': (context) => SelectionPage(),
      },
      theme: ThemeData(
        fontFamily: 'Involve', // Set the default font family here
        textTheme: TextTheme(
          bodyLarge: TextStyle(color: Colors.black),
          bodyMedium: TextStyle(color: Colors.black),
          // Define other text styles if needed
        ),
      ),
    );
  }
}

class WelcomePage extends StatelessWidget {
  final Color darkAccent = Color.fromARGB(255, 0, 0, 0); // Dark color

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:
          Color.fromARGB(255, 255, 255, 240), // Fully opaque light color
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Добро',
                style: TextStyle(
                    fontSize: 32,
                    color: darkAccent,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                'пожаловать',
                style: TextStyle(
                    fontSize: 32,
                    color: darkAccent,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                'в',
                style: TextStyle(
                    fontSize: 32,
                    color: darkAccent,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                'UNIX',
                style: TextStyle(
                    fontSize: 32,
                    color: darkAccent,
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 16), // Added spacing for better layout
              Text(
                'Давай выберем твой город и отправим запрос',
                style: TextStyle(
                  fontSize: 17,
                  color: darkAccent,
                  height: 1.5,
                ),
                textAlign: TextAlign.center, // Center the text
              ),
              SizedBox(height: 30),
              ElevatedButton(
                onPressed: () {
                  Navigator.pushNamed(context, '/selection');
                },
                child: Text(
                  'Начать',
                  style: TextStyle(
                      fontSize: 18, color: Color.fromARGB(255, 255, 255, 240)),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: darkAccent, // Button background color
                  padding:
                      EdgeInsets.symmetric(horizontal: 50.0, vertical: 15.0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class SelectionPage extends StatefulWidget {
  @override
  _SelectionPageState createState() => _SelectionPageState();
}

class _SelectionPageState extends State<SelectionPage> {
  final Color darkAccent = Color.fromARGB(255, 0, 0, 0); // Simple dark
  final Color darkPrimary = Color.fromARGB(
      255, 52, 49, 49); // Fully opaque dark for inactive elements

  // Controllers and state variables
  TextEditingController openAIController = TextEditingController();
  bool isLoading = false; // To show loading indicator

  // State for selected city
  City? selectedCity;

  @override
  void dispose() {
    openAIController.dispose(); // Dispose the controller
    super.dispose();
  }

  // List of cities in Russia
  final List<City> cities = [
    City(id: 1, name: 'Москва'),
    City(id: 2, name: 'Санкт-Петербург'),
    City(id: 3, name: 'Новосибирск'),
    City(id: 4, name: 'Екатеринбург'),
    City(id: 5, name: 'Нижний Новгород'),
    City(id: 6, name: 'Казань'),
    City(id: 7, name: 'Красноярск'),
    City(id: 8, name: 'Омск'),
    City(id: 9, name: 'Самара'),
    City(id: 10, name: 'Ростов-на-Дону'),
    // Add more cities as needed
  ];

  // Method to show the Bottom Sheet for city selection
  void _showCityBottomSheet() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return CityBottomSheet(
          cities: cities,
          onCitySelected: (City city) {
            setState(() {
              selectedCity = city;
            });
            Navigator.pop(context);
          },
        );
      },
    );
  }

  // Method to send request to OpenAI
  Future<void> _sendOpenAIRequest() async {
    final String prompt = openAIController.text.trim();
    if (prompt.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Пожалуйста, введите запрос.'),
          backgroundColor: Color.fromARGB(255, 210, 16, 6),
        ),
      );
      return;
    }

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

    try {
      // Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key
      const String apiKey = 'YOUR_OPENAI_API_KEY';

      // Define the API endpoint
      final String apiUrl = 'https://api.openai.com/v1/completions';

      // Make the HTTP POST request
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $apiKey',
        },
        body: jsonEncode({
          'model': 'text-davinci-003', // Choose the appropriate model
          'prompt': prompt,
          'max_tokens': 150,
          'n': 1,
          'stop': null,
          'temperature': 0.7,
        }),
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = json.decode(response.body);
        String aiResponse = data['choices'][0]['text'].trim();

        // Show the response in a dialog
        showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('Ответ от OpenAI'),
              content: SingleChildScrollView(
                child: Text(aiResponse),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text('Закрыть'),
                ),
              ],
            );
          },
        );
      } else {
        // Handle error
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
                'Ошибка: ${response.statusCode}. Не удалось получить ответ от OpenAI.'),
            backgroundColor: Color.fromARGB(255, 210, 16, 6),
          ),
        );
      }
    } catch (e) {
      // Handle any other errors
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Произошла ошибка: $e'),
          backgroundColor: Color.fromARGB(255, 210, 16, 6),
        ),
      );
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  // Build method
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255, 255, 240),
      appBar: AppBar(
        title: Text(
          'Настройки',
          style: TextStyle(color: darkAccent),
        ),
        backgroundColor: Color.fromARGB(255, 255, 255, 240),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: darkAccent),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // City selection
            Row(
              children: [
                Expanded(
                  child: Text(
                    selectedCity != null
                        ? 'Город: ${selectedCity!.name}'
                        : 'Выберите город',
                    style: TextStyle(fontSize: 18, color: darkAccent),
                  ),
                ),
                ElevatedButton(
                  onPressed: _showCityBottomSheet,
                  child: Text(
                    'Выбрать город',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: darkAccent,
                    padding:
                        EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 30),
            // Divider
            Divider(),
            SizedBox(height: 20),
            // OpenAI Query Section
            Text(
              'Отправить запрос в OpenAI',
              style: TextStyle(
                  fontSize: 20,
                  color: darkAccent,
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            TextField(
              controller: openAIController,
              decoration: InputDecoration(
                labelText: 'Введите ваш запрос',
                border: OutlineInputBorder(),
              ),
              maxLines: null, // Allow multiple lines
            ),
            SizedBox(height: 20),
            isLoading
                ? CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: _sendOpenAIRequest,
                    child: Text(
                      'Отправить',
                      style: TextStyle(
                          fontSize: 18,
                          color: const Color.fromARGB(255, 255, 255, 255)),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          darkAccent, // Button background color
                      padding: EdgeInsets.symmetric(
                          horizontal: 50.0, vertical: 15.0),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                  ),
          ],
        ),
      ),
    );
  }
}

class CityBottomSheet extends StatelessWidget {
  final List<City> cities;
  final Function(City) onCitySelected;

  CityBottomSheet({required this.cities, required this.onCitySelected});

  @override
  Widget build(BuildContext context) {
    return Container(
      // Adjust height as needed
      height: 400,
      child: Column(
        children: [
          SizedBox(height: 10),
          Text(
            'Выберите город',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          Divider(),
          Expanded(
            child: ListView.builder(
              itemCount: cities.length,
              itemBuilder: (context, index) {
                City city = cities[index];
                return ListTile(
                  leading: CircleAvatar(
                    child: Text(city.id.toString()),
                    backgroundColor: Colors.blueAccent,
                    foregroundColor: Colors.white,
                  ),
                  title: Text(city.name),
                  onTap: () {
                    onCitySelected(city);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}


remove city selector, also remove everything which link's to city select