import 'package:flutter/material.dart';
import 'package:neomovies_mobile/presentation/providers/auth_provider.dart';
import 'package:neomovies_mobile/presentation/screens/auth/login_screen.dart';
import 'package:provider/provider.dart';

class ProfileScreen extends StatelessWidget {
  const ProfileScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Профиль'),
      ),
      body: Consumer<AuthProvider>(
        builder: (context, authProvider, child) {
          switch (authProvider.state) {
            case AuthState.initial:
            case AuthState.loading:
              return const Center(child: CircularProgressIndicator());
            case AuthState.unauthenticated:
              return _buildUnauthenticatedView(context);
            case AuthState.authenticated:
              return _buildAuthenticatedView(context, authProvider);
            case AuthState.error:
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('Произошла ошибка: ${authProvider.error}'),
                    const SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: () => authProvider.checkAuthStatus(),
                      child: const Text('Попробовать снова'),
                    )
                  ],
                ),
              );
          }
        },
      ),
    );
  }

  Widget _buildUnauthenticatedView(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('Войдите в свой аккаунт, чтобы продолжить'),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const LoginScreen()),
              );
            },
            child: const Text('Войти или Зарегистрироваться'),
          ),
          const SizedBox(height: 40),
          TextButton(
            onPressed: () => _showLicensesScreen(context),
            child: const Text('Лицензии библиотек'),
          ),
        ],
      ),
    );
  }

  Widget _buildAuthenticatedView(BuildContext context, AuthProvider authProvider) {
    final user = authProvider.user!;
    final initial = user.name.isNotEmpty ? user.name[0].toUpperCase() : '?';

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Center(
            child: CircleAvatar(
              radius: 40,
              child: Text(initial, style: Theme.of(context).textTheme.headlineMedium),
            ),
          ),
          const SizedBox(height: 16),
          Center(
            child: Text(user.name, style: Theme.of(context).textTheme.headlineSmall),
          ),
          const SizedBox(height: 8),
          Center(
            child: Text(user.email, style: Theme.of(context).textTheme.bodyMedium),
          ),
          const Spacer(),
          TextButton(
            onPressed: () => _showLicensesScreen(context),
            child: const Text('Лицензии библиотек'),
          ),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              authProvider.logout();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
              foregroundColor: Theme.of(context).colorScheme.onSecondaryContainer,
            ),
            child: const Text('Выйти'),
          ),
          const SizedBox(height: 10),
          OutlinedButton(
            onPressed: () => _showDeleteConfirmationDialog(context, authProvider),
            style: OutlinedButton.styleFrom(
              foregroundColor: Theme.of(context).colorScheme.error,
              side: BorderSide(color: Theme.of(context).colorScheme.error),
            ),
            child: const Text('Удалить аккаунт'),
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmationDialog(BuildContext context, AuthProvider authProvider) {
    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text('Удалить аккаунт'),
          content: const Text('Вы уверены, что хотите удалить свой аккаунт? Это действие необратимо.'),
          actions: <Widget>[
            TextButton(
              child: const Text('Отмена'),
              onPressed: () {
                Navigator.of(dialogContext).pop();
              },
            ),
            TextButton(
              style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.error),
              child: const Text('Удалить'),
              onPressed: () {
                Navigator.of(dialogContext).pop();
                authProvider.deleteAccount();
              },
            ),
          ],
        );
      },
    );
  }

  void _showLicensesScreen(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const LicensesScreen(),
      ),
    );
  }
}

class LicensesScreen extends StatelessWidget {
  const LicensesScreen({super.key});

  static const List<LibraryLicense> _licenses = [
    LibraryLicense(
      name: 'NeoMovies Mobile',
      version: '1.0.0',
      license: 'Apache-2.0',
      url: 'https://gitlab.com/foxixus/neomovies_mobile',
      description: 'Мобильное приложение для просмотра фильмов и сериалов',
    ),
    LibraryLicense(
      name: 'Flutter',
      version: '3.8.1+',
      license: 'BSD-3-Clause',
      url: 'https://github.com/flutter/flutter',
      description: 'UI toolkit for building natively compiled applications',
    ),
    LibraryLicense(
      name: 'http',
      version: '^1.2.1',
      license: 'BSD-3-Clause',
      url: 'https://github.com/dart-lang/http',
      description: 'A composable, multi-platform, Future-based API for HTTP requests',
    ),
    LibraryLicense(
      name: 'provider',
      version: '^6.1.2',
      license: 'MIT',
      url: 'https://github.com/rrousselGit/provider',
      description: 'A wrapper around InheritedWidget to make them easier to use',
    ),
    LibraryLicense(
      name: 'flutter_dotenv',
      version: '^5.1.0',
      license: 'MIT',
      url: 'https://github.com/java-james/flutter_dotenv',
      description: 'Environment configuration for Flutter',
    ),
    LibraryLicense(
      name: 'cached_network_image',
      version: '^3.3.1',
      license: 'MIT',
      url: 'https://github.com/Baseflow/flutter_cached_network_image',
      description: 'A flutter library to show images from the internet and keep them in cache',
    ),
    LibraryLicense(
      name: 'google_fonts',
      version: '^6.2.1',
      license: 'Apache-2.0',
      url: 'https://github.com/material-foundation/flutter-packages',
      description: 'A package which allows developers to use Google fonts in their Flutter apps',
    ),
    LibraryLicense(
      name: 'hive',
      version: '^2.2.3',
      license: 'Apache-2.0',
      url: 'https://github.com/isar/hive',
      description: 'Lightweight and blazing fast key-value database',
    ),
    LibraryLicense(
      name: 'hive_flutter',
      version: '^1.1.0',
      license: 'Apache-2.0',
      url: 'https://github.com/isar/hive',
      description: 'Extension for Hive that makes it easier to use Hive in Flutter',
    ),
    LibraryLicense(
      name: 'flutter_secure_storage',
      version: '^9.2.2',
      license: 'BSD-3-Clause',
      url: 'https://github.com/mogol/flutter_secure_storage',
      description: 'Flutter Secure Storage provides API to store data in secure storage',
    ),
    LibraryLicense(
      name: 'shared_preferences',
      version: '^2.2.2',
      license: 'BSD-3-Clause',
      url: 'https://github.com/flutter/packages',
      description: 'Flutter plugin for reading and writing simple key-value pairs',
    ),
    LibraryLicense(
      name: 'intl',
      version: '^0.20.2',
      license: 'BSD-3-Clause',
      url: 'https://github.com/dart-lang/intl',
      description: 'Internationalization and localization facilities',
    ),
    LibraryLicense(
      name: 'webview_flutter',
      version: '^4.7.0',
      license: 'BSD-3-Clause',
      url: 'https://github.com/flutter/packages',
      description: 'A Flutter plugin that provides a WebView widget',
    ),
    LibraryLicense(
      name: 'wakelock_plus',
      version: '^1.2.1',
      license: 'Apache-2.0',
      url: 'https://github.com/ffunes/wakelock_plus',
      description: 'Plugin that allows you to keep the device screen awake',
    ),
    LibraryLicense(
      name: 'equatable',
      version: '^2.0.5',
      license: 'MIT',
      url: 'https://github.com/felangel/equatable',
      description: 'A Dart package that helps to implement value based equality',
    ),
    LibraryLicense(
      name: 'dynamic_color',
      version: '1.7.0',
      license: 'Apache-2.0',
      url: 'https://github.com/material-foundation/flutter-packages',
      description: 'A Flutter package to create Material Color Schemes from a source color',
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Лицензии библиотек'),
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _licenses.length,
        itemBuilder: (context, index) {
          final license = _licenses[index];
          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: ListTile(
              title: Text(
                license.name,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Версия: ${license.version}'),
                  Text('Лицензия: ${license.license}'),
                  if (license.description.isNotEmpty)
                    Text(
                      license.description,
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurfaceVariant,
                        fontSize: 12,
                      ),
                    ),
                ],
              ),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                    icon: const Icon(Icons.open_in_new),
                    onPressed: () => _showLicenseDialog(context, license),
                    tooltip: 'Открыть исходный код',
                  ),
                  IconButton(
                    icon: const Icon(Icons.description),
                    onPressed: () => _showFullLicenseDialog(context, license),
                    tooltip: 'Показать полную лицензию',
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  void _showLicenseDialog(BuildContext context, LibraryLicense license) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(license.name),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Версия: ${license.version}'),
              Text('Лицензия: ${license.license}'),
              const SizedBox(height: 8),
              Text('Исходный код: ${license.url}'),
              const SizedBox(height: 8),
              if (license.description.isNotEmpty)
                Text(license.description),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Закрыть'),
            ),
          ],
        );
      },
    );
  }

  void _showFullLicenseDialog(BuildContext context, LibraryLicense license) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('${license.name} - Полная лицензия'),
          content: SizedBox(
            width: double.maxFinite,
            height: 400,
            child: SingleChildScrollView(
              child: Text(
                _getLicenseText(license.license),
                style: const TextStyle(fontSize: 12),
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Закрыть'),
            ),
          ],
        );
      },
    );
  }

  String _getLicenseText(String licenseType) {
    switch (licenseType) {
      case 'MIT':
        return '''MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.''';
      case 'Apache-2.0':
        return '''Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with such entity...

[Полный текст лицензии Apache 2.0]''';
      case 'BSD-3-Clause':
        return '''BSD 3-Clause License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED...''';
      default:
        return 'Текст лицензии не найден. Пожалуйста, обратитесь к официальному источнику.';
    }
  }
}

class LibraryLicense {
  final String name;
  final String version;
  final String license;
  final String url;
  final String description;

  const LibraryLicense({
    required this.name,
    required this.version,
    required this.license,
    required this.url,
    required this.description,
  });
}