/// Forgot Password Page
///
/// Allows users to reset their password by entering their phone number.
/// Sends OTP to the provided phone number for verification.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/core/utils/validators.dart';
import 'package:worker/features/auth/presentation/widgets/phone_input_field.dart';

/// Forgot Password Page
///
/// Simple page for password recovery flow.
/// User enters phone number and receives OTP for verification.
///
/// Features:
/// - Phone number input with validation
/// - Submit button to request OTP
/// - Back to login link
/// - Customer support link
class ForgotPasswordPage extends ConsumerStatefulWidget {
  const ForgotPasswordPage({super.key});

  @override
  ConsumerState<ForgotPasswordPage> createState() =>
      _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends ConsumerState<ForgotPasswordPage> {
  // Form key for validation
  final _formKey = GlobalKey<FormState>();

  // Controllers
  final _phoneController = TextEditingController();

  // Focus nodes
  final _phoneFocusNode = FocusNode();

  // Loading state
  bool _isLoading = false;

  @override
  void dispose() {
    _phoneController.dispose();
    _phoneFocusNode.dispose();
    super.dispose();
  }

  /// Handle submit button press
  Future<void> _handleSubmit() async {
    // Validate form
    if (!_formKey.currentState!.validate()) {
      return;
    }

    // Unfocus keyboard
    FocusScope.of(context).unfocus();

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

    try {
      // TODO: Implement forgot password API call
      // For now, just show success message after delay
      await Future.delayed(const Duration(seconds: 2));

      if (mounted) {
        // Show success message
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Mã OTP đã được gửi đến số điện thoại của bạn'),
            backgroundColor: AppColors.success,
            behavior: SnackBarBehavior.floating,
            duration: Duration(seconds: 3),
          ),
        );

        // Navigate back to login after 1 second
        await Future.delayed(const Duration(seconds: 1));
        if (mounted) {
          context.pop();
        }
      }
    } catch (e) {
      // Show error message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Có lỗi xảy ra: ${e.toString()}'),
            backgroundColor: AppColors.danger,
            behavior: SnackBarBehavior.floating,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// Show support dialog
  void _showSupport() {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Hỗ trợ khách hàng'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Hotline: 1900 xxxx'),
            SizedBox(height: AppSpacing.sm),
            Text('Email: support@eurotile.vn'),
            SizedBox(height: AppSpacing.sm),
            Text('Giờ làm việc: 8:00 - 17:00 (T2-T6)'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Đóng'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        title: const Text(
          'Quên mật khẩu',
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: false,
        leading: IconButton(
          icon: const FaIcon(FontAwesomeIcons.arrowLeft, color: Colors.black, size: 20),
          onPressed: () => context.pop(),
        ),
        actions: const [
          SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(AppSpacing.lg),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const SizedBox(height: AppSpacing.xl),

                // Icon
                _buildIcon(colorScheme),

                const SizedBox(height: AppSpacing.xl),

                // Title & Instructions
                _buildInstructions(colorScheme),

                const SizedBox(height: AppSpacing.xl),

                // Form Card
                _buildFormCard(colorScheme),

                const SizedBox(height: AppSpacing.lg),

                // Back to Login Link
                _buildBackToLoginLink(colorScheme),

                const SizedBox(height: AppSpacing.xl),

                // Support Link
                _buildSupportLink(colorScheme),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// Build icon
  Widget _buildIcon(ColorScheme colorScheme) {
    return Center(
      child: Container(
        width: 100,
        height: 100,
        decoration: BoxDecoration(
          color: colorScheme.primary.withValues(alpha: 0.1),
          shape: BoxShape.circle,
        ),
        child: Icon(
          FontAwesomeIcons.key,
          size: 50,
          color: colorScheme.primary,
        ),
      ),
    );
  }

  /// Build instructions
  Widget _buildInstructions(ColorScheme colorScheme) {
    return Column(
      children: [
        Text(
          'Đặt lại mật khẩu',
          style: TextStyle(
            fontSize: 28.0,
            fontWeight: FontWeight.bold,
            color: colorScheme.onSurface,
          ),
        ),
        const SizedBox(height: AppSpacing.sm),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
          child: Text(
            'Nhập số điện thoại đã đăng ký. Chúng tôi sẽ gửi mã OTP để xác nhận và đặt lại mật khẩu của bạn.',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 15.0,
              color: colorScheme.onSurfaceVariant,
              height: 1.5,
            ),
          ),
        ),
      ],
    );
  }

  /// Build form card
  Widget _buildFormCard(ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.all(AppSpacing.lg),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10.0,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // Phone Input
          PhoneInputField(
            controller: _phoneController,
            focusNode: _phoneFocusNode,
            validator: Validators.phone,
            enabled: !_isLoading,
            onFieldSubmitted: (_) {
              if (!_isLoading) {
                _handleSubmit();
              }
            },
          ),

          const SizedBox(height: AppSpacing.lg),

          // Submit Button
          SizedBox(
            height: ButtonSpecs.height,
            child: ElevatedButton(
              onPressed: _isLoading ? null : _handleSubmit,
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                disabledBackgroundColor: colorScheme.surfaceContainerHighest,
                disabledForegroundColor: colorScheme.onSurfaceVariant,
                elevation: ButtonSpecs.elevation,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(ButtonSpecs.borderRadius),
                ),
              ),
              child: _isLoading
                  ? CustomLoadingIndicator(
                      color: colorScheme.onPrimary,
                      size: 20,
                    )
                  : const Text(
                      'Gửi mã OTP',
                      style: TextStyle(
                        fontSize: ButtonSpecs.fontSize,
                        fontWeight: ButtonSpecs.fontWeight,
                      ),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build back to login link
  Widget _buildBackToLoginLink(ColorScheme colorScheme) {
    return Center(
      child: RichText(
        text: TextSpan(
          text: 'Nhớ mật khẩu? ',
          style: TextStyle(fontSize: 14.0, color: colorScheme.onSurfaceVariant),
          children: [
            WidgetSpan(
              child: GestureDetector(
                onTap: () => context.pop(),
                child: Text(
                  'Đăng nhập',
                  style: TextStyle(
                    fontSize: 14.0,
                    color: colorScheme.primary,
                    fontWeight: FontWeight.w500,
                    decoration: TextDecoration.none,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build support link
  Widget _buildSupportLink(ColorScheme colorScheme) {
    return Center(
      child: TextButton.icon(
        onPressed: _showSupport,
        icon: Icon(
          FontAwesomeIcons.headset,
          size: AppIconSize.sm,
          color: colorScheme.primary,
        ),
        label: Text(
          'Hỗ trợ khách hàng',
          style: TextStyle(
            fontSize: 14.0,
            color: colorScheme.primary,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
