import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

void main() {
  runApp(UnixApp());
}

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

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

// Custom InputFormatter to limit input value
class MaxValueInputFormatter extends TextInputFormatter {
  final int max;

  MaxValueInputFormatter({required this.max});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.isEmpty) {
      return newValue;
    }

    final int? value = int.tryParse(newValue.text);
    if (value == null || value > max) {
      return oldValue;
    }
    return newValue;
  }
}

class UnixApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'UNIX App',
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      routes: {
        '/': (context) => WelcomePage(),
        '/selection': (context) => SelectionPage(),
        '/secret': (context) => SecretPage(), // Added secret page route
      },
      onGenerateRoute: (settings) {
        if (settings.name == '/development') {
          final args = settings.arguments as Map<String, dynamic>;
          return MaterialPageRoute(
            builder: (context) {
              return DevelopmentPage(
                selectedSubjects: args['selectedSubjects'],
                selectedCity: args['selectedCity'],
              );
            },
          );
        }
        assert(false, 'Need to implement ${settings.name}');
        return null;
      },
      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 blue

  // Define the secret phrase
  final String secretPhrase = "matrassex";

  @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),
              ),
              GestureDetector(
                onLongPress: () {
                  _showSecretPhraseDialog(context);
                },
                child: 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),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // Method to show the secret phrase dialog
  void _showSecretPhraseDialog(BuildContext context) {
    TextEditingController _phraseController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("Ввести секретную фразу"),
          content: TextField(
            controller: _phraseController,
            decoration: InputDecoration(
              hintText: "Введите секретную фразу",
            ),
            obscureText: true, // Hide the input
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context); // Close dialog
              },
              child: Text("Отмена"),
            ),
            ElevatedButton(
              onPressed: () {
                if (_phraseController.text == secretPhrase) {
                  Navigator.pop(context); // Close dialog
                  Navigator.pushNamed(
                      context, '/secret'); // Navigate to secret page
                } else {
                  // Show error
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Неправильная фраза!'),
                      backgroundColor: Color.fromARGB(255, 210, 16, 6),
                    ),
                  );
                }
              },
              child: Text("Войти"),
            ),
          ],
        );
      },
    );
  }
}

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 green for inactive elements

  // State variables for switches
  bool russianSelected = false;
  bool mathSelected = false;
  bool informaticsSelected = false;
  bool physicsSelected = false;
  bool obshestvoSelected = false;
  bool englishSelected = false;
  bool chemistrySelected = false;
  bool literatureSelected = false;
  bool historySelected = false;
  bool biologySelected = false;

  // Controllers for text fields
  TextEditingController russianController = TextEditingController(text: '50');
  TextEditingController mathController = TextEditingController(text: '50');
  TextEditingController informaticsController =
      TextEditingController(text: '50');
  TextEditingController physicsController = TextEditingController(text: '50');
  TextEditingController obshestvoController = TextEditingController(text: '50');
  TextEditingController englishController = TextEditingController(text: '50');
  TextEditingController chemistryController = TextEditingController(text: '50');
  TextEditingController literatureController =
      TextEditingController(text: '50');
  TextEditingController historyController = TextEditingController(text: '50');
  TextEditingController biologyController = TextEditingController(text: '50');

  // State for selected city
  City? selectedCity;

  @override
  void dispose() {
    russianController.dispose();
    mathController.dispose();
    informaticsController.dispose();
    physicsController.dispose();
    obshestvoController.dispose();
    englishController.dispose();
    chemistryController.dispose();
    literatureController.dispose();
    historyController.dispose();
    biologyController.dispose();
    super.dispose();
  }

  // Method to collect selected subjects and their scores
  Map<String, double> _getSelectedSubjects() {
    Map<String, double> selected = {};
    if (russianSelected) {
      double value = double.tryParse(russianController.text) ?? 0;
      selected['Русский'] = value;
    }
    if (mathSelected) {
      double value = double.tryParse(mathController.text) ?? 0;
      selected['Математика'] = value;
    }
    if (informaticsSelected) {
      double value = double.tryParse(informaticsController.text) ?? 0;
      selected['Информатика'] = value;
    }
    if (physicsSelected) {
      double value = double.tryParse(physicsController.text) ?? 0;
      selected['Физика'] = value;
    }
    if (obshestvoSelected) {
      double value = double.tryParse(obshestvoController.text) ?? 0;
      selected['Обществознание'] = value;
    }
    if (englishSelected) {
      double value = double.tryParse(englishController.text) ?? 0;
      selected['Английский'] = value;
    }
    if (chemistrySelected) {
      double value = double.tryParse(chemistryController.text) ?? 0;
      selected['Химия'] = value;
    }
    if (literatureSelected) {
      double value = double.tryParse(literatureController.text) ?? 0;
      selected['Литература'] = value;
    }
    if (historySelected) {
      double value = double.tryParse(historyController.text) ?? 0;
      selected['История'] = value;
    }
    if (biologySelected) {
      double value = double.tryParse(biologyController.text) ?? 0;
      selected['Биология'] = value;
    }
    return selected;
  }

  // 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
  void _showCityBottomSheet() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return CityBottomSheet(
          cities: cities,
          onCitySelected: (City city) {
            setState(() {
              selectedCity = city;
            });
            Navigator.pop(context);
          },
        );
      },
    );
  }

  @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: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: 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),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // Divider
          Divider(),
          // Expanded to contain the subjects list
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    SubjectBlock(
                      title: 'Русский',
                      isSelected: russianSelected,
                      onToggle: (value) {
                        setState(() {
                          russianSelected = value;
                        });
                      },
                      controller: russianController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.verified, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Математика',
                      isSelected: mathSelected,
                      onToggle: (value) {
                        setState(() {
                          mathSelected = value;
                        });
                      },
                      controller: mathController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.functions, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Информатика',
                      isSelected: informaticsSelected,
                      onToggle: (value) {
                        setState(() {
                          informaticsSelected = value;
                        });
                      },
                      controller: informaticsController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.dvr, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Физика',
                      isSelected: physicsSelected,
                      onToggle: (value) {
                        setState(() {
                          physicsSelected = value;
                        });
                      },
                      controller: physicsController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.rocket_launch, // Added icon
                      // If not available, use FontAwesomeIcons.rocket,
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Обществознание',
                      isSelected: obshestvoSelected,
                      onToggle: (value) {
                        setState(() {
                          obshestvoSelected = value;
                        });
                      },
                      controller: obshestvoController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.local_police, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Английский',
                      isSelected: englishSelected,
                      onToggle: (value) {
                        setState(() {
                          englishSelected = value;
                        });
                      },
                      controller: englishController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.translate, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Химия',
                      isSelected: chemistrySelected,
                      onToggle: (value) {
                        setState(() {
                          chemistrySelected = value;
                        });
                      },
                      controller: chemistryController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.science, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Литература',
                      isSelected: literatureSelected,
                      onToggle: (value) {
                        setState(() {
                          literatureSelected = value;
                        });
                      },
                      controller: literatureController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.book, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'История',
                      isSelected: historySelected,
                      onToggle: (value) {
                        setState(() {
                          historySelected = value;
                        });
                      },
                      controller: historyController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.public, // Added icon
                    ),
                    SizedBox(height: 20),
                    SubjectBlock(
                      title: 'Биология',
                      isSelected: biologySelected,
                      onToggle: (value) {
                        setState(() {
                          biologySelected = value;
                        });
                      },
                      controller: biologyController,
                      darkAccent: darkAccent,
                      darkPrimary: darkPrimary,
                      icon: Icons.biotech, // Added icon
                    ),
                    SizedBox(height: 40),
                    ElevatedButton(
                      onPressed: () {
                        if (selectedCity == null) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('Пожалуйста, выберите город.'),
                              backgroundColor: Color.fromARGB(255, 210, 16, 6),
                            ),
                          );
                          return;
                        }
                        Map<String, double> selectedSubjects =
                            _getSelectedSubjects();
                        Navigator.pushNamed(
                          context,
                          '/development',
                          arguments: {
                            'selectedSubjects': selectedSubjects,
                            'selectedCity': selectedCity,
                          },
                        );
                      },
                      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);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class SubjectBlock extends StatelessWidget {
  final String title;
  final bool isSelected;
  final Function(bool) onToggle;
  final TextEditingController controller;
  final Color darkAccent;
  final Color darkPrimary;
  final IconData? icon; // Added icon parameter

  SubjectBlock({
    required this.title,
    required this.isSelected,
    required this.onToggle,
    required this.controller,
    required this.darkAccent,
    required this.darkPrimary,
    this.icon, // Initialize icon
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            if (icon != null) ...[
              Icon(
                icon,
                color: darkAccent,
              ),
              SizedBox(width: 8),
            ],
            Expanded(
              child: Text(
                title,
                style: TextStyle(fontSize: 20, color: darkAccent),
              ),
            ),
            Switch(
              value: isSelected,
              onChanged: onToggle,
              activeColor: darkAccent,
              activeTrackColor: darkAccent.withOpacity(0.5),
              inactiveThumbColor: darkAccent,
              inactiveTrackColor: darkPrimary.withOpacity(0.5),
            ),
          ],
        ),
        if (isSelected)
          Padding(
            padding: const EdgeInsets.only(top: 10.0),
            child: TextField(
              controller: controller,
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly, // Allow only digits
                MaxValueInputFormatter(max: 100), // Limit value to 100
              ],
              decoration: InputDecoration(
                labelText: 'Баллы (0-100)',
                border: OutlineInputBorder(),
                // Optional: Add error text or validation
              ),
              onChanged: (value) {
                // Optional: Add any additional logic or validation here
              },
            ),
          ),
      ],
    );
  }
}

class DevelopmentPage extends StatelessWidget {
  final Map<String, double> selectedSubjects;
  final City? selectedCity;
  final Color customTextColor =
      Color.fromARGB(255, 255, 253, 253); // Fully white color

  DevelopmentPage({required this.selectedSubjects, required this.selectedCity});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255, 255, 240),
      appBar: AppBar(
        title: Text(
          'Ваши результаты',
          style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)),
        ),
        backgroundColor:
            Color.fromARGB(255, 255, 255, 240), // Fully opaque white background
        elevation: 0, // Remove shadow
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Color.fromARGB(255, 0, 0, 0)),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: selectedSubjects.isNotEmpty
            ? AnimationLimiter(
                child: ListView(
                  children: [
                    // Display selected city
                    if (selectedCity != null)
                      Card(
                        color: Colors.blueAccent,
                        margin: EdgeInsets.symmetric(vertical: 8.0),
                        child: ListTile(
                          leading: Icon(
                            Icons.location_city,
                            color: Colors.white,
                          ),
                          title: Text(
                            'Город: ${selectedCity!.name}',
                            style: TextStyle(
                              fontSize: 20,
                              color: customTextColor,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ...selectedSubjects.entries.map((entry) {
                      return AnimationConfiguration.staggeredList(
                        position:
                            selectedSubjects.keys.toList().indexOf(entry.key),
                        duration: const Duration(milliseconds: 375),
                        child: SlideAnimation(
                          verticalOffset: 50.0,
                          child: FadeInAnimation(
                            child: Card(
                              color: Color.fromARGB(255, 31, 31, 31),
                              margin: EdgeInsets.symmetric(vertical: 8.0),
                              child: ListTile(
                                title: Text(
                                  entry.key,
                                  style: TextStyle(
                                    fontSize: 20,
                                    color: customTextColor,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                subtitle: Text(
                                  'Баллы: ${entry.value.toInt()}',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: customTextColor,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ],
                ),
              )
            : Center(
                child: Text(
                  'Нет выбранных предметов.',
                  style: TextStyle(
                    fontSize: 20,
                    color: customTextColor,
                  ),
                ),
              ),
      ),
    );
  }
}

class SecretPage extends StatelessWidget {
  final Color customTextColor =
      Color.fromARGB(255, 255, 253, 253); // Fully white color

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 31, 31, 31), // Dark background
      appBar: AppBar(
        title: Text(
          'Секретная страница',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Color.fromARGB(255, 31, 31, 31),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Center(
        child: Image.asset(
          'images/lol.jpg',
          // Ensure you have this image in your assets folder and declared in pubspec.yaml
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}


add shader's on background on start page


void mainImage( out vec4 fragColor, in vec2 fragCoord ){
    vec2 uv =  (2.0 * fragCoord - iResolution.xy) / min(iResolution.x, iResolution.y);

    for(float i = 1.0; i < 10.0; i++){
        uv.x += 0.6 / i * cos(i * 2.5* uv.y + iTime);
        uv.y += 0.6 / i * cos(i * 1.5 * uv.x + iTime);
    }
    
    fragColor = vec4(vec3(0.1)/abs(sin(iTime-uv.y-uv.x)),1.0);
}