diff --git a/README.md b/README.md index a4e4753..905bc91 100644 --- a/README.md +++ b/README.md @@ -22,4 +22,4 @@ The application is built with a focus on performance, security, and clean code p For a deeper dive into our system design and development workflows, please explore the attached documentation: * [Flutter App Architecture](documentation/architecture/flutter-architecture.md) * [Database Schema & ERD](documentation/architecture/database-schema.md) -* [Git & Conventional Commits Guidelines](documentation/guidelines/conventional-commit.md) \ No newline at end of file +* [Git & Conventional Commits Guidelines](documentation/guidelines/conventional-commit.md) diff --git a/src/lib/core/theme/app_theme.dart b/src/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..1da88ec --- /dev/null +++ b/src/lib/core/theme/app_theme.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + // ========================================================= + // ☀️ LIGHT THEME DICTIONARY + // Inherited from the legacy AppColors class + // ========================================================= + static final ThemeData lightTheme = ThemeData( + brightness: Brightness.light, + scaffoldBackgroundColor: const Color(0xFFF4F6F9), // Legacy: AppColors.background + + colorScheme: const ColorScheme.light( + // Brand Colors + primary: Color(0xFF5A8DF3), // Legacy: AppColors.primary + secondary: Color(0xFF4A90E2), // Legacy: AppColors.primaryBlue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Colors.white, // Legacy: AppColors.taskCardBg / white + surfaceContainerHighest: Color(0xFFE0F7FA), // Legacy: AppColors.backgroundBlue (Tinted background) + + // Text Colors + onSurface: Color(0xFF2D3440), // Legacy: AppColors.textDark + onSurfaceVariant: Color(0xFF757575), // Legacy: AppColors.grayText / textSecondary + + // Border & Status Colors + outline: Color(0xFFE2E8F0), // Legacy: AppColors.border + error: Colors.redAccent, // Legacy: AppColors.error + tertiary: Colors.green, // Using Tertiary for Success (Green) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF5A8DF3)), + titleTextStyle: TextStyle( + color: Color(0xFF5A8DF3), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFFE2E8F0)), + ); + + // ========================================================= + // 🌙 DARK THEME DICTIONARY + // Extracted from the provided Stitch Design System + // ========================================================= + static final ThemeData darkTheme = ThemeData( + brightness: Brightness.dark, + scaffoldBackgroundColor: const Color(0xFF0F172A), // Neutral Slate Dark + + colorScheme: const ColorScheme.dark( + // Brand Colors (Slightly brighter to stand out on dark background) + primary: Color(0xFF60A5FA), // Bright Blue + secondary: Color(0xFF61789A), // Slate Blue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Color(0xFF1E293B), // Slightly lighter than background, used for Cards + surfaceContainerHighest: Color(0xFF162032), // Dark mode counterpart for backgroundBlue + + // Text Colors + onSurface: Colors.white, // Primary text (White) + onSurfaceVariant: Color(0xFF94A3B8), // Secondary text (Light Slate) + + // Border, Status & Highlight Colors + outline: Color(0xFF334155), // Faint Card Border + error: Color(0xFFF87171), // Pinkish Red (Similar to Trash Icon) + tertiary: Color(0xFFD19900), // Mustard Yellow (Similar to Edit Pencil Icon) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF60A5FA)), + titleTextStyle: TextStyle( + color: Color(0xFF60A5FA), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFF334155)), + ); +} \ No newline at end of file diff --git a/src/lib/core/theme/auth_layout_template.dart b/src/lib/core/theme/auth_layout_template.dart index 88e796d..3146fc2 100644 --- a/src/lib/core/theme/auth_layout_template.dart +++ b/src/lib/core/theme/auth_layout_template.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// The master layout template for all authentication screens. /// Handles the UI skeleton, loading states, backgrounds, and responsive scrolling. @@ -16,6 +15,7 @@ class AuthLayoutTemplate extends StatelessWidget { final Widget? footerContent; final VoidCallback? onGoogleTap; // Login with Google final VoidCallback? onFacebookTap; // Login with Facebook + final bool compactMode; const AuthLayoutTemplate({ super.key, @@ -31,81 +31,122 @@ class AuthLayoutTemplate extends StatelessWidget { this.footerContent, this.onGoogleTap, this.onFacebookTap, + this.compactMode = false, }); @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: Navigator.canPop(context) ? IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + ), + child: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), + ), onPressed: () => Navigator.pop(context), ) : null, ), - body: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _buildHeader(), - const SizedBox(height: 32), - useCard ? _buildCardContainer() : _buildTransparentContainer(), - const SizedBox(height: 32), - if (footerContent != null) footerContent!, - ], + body: LayoutBuilder( + builder: (context, constraints) { + final isCompact = compactMode || constraints.maxHeight <= 780; + + return Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, ), - ), - ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB(20.0, isCompact ? 8.0 : 16.0, 20.0, isCompact ? 16.0 : 36.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildHeader(context, isCompact), + SizedBox(height: isCompact ? 16 : 28), + useCard + ? _buildCardContainer(context, isCompact) + : _buildTransparentContainer(context, isCompact), + SizedBox(height: isCompact ? 12 : 24), + if (footerContent != null) footerContent!, + ], + ), + ), + ), + ), + ); + }, ), ); } - Widget _buildHeader() { + Widget _buildHeader(BuildContext context, bool isCompact) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Column( children: [ customHeaderIcon ?? Container( - width: 80, - height: 80, + width: isCompact ? 64 : 80, + height: isCompact ? 64 : 80, decoration: BoxDecoration( - color: AppColors.white, + color: isDark ? const Color(0xFF1E2B47) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.1), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.14), blurRadius: 20, offset: const Offset(0, 10), ), ], ), - child: const Center( - child: Icon(Icons.task_alt, size: 48, color: AppColors.primary), + child: Center( + child: Icon( + Icons.task_alt, + size: isCompact ? 36 : 48, + color: Theme.of(context).colorScheme.primary, + ), ), ), - const SizedBox(height: 24), + SizedBox(height: isCompact ? 12 : 24), Text( title, - style: const TextStyle( - fontSize: 28, + style: TextStyle( + fontSize: isCompact ? 24 : 28, fontWeight: FontWeight.w800, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, letterSpacing: -0.5, ), ), - const SizedBox(height: 8), + SizedBox(height: isCompact ? 4 : 8), Text( subtitle, - style: const TextStyle( - fontSize: 14, + style: TextStyle( + fontSize: isCompact ? 13 : 14, fontWeight: FontWeight.w500, - color: AppColors.textSecondary, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), textAlign: TextAlign.center, ), @@ -113,50 +154,60 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildCardContainer() { + Widget _buildCardContainer(BuildContext context, bool isCompact) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( - padding: const EdgeInsets.all(32), + padding: EdgeInsets.all(isCompact ? 20 : 32), decoration: BoxDecoration( - color: AppColors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(32), + border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) : null, boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.08), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.12), blurRadius: 30, offset: const Offset(0, 10), ), ], ), - child: _buildFormElements(), + child: _buildFormElements(context, isCompact), ); } - Widget _buildTransparentContainer() => _buildFormElements(); + Widget _buildTransparentContainer(BuildContext context, bool isCompact) => + _buildFormElements(context, isCompact); + + Widget _buildFormElements(BuildContext context, bool isCompact) { + final isDark = Theme.of(context).brightness == Brightness.dark; - Widget _buildFormElements() { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ formContent, - const SizedBox(height: 16), + SizedBox(height: isCompact ? 12 : 16), ElevatedButton( // Disable button if loading onPressed: isLoading ? null : onSubmit, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, - disabledBackgroundColor: AppColors.primary.withOpacity(0.6), - padding: const EdgeInsets.symmetric(vertical: 20), + backgroundColor: Theme.of(context).colorScheme.primary, + disabledBackgroundColor: + Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), + padding: EdgeInsets.symmetric(vertical: isCompact ? 14 : 20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), - elevation: isLoading ? 0 : 4, + elevation: isLoading ? 0 : (isDark ? 8 : 4), + shadowColor: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.35) + : null, ), child: isLoading - ? const SizedBox( + ? SizedBox( height: 20, width: 20, child: CircularProgressIndicator( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, strokeWidth: 2, ), ) @@ -165,45 +216,59 @@ class AuthLayoutTemplate extends StatelessWidget { children: [ Text( submitText, - style: const TextStyle( - fontSize: 16, + style: TextStyle( + fontSize: isCompact ? 15 : 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), const SizedBox(width: 8), - const Icon( + Icon( Icons.arrow_forward, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, size: 20, ), ], ), ), if (showSocial) ...[ - const SizedBox(height: 32), - const Row( + SizedBox(height: isCompact ? 16 : 32), + Row( children: [ - Expanded(child: Divider(color: AppColors.border)), + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: EdgeInsets.symmetric(horizontal: isCompact ? 12 : 16), child: Text( 'OR', style: TextStyle( fontSize: 10, fontWeight: FontWeight.bold, - color: AppColors.textSecondary, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), ), - Expanded(child: Divider(color: AppColors.border)), + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), ], ), - const SizedBox(height: 24), + SizedBox(height: isCompact ? 12 : 24), Row( children: [ Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: EdgeInsets.symmetric(vertical: isCompact ? 10 : 14), + ), onPressed: onGoogleTap, icon: const Icon( Icons.g_mobiledata, @@ -213,9 +278,19 @@ class AuthLayoutTemplate extends StatelessWidget { label: const Text('Google'), ), ), - const SizedBox(width: 16), + SizedBox(width: isCompact ? 10 : 16), Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: EdgeInsets.symmetric(vertical: isCompact ? 10 : 14), + ), onPressed: onFacebookTap, icon: const Icon(Icons.facebook, color: Color(0xFF1877F2)), label: const Text('Facebook'), diff --git a/src/lib/core/theme/custom_text_field.dart b/src/lib/core/theme/custom_text_field.dart index 7e98bcf..05a651d 100644 --- a/src/lib/core/theme/custom_text_field.dart +++ b/src/lib/core/theme/custom_text_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// A highly reusable text input field component. class CustomTextField extends StatelessWidget { @@ -24,6 +23,8 @@ class CustomTextField extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Padding( padding: const EdgeInsets.only(bottom: 16), child: Column( @@ -36,7 +37,10 @@ class CustomTextField extends StatelessWidget { style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, - color: AppColors.textDark.withOpacity(0.6), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: isDark ? 0.9 : 0.8), letterSpacing: 1, ), ), @@ -44,26 +48,29 @@ class CustomTextField extends StatelessWidget { TextFormField( controller: controller, obscureText: obscureText, - style: const TextStyle( - color: AppColors.textDark, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w600, fontSize: 16, ), decoration: InputDecoration( hintText: hint, hintStyle: TextStyle( - color: AppColors.textDark.withOpacity(0.3), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.65), fontWeight: FontWeight.w400, fontSize: 16, ), filled: true, - fillColor: AppColors.inputBackground, - prefixIcon: Icon(icon, color: AppColors.primary), + fillColor: isDark ? const Color(0xFF344765) : Theme.of(context).colorScheme.surface, + prefixIcon: Icon(icon, color: Theme.of(context).colorScheme.primary), suffixIcon: isPassword ? IconButton( icon: Icon( obscureText ? Icons.visibility_off : Icons.visibility, - color: Colors.grey, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), onPressed: onToggleVisibility, ) @@ -73,18 +80,22 @@ class CustomTextField extends StatelessWidget { horizontal: 16, ), border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), + borderRadius: BorderRadius.circular(24), borderSide: BorderSide.none, ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide(color: AppColors.border), + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide( + color: isDark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide( - color: AppColors.primary, - width: 2, + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + width: 1.5, ), ), ), diff --git a/src/lib/core/theme/theme_provider.dart b/src/lib/core/theme/theme_provider.dart new file mode 100644 index 0000000..d265fea --- /dev/null +++ b/src/lib/core/theme/theme_provider.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class ThemeProvider extends ChangeNotifier { + + static const String _themeKey = "theme_mode"; + + ThemeMode _themeMode = ThemeMode.light; + + ThemeMode get themeMode => _themeMode; + + ThemeProvider() { + _loadThemeFromPrefs(); + } + + // func change theme + void updateTheme(String appearance) { + final normalized = appearance.trim().toLowerCase(); + + if (normalized == 'dark') { + _themeMode = ThemeMode.dark; + } else if (normalized == 'light') { + _themeMode = ThemeMode.light; + } else { + _themeMode = ThemeMode.system; + } + + _saveThemeToPrefs( + _themeMode == ThemeMode.dark + ? 'Dark' + : _themeMode == ThemeMode.light + ? 'Light' + : 'System', + ); + notifyListeners(); + } + + Future _saveThemeToPrefs(String appearance) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_themeKey, appearance); + } + + // load theme when user open app + Future _loadThemeFromPrefs() async { + final prefs = await SharedPreferences.getInstance(); + final appearance = (prefs.getString(_themeKey) ?? 'Light').trim().toLowerCase(); + + if (appearance == 'dark') { + _themeMode = ThemeMode.dark; + } else if (appearance == 'system') { + _themeMode = ThemeMode.system; + } else { + _themeMode = ThemeMode.light; + } + notifyListeners(); + } +} \ No newline at end of file diff --git a/src/lib/core/utils/adaptive_color_extension.dart b/src/lib/core/utils/adaptive_color_extension.dart new file mode 100644 index 0000000..f5c022e --- /dev/null +++ b/src/lib/core/utils/adaptive_color_extension.dart @@ -0,0 +1,11 @@ +import 'package:flutter/material.dart'; + +extension AdaptiveColorExtension on Color { + Color toAdaptiveColor(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + if (!isDark) return this; + + return Color.lerp(this, Colors.white, 0.4) ?? this; + } +} + diff --git a/src/lib/core/widgets/custom_input_field.dart b/src/lib/core/widgets/custom_input_field.dart index 29bb775..3552a50 100644 --- a/src/lib/core/widgets/custom_input_field.dart +++ b/src/lib/core/widgets/custom_input_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../theme/app_colors.dart'; class CustomInputField extends StatelessWidget { final String label; @@ -32,8 +31,11 @@ class CustomInputField extends StatelessWidget { contentPadding: EdgeInsets.zero, enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.black26)), - focusedBorder: const UnderlineInputBorder( - borderSide: BorderSide(color: AppColors.primaryBlue)), + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + ), + ), ), ), ], diff --git a/src/lib/features/auth/otp_verification_view.dart b/src/lib/features/auth/otp_verification_view.dart index 1f80d61..0f96ea4 100644 --- a/src/lib/features/auth/otp_verification_view.dart +++ b/src/lib/features/auth/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../core/theme/app_colors.dart'; import '../auth/viewmodels/auth_viewmodels.dart'; import '../auth/presentation/view/new_password_view.dart'; @@ -18,18 +17,21 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'OTP Verification', style: TextStyle( - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, fontSize: 18, ), @@ -46,24 +48,26 @@ class _OtpVerificationViewState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon( + Icon( Icons.mark_email_read, size: 80, - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, ), const SizedBox(height: 32), - const Text( + Text( 'Enter 8-digit code', // Show correct 8-digit count style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), ), const SizedBox(height: 8), - const Text( + Text( 'The code has been sent to your email.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -117,28 +121,28 @@ class _OtpVerificationViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), child: _vm.isLoading - ? const CircularProgressIndicator( - color: AppColors.white, + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, ) - : const Text( + : Text( 'CONFIRM', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), ), @@ -154,24 +158,31 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( + SnackBar( content: Text('OTP code resent!'), - backgroundColor: AppColors.success, + backgroundColor: Theme.of(context).colorScheme.tertiary, ), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Resend code', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) ], @@ -190,9 +201,9 @@ class _OtpVerificationViewState extends State { width: boxWidth, // Use calculated width height: 48, decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all(color: Theme.of(context).colorScheme.outline), ), child: TextField( onChanged: (value) { @@ -205,10 +216,10 @@ class _OtpVerificationViewState extends State { FocusScope.of(context).previousFocus(); } }, - style: const TextStyle( + style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), keyboardType: TextInputType.number, textAlign: TextAlign.center, diff --git a/src/lib/features/auth/presentation/view/forgot_password_view.dart b/src/lib/features/auth/presentation/view/forgot_password_view.dart index bc105ca..8029cca 100644 --- a/src/lib/features/auth/presentation/view/forgot_password_view.dart +++ b/src/lib/features/auth/presentation/view/forgot_password_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -16,6 +15,8 @@ class _ForgotPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -26,12 +27,23 @@ class _ForgotPasswordViewState extends State { isLoading: _vm.isLoading, customHeaderIcon: Container( width: 120, height: 120, - decoration: const BoxDecoration( - color: AppColors.white, + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1B2A46) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Color(0xFFD1D9E6), blurRadius: 16)], + boxShadow: [ + BoxShadow( + color: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.22) + : const Color(0xFFD1D9E6), + blurRadius: 24, + ) + ], + ), + child: Icon( + Icons.lock_reset, + size: 64, + color: Theme.of(context).colorScheme.primary, ), - child: const Icon(Icons.lock_reset, size: 64, color: AppColors.primary), ), onSubmit: () async { FocusScope.of(context).unfocus(); // Đóng bàn phím @@ -45,7 +57,12 @@ class _ForgotPasswordViewState extends State { Navigator.push(context, MaterialPageRoute(builder: (_) => const OtpVerificationView())); } else { // Có lỗi (như nhập sai định dạng, spam nút) -> Vã cái lỗi màu đỏ ra - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: CustomTextField( @@ -54,15 +71,34 @@ class _ForgotPasswordViewState extends State { icon: Icons.mail, controller: _vm.emailCtrl, ), - footerContent: const Padding( - padding: EdgeInsets.only(bottom: 24.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.help, size: 16, color: AppColors.primary), - SizedBox(width: 4), - Text('Cần hỗ trợ? Liên hệ CSKH', style: TextStyle(color: AppColors.textSecondary, fontSize: 14, fontWeight: FontWeight.bold)), - ], + footerContent: Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF111E37) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.help, + size: 16, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Cần hỗ trợ? Liên hệ CSKH', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + ], + ), ), ), ), diff --git a/src/lib/features/auth/presentation/view/login_view.dart b/src/lib/features/auth/presentation/view/login_view.dart index 8d39494..c315fd9 100644 --- a/src/lib/features/auth/presentation/view/login_view.dart +++ b/src/lib/features/auth/presentation/view/login_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -23,18 +22,29 @@ class _LoginViewState extends State { title: 'Task Management', subtitle: 'Chào mừng trở lại!', submitText: 'Đăng nhập', + compactMode: true, isLoading: _vm.isLoading, showSocial: true, onGoogleTap: () async { final error = await _vm.loginWithGoogle(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onFacebookTap: () async { final error = await _vm.loginWithFacebook(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onSubmit: () async { @@ -43,11 +53,21 @@ class _LoginViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng nhập thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng nhập thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // If LoginView was pushed on top of AuthGate, pop back to root so MainScreen is visible. Navigator.of(context).popUntil((route) => route.isFirst); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -60,28 +80,58 @@ class _LoginViewState extends State { ), TextButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const ForgotPasswordView())), - child: const Text('Quên mật khẩu?', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold)), + style: TextButton.styleFrom(minimumSize: const Size(50, 40), padding: const EdgeInsets.symmetric(horizontal: 4)), + child: Text( + 'Quên mật khẩu?', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ), ], ), - footerContent: _buildFooter('Chưa có tài khoản? ', 'Đăng ký ngay', () { - Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); - }), + footerContent: _buildFooter( + context, + 'Chưa có tài khoản? ', + 'Đăng ký ngay', + () { + Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); + }, + ), ), ); } - Widget _buildFooter(String text, String action, VoidCallback onTap) { + Widget _buildFooter( + BuildContext context, + String text, + String action, + VoidCallback onTap, + ) { return Padding( - padding: const EdgeInsets.only(bottom: 24.0), + padding: const EdgeInsets.only(bottom: 14.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(text, style: const TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + text, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 15, + ), + ), TextButton( onPressed: onTap, - style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: Text(action, style: const TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + style: TextButton.styleFrom(minimumSize: const Size(50, 40)), + child: Text( + action, + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 15, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/new_password_view.dart b/src/lib/features/auth/presentation/view/new_password_view.dart index dbe9bfc..64c6e84 100644 --- a/src/lib/features/auth/presentation/view/new_password_view.dart +++ b/src/lib/features/auth/presentation/view/new_password_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -16,6 +15,8 @@ class _NewPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -23,10 +24,14 @@ class _NewPasswordViewState extends State { subtitle: 'Mật khẩu mới phải khác với mật khẩu cũ', submitText: 'Cập nhật', isLoading: _vm.isLoading, - customHeaderIcon: const CircleAvatar( + customHeaderIcon: CircleAvatar( radius: 40, - backgroundColor: Color(0xFFEBF2FF), - child: Icon(Icons.lock_reset, size: 40, color: AppColors.primary), + backgroundColor: isDark ? const Color(0xFF213A63) : const Color(0xFFEBF2FF), + child: Icon( + Icons.lock_reset, + size: 40, + color: Theme.of(context).colorScheme.primary, + ), ), onSubmit: () async { FocusScope.of(context).unfocus(); @@ -37,12 +42,22 @@ class _NewPasswordViewState extends State { if (errorMessage == null) { // Null -> Thành công -> Báo xanh mướt - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đổi mật khẩu thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đổi mật khẩu thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Cú đá chót: Xóa hết lịch sử trang, đá thẳng mặt về trang Login (isFirst) Navigator.popUntil(context, (route) => route.isFirst); } else { // Nếu lỗi do User nhập lệch pass -> Chửi - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -59,15 +74,30 @@ class _NewPasswordViewState extends State { Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: const Color(0xFFEBF2FF), + color: isDark + ? const Color(0xFF223A63) + : const Color(0xFFEBF2FF), borderRadius: BorderRadius.circular(12), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.25)) + : null, ), - child: const Row( + child: Row( children: [ - Icon(Icons.info, color: AppColors.primary, size: 16), - SizedBox(width: 8), + Icon( + Icons.info, + color: Theme.of(context).colorScheme.primary, + size: 16, + ), + const SizedBox(width: 8), Expanded( - child: Text('Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', style: TextStyle(fontSize: 12, color: AppColors.primary)), + child: Text( + 'Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/otp_verification_view.dart b/src/lib/features/auth/presentation/view/otp_verification_view.dart index b8bb7b7..6bd64c8 100644 --- a/src/lib/features/auth/presentation/view/otp_verification_view.dart +++ b/src/lib/features/auth/presentation/view/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodels/auth_viewmodels.dart'; import 'new_password_view.dart'; @@ -15,40 +14,69 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'Xác thực OTP', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 18), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.bold, + fontSize: 18, + ), ), centerTitle: true, ), - body: AnimatedBuilder( - animation: _vm, - builder: (context, child) { - return SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.mark_email_read, size: 80, color: AppColors.primary), + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: AnimatedBuilder( + animation: _vm, + builder: (context, child) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.mark_email_read, + size: 80, + color: Theme.of(context).colorScheme.primary, + ), const SizedBox(height: 32), - const Text( + Text( 'Nhập mã 8 số', // Sửa chữ thành 8 số - style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), ), const SizedBox(height: 8), - const Text( + Text( 'Mã đã được gửi đến email của bạn.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -73,20 +101,34 @@ class _OtpVerificationViewState extends State { ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + elevation: isDark ? 10 : null, + shadowColor: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.35), ), child: _vm.isLoading - ? const CircularProgressIndicator(color: AppColors.white) - : const Text( + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, + ) + : Text( 'XÁC NHẬN', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppColors.white), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.surface, + ), ), ), const SizedBox(height: 16), @@ -98,25 +140,39 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Đã gửi lại mã OTP!'), backgroundColor: AppColors.success), + SnackBar( + content: const Text('Đã gửi lại mã OTP!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Gửi lại mã', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) - ], + ], + ), ), - ), - ); - } + ); + } + ), ), ); } @@ -125,9 +181,15 @@ class _OtpVerificationViewState extends State { return Container( width: 35, height: 48, // Thu nhỏ kích thước ô lại để nhét vừa 8 ô trên 1 dòng decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF344765) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all( + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), child: TextField( onChanged: (value) { @@ -137,7 +199,11 @@ class _OtpVerificationViewState extends State { if (value.isNotEmpty && index < 7) FocusScope.of(context).nextFocus(); if (value.isEmpty && index > 0) FocusScope.of(context).previousFocus(); }, - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), keyboardType: TextInputType.number, textAlign: TextAlign.center, inputFormatters: [ diff --git a/src/lib/features/auth/presentation/view/register_view.dart b/src/lib/features/auth/presentation/view/register_view.dart index 17dfc88..d5125d7 100644 --- a/src/lib/features/auth/presentation/view/register_view.dart +++ b/src/lib/features/auth/presentation/view/register_view.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -21,6 +21,7 @@ class _RegisterViewState extends State { title: 'Tạo tài khoản mới', subtitle: 'Bắt đầu quản lý công việc khoa học', submitText: 'Đăng ký', + compactMode: true, isLoading: _vm.isLoading, showSocial: true, onSubmit: () async { @@ -29,11 +30,21 @@ class _RegisterViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng ký thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng ký thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Return to the existing LoginView to avoid stacking duplicate login routes. Navigator.pop(context); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -51,15 +62,28 @@ class _RegisterViewState extends State { ], ), footerContent: Padding( - padding: const EdgeInsets.only(bottom: 24.0), + padding: const EdgeInsets.only(bottom: 14.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text('Đã có tài khoản? ', style: TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + 'Đã có tài khoản? ', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 15, + ), + ), TextButton( onPressed: () => Navigator.pop(context), - style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: const Text('Đăng nhập', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + style: TextButton.styleFrom(minimumSize: const Size(50, 40)), + child: Text( + 'Đăng nhập', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 15, + ), + ), ), ], ), diff --git a/src/lib/features/category/model/category_model.dart b/src/lib/features/category/model/category_model.dart new file mode 100644 index 0000000..7bcef4f --- /dev/null +++ b/src/lib/features/category/model/category_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class CategoryModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const CategoryModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory CategoryModel.fromJson(Map json) { + return CategoryModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#5A8DF3', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF5A8DF3); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF5A8DF3); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/category/repository/category_repository.dart b/src/lib/features/category/repository/category_repository.dart new file mode 100644 index 0000000..cbfeb93 --- /dev/null +++ b/src/lib/features/category/repository/category_repository.dart @@ -0,0 +1,26 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/category_model.dart'; + +class CategoryRepository { + final SupabaseClient _client; + + CategoryRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchCategories() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('category') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => CategoryModel.fromJson(Map.from(e))) + .toList(); + } +} + diff --git a/src/lib/features/category/view/widgets/category_choice_chips.dart b/src/lib/features/category/view/widgets/category_choice_chips.dart new file mode 100644 index 0000000..e9ecf26 --- /dev/null +++ b/src/lib/features/category/view/widgets/category_choice_chips.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; + +import '../../model/category_model.dart'; + +class CategoryChoiceChips extends StatelessWidget { + const CategoryChoiceChips({ + super.key, + required this.categories, + required this.selectedCategoryId, + required this.onSelected, + }); + + final List categories; + final int? selectedCategoryId; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 40, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: categories.length, + itemBuilder: (context, index) { + final category = categories[index]; + final adaptiveColor = category.color.toAdaptiveColor(context); + final isSelected = category.id == selectedCategoryId; + return Padding( + padding: const EdgeInsets.only(right: 10), + child: ChoiceChip( + label: Text(category.name), + selected: isSelected, + onSelected: (selected) { + if (selected) onSelected(category); + }, + backgroundColor: adaptiveColor.withValues(alpha: 0.15), + selectedColor: adaptiveColor, + labelStyle: TextStyle( + color: isSelected ? Colors.white : adaptiveColor, + fontSize: 14, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: BorderSide( + color: adaptiveColor.withValues(alpha: 0.4), + width: 1, + ), + ), + showCheckmark: false, + ), + ); + }, + ), + ); + } +} + diff --git a/src/lib/features/category/viewmodel/category_viewmodel.dart b/src/lib/features/category/viewmodel/category_viewmodel.dart new file mode 100644 index 0000000..c9e1dc0 --- /dev/null +++ b/src/lib/features/category/viewmodel/category_viewmodel.dart @@ -0,0 +1,41 @@ +import 'package:flutter/foundation.dart'; + +import '../model/category_model.dart'; +import '../repository/category_repository.dart'; + +class CategoryViewModel extends ChangeNotifier { + final CategoryRepository _repository; + + CategoryViewModel({CategoryRepository? repository}) + : _repository = repository ?? CategoryRepository(); + + final List _categories = []; + + List get categories => List.unmodifiable(_categories); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadCategories() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchCategories(); + _categories + ..clear() + ..addAll(data); + } catch (e) { + _error = e.toString(); + _categories.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } +} + diff --git a/src/lib/features/chatbot/model/chatmessage_model.dart b/src/lib/features/chatbot/model/chatmessage_model.dart new file mode 100644 index 0000000..2fb31ae --- /dev/null +++ b/src/lib/features/chatbot/model/chatmessage_model.dart @@ -0,0 +1,46 @@ +import 'dart:convert'; + +class ChatMessageModel { + final String text; + final bool isUser; + final DateTime timestamp; + + ChatMessageModel({ + required this.text, + required this.isUser, + DateTime? timestamp, + }) : timestamp = timestamp ?? DateTime.now(); + + factory ChatMessageModel.fromJson(Map json) { + final parsedTimestamp = + DateTime.tryParse(json['timestamp']?.toString() ?? '') ?? DateTime.now(); + + return ChatMessageModel( + text: json['text']?.toString() ?? '', + isUser: json['isUser'] as bool? ?? true, + timestamp: parsedTimestamp, + ); + } + + Map toJson() { + return { + 'text': text, + 'isUser': isUser, + 'timestamp': timestamp.toIso8601String(), + }; + } + + static String encodeList(List messages) { + return jsonEncode(messages.map((message) => message.toJson()).toList()); + } + + static List decodeList(String raw) { + final decoded = jsonDecode(raw); + if (decoded is! List) return []; + + return decoded + .whereType() + .map((item) => ChatMessageModel.fromJson(Map.from(item))) + .toList(); + } +} diff --git a/src/lib/features/chatbot/services/chatbot_services.dart b/src/lib/features/chatbot/services/chatbot_services.dart new file mode 100644 index 0000000..c37a31f --- /dev/null +++ b/src/lib/features/chatbot/services/chatbot_services.dart @@ -0,0 +1,143 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:google_generative_ai/google_generative_ai.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class ChatBotAssistantService { + final String _apiKey = (dotenv.env['GEMINI_API_KEY'] ?? '').trim(); + GenerativeModel? _model; + ChatSession? _chatSession; + + ChatBotAssistantService() { + if (_apiKey.isEmpty) { + debugPrint("Forget to set GEMINI_API_KEY in .env file"); + return; + } + + _model = GenerativeModel( + apiKey: _apiKey, + model: 'gemini-2.5-flash', + tools: [ + Tool( + functionDeclarations: [ + FunctionDeclaration( + 'create_task_full', + 'Tạo một công việc mới. Hãy tự động trích xuất tên công việc, suy luận độ ưu tiên (1-Thấp, 2-Trung bình, 3-Cao) và các thẻ (tags) dựa trên câu nói của người dùng.', + Schema( + SchemaType.object, + properties: { + 'title': Schema( + SchemaType.string, + description: 'Tên công việc cần làm', + ), + 'priority': Schema( + SchemaType.integer, + description: + 'Độ ưu tiên: 1 (Thấp), 2 (Trung bình), 3 (Cao). Nếu người dùng không nói rõ, mặc định là 1.', + ), + 'tags': Schema( + SchemaType.array, + items: Schema(SchemaType.string), + description: + 'Danh sách các thẻ phân loại (ví dụ: ["Học tập", "Gấp", "Backend"]). Gửi mảng rỗng [] nếu không có.', + ), + 'start_time': Schema( + SchemaType.string, + description: + 'Thời gian bắt đầu công việc theo định dạng ISO 8601 (VD: 2026-04-18T15:00:00Z). Nếu người dùng không nói, hãy bỏ qua hoặc để rỗng.', + ), + 'due_time': Schema( + SchemaType.string, + description: + 'Thời gian kết thúc (deadline) theo định dạng ISO 8601. Nếu không có, bỏ qua.', + ), + 'category_name': Schema( + SchemaType.string, + description: + 'Phân loại công việc vào 1 trong 4 nhóm: "Cá nhân", "Học tập", "Công việc", hoặc "Giải trí". Nếu không phân loại được, mặc định trả về "Cá nhân".', + ), + }, + requiredProperties: ['title', 'priority', 'tags'], + ), + ), + ], + ), + ], + systemInstruction: Content.system( + 'Bạn là một chuyên gia quản lý thời gian và trợ lý năng suất cho ứng dụng Task Management. ' + 'Nhiệm vụ của bạn là đưa ra lời khuyên ngắn gọn (dưới 100 chữ), thực tế để giúp người dùng ' + 'hoàn thành công việc. Trả lời bằng tiếng Việt thân thiện, nhiệt tình. ' + 'Từ chối mọi câu hỏi không liên quan đến công việc hoặc quản lý thời gian.', + ), + ); + + _chatSession = _model!.startChat(); + } + + Future sendMessage(String userMessage) async { + if (_chatSession == null) { + return 'Chatbot chưa được cấu hình API key. Vui lòng kiểm tra file .env.'; + } + + try { + final response = await _chatSession!.sendMessage( + Content.text(userMessage), + ); + + if (response.functionCalls.isNotEmpty) { + final functionCall = response.functionCalls.first; + if (functionCall.name == 'create_task_full') { + final args = functionCall.args; + final title = args['title'] as String; + final priority = (args['priority'] as num?)?.toInt() ?? 1; + final rawTags = args['tags'] as List? ?? []; + final tags = rawTags.map((e) => e.toString()).toList(); + final startTime = args['start_time'] as String?; + final dueTime = args['due_time'] as String?; + + final userId = Supabase.instance.client.auth.currentUser?.id; + if (userId == null) { + return 'Vui lòng đăng nhập để tạo công việc.'; + } + final categoryName = args['category_name'] as String? ?? 'Cá nhân'; + final dbResponse = await Supabase.instance.client.rpc( + 'create_task_full', + params: { + 'p_title': args['title'], + 'p_priority': (args['priority'] as num?)?.toInt() ?? 1, + 'p_profile_id': userId, + 'p_tag_names': + (args['tags'] as List?)?.map((e) => e.toString()).toList() ?? + [], + 'p_category_name': categoryName, + 'p_start_time': args['start_time'], + 'p_due_time': args['due_time'], + }, + ); + + final isSuccess = dbResponse['success'] == true; + if (!isSuccess) { + debugPrint("Lỗi từ Supabase: ${dbResponse['error']}"); + } + final functionResponse = await _chatSession!.sendMessage( + Content.functionResponse('create_task_full', { + 'status': isSuccess ? 'Thành công' : 'Thất bại', + + 'reason': isSuccess ? '' : dbResponse['error'].toString(), + }), + ); + return functionResponse.text ?? 'Đã xử lý xong yêu cầu của bạn!'; + } + } + return response.text ?? 'Xin lỗi, trợ lý đang bận xíu. Thử lại sau nhé!'; + } catch (e) { + final errorString = e.toString(); + if (errorString.contains('503')) { + return 'Bạn đợi vài phút rồi chat lại nhé!'; + } else if (errorString.contains('429')) { + return 'Bạn chat nhanh quá! Vui lòng chờ chút'; + } + return 'Lỗi kết nối AI: $e'; + } + } +} diff --git a/src/lib/features/chatbot/view/chatbot_view.dart b/src/lib/features/chatbot/view/chatbot_view.dart new file mode 100644 index 0000000..f5e104a --- /dev/null +++ b/src/lib/features/chatbot/view/chatbot_view.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/chat_header.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/day_separator.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_composer.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_tile.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/typing_indicator.dart'; + +import '../viewmodel/chatbot_viewmodel.dart'; + +class ChatBotView extends StatelessWidget { + const ChatBotView({super.key, this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (_) => ChatBotViewModel(), + child: _ChatBotViewBody(userAvatarUrl: userAvatarUrl), + ); + } +} + +class _ChatBotViewBody extends StatefulWidget { + const _ChatBotViewBody({this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + State<_ChatBotViewBody> createState() => _ChatBotViewBodyState(); +} + +class _ChatBotViewBodyState extends State<_ChatBotViewBody> { + final TextEditingController _controller = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + void _scrollToBottom() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + Future _sendMessage(ChatBotViewModel viewModel) async { + final text = _controller.text.trim(); + if (text.isEmpty || viewModel.isLoading) return; + + _controller.clear(); + _scrollToBottom(); + + await viewModel.sendMessage(text); + if (!mounted) return; + + _scrollToBottom(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Scaffold( + backgroundColor: theme.scaffoldBackgroundColor, + body: SafeArea( + child: Column( + children: [ + const ChatHeader(), + Divider(height: 1, color: scheme.outline.withValues(alpha: 0.4)), + Expanded( + child: Consumer( + builder: (context, viewModel, _) { + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + itemCount: viewModel.messages.length + 1, + itemBuilder: (context, index) { + if (index == 0) { + return const Padding( + padding: EdgeInsets.only(bottom: 16), + child: DaySeparator(label: 'Today'), + ); + } + + final message = viewModel.messages[index - 1]; + return MessageTile( + message: message, + userAvatarUrl: widget.userAvatarUrl, + ); + }, + ); + }, + ), + ), + Consumer( + builder: (context, viewModel, _) { + if (!viewModel.isLoading) return const SizedBox.shrink(); + return const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 12), + child: TypingIndicator(), + ); + }, + ), + Consumer( + builder: (context, viewModel, _) { + return MessageComposer( + controller: _controller, + isSending: viewModel.isLoading, + onSend: () => _sendMessage(viewModel), + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/src/lib/features/chatbot/view/widgets/bot_avatar.dart b/src/lib/features/chatbot/view/widgets/bot_avatar.dart new file mode 100644 index 0000000..d689144 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/bot_avatar.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; + +class BotAvatar extends StatelessWidget { + const BotAvatar({super.key, required this.size}); + + final double size; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + alignment: Alignment.center, + child: Icon( + Icons.smart_toy_rounded, + size: size * 0.58, + color: scheme.primary, + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/chat_header.dart b/src/lib/features/chatbot/view/widgets/chat_header.dart new file mode 100644 index 0000000..35e83ff --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/chat_header.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class ChatHeader extends StatelessWidget { + const ChatHeader({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 10), + child: Row( + children: [ + const BotAvatar(size: 48), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'TaskBot', + style: theme.textTheme.headlineSmall?.copyWith( + color: scheme.primary, + fontWeight: FontWeight.w800, + ), + ), + Text( + 'ONLINE AI ASSISTANT', + style: theme.textTheme.labelLarge?.copyWith( + color: scheme.tertiary, + letterSpacing: 0.6, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/day_separator.dart b/src/lib/features/chatbot/view/widgets/day_separator.dart new file mode 100644 index 0000000..351c129 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/day_separator.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; + +class DaySeparator extends StatelessWidget { + const DaySeparator({super.key, required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + label, + style: TextStyle( + color: scheme.onSurfaceVariant, + fontWeight: FontWeight.w600, + ), + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_composer.dart b/src/lib/features/chatbot/view/widgets/message_composer.dart new file mode 100644 index 0000000..7b4988f --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_composer.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; + +class MessageComposer extends StatelessWidget { + const MessageComposer({ + super.key, + required this.controller, + required this.onSend, + required this.isSending, + }); + + final TextEditingController controller; + final VoidCallback onSend; + final bool isSending; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 0, 16, 14), + child: Container( + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(22), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.14), + blurRadius: 14, + offset: const Offset(0, 4), + ), + ], + ), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + child: Row( + children: [ + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.add_circle, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + Expanded( + child: TextField( + controller: controller, + textInputAction: TextInputAction.send, + enabled: !isSending, + onSubmitted: (_) => onSend(), + style: TextStyle(color: scheme.onSurface), + decoration: InputDecoration( + hintText: 'Type a message or ask for help...', + hintStyle: TextStyle(color: scheme.onSurfaceVariant), + border: InputBorder.none, + ), + ), + ), + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.mic, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + SizedBox( + width: 44, + height: 44, + child: ElevatedButton( + onPressed: isSending ? null : onSend, + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + padding: EdgeInsets.zero, + backgroundColor: scheme.primary, + foregroundColor: scheme.onPrimary, + ), + child: Icon( + Icons.send_rounded, + color: isSending + ? scheme.onPrimary.withValues(alpha: 0.7) + : scheme.onPrimary, + ), + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_tile.dart b/src/lib/features/chatbot/view/widgets/message_tile.dart new file mode 100644 index 0000000..74546a2 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_tile.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; + +import '../../model/chatmessage_model.dart'; +import 'bot_avatar.dart'; +import 'user_avatar.dart'; + +class MessageTile extends StatelessWidget { + const MessageTile({super.key, required this.message, this.userAvatarUrl}); + + final ChatMessageModel message; + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final isUser = message.isUser; + final crossAxis = isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start; + + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: LayoutBuilder( + builder: (context, constraints) { + final maxBubbleWidth = constraints.maxWidth * 0.72; + + Widget bubble() { + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxBubbleWidth), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration( + color: isUser ? scheme.primary : scheme.surface, + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.12), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], + ), + child: Text( + _breakLongTokens(message.text), + softWrap: true, + style: theme.textTheme.titleMedium?.copyWith( + height: 1.45, + color: isUser ? scheme.onPrimary : scheme.onSurface, + ), + ), + ), + ); + } + + return Column( + crossAxisAlignment: crossAxis, + children: [ + if (isUser) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: bubble(), + ), + ), + const SizedBox(width: 10), + UserAvatar(size: 36, avatarUrl: userAvatarUrl), + ], + ) + else + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const BotAvatar(size: 36), + const SizedBox(width: 10), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: bubble(), + ), + ), + ], + ), + const SizedBox(height: 6), + Padding( + padding: EdgeInsets.only(left: isUser ? 0 : 46, right: isUser ? 46 : 0), + child: Text( + _formatTime(context, message.timestamp), + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ], + ); + }, + ), + ); + } + + String _formatTime(BuildContext context, DateTime time) { + final localTime = TimeOfDay.fromDateTime(time); + return MaterialLocalizations.of(context).formatTimeOfDay(localTime); + } + + String _breakLongTokens(String input) { + final tokenRegex = RegExp(r'\S{24,}'); + return input.replaceAllMapped(tokenRegex, (match) { + final token = match.group(0) ?? ''; + final buffer = StringBuffer(); + for (int i = 0; i < token.length; i++) { + buffer.write(token[i]); + if ((i + 1) % 12 == 0 && i + 1 < token.length) { + buffer.write('\u200B'); + } + } + return buffer.toString(); + }); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/typing_indicator.dart b/src/lib/features/chatbot/view/widgets/typing_indicator.dart new file mode 100644 index 0000000..a35d7cc --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/typing_indicator.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class TypingIndicator extends StatelessWidget { + const TypingIndicator({super.key}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Row( + children: [ + const BotAvatar(size: 34), + const SizedBox(width: 10), + Flexible( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + 'TaskBot is typing...', + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onSurfaceVariant), + ), + ), + ), + ], + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/user_avatar.dart b/src/lib/features/chatbot/view/widgets/user_avatar.dart new file mode 100644 index 0000000..a8ae00b --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/user_avatar.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class UserAvatar extends StatelessWidget { + const UserAvatar({super.key, required this.size, this.avatarUrl}); + + final double size; + final String? avatarUrl; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final fallbackUrl = + (Supabase.instance.client.auth.currentUser?.userMetadata?['avatar_url'] as String?)?.trim(); + final resolvedUrl = (avatarUrl ?? fallbackUrl ?? '').trim(); + final canLoadNetworkImage = _isValidHttpUrl(resolvedUrl); + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + clipBehavior: Clip.antiAlias, + child: canLoadNetworkImage + ? Image.network( + resolvedUrl, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => Icon( + Icons.person, + size: size * 0.6, + color: scheme.primary, + ), + ) + : Icon(Icons.person, size: size * 0.6, color: scheme.primary), + ); + } + + bool _isValidHttpUrl(String value) { + if (value.isEmpty || value.length > 2048) return false; + final uri = Uri.tryParse(value); + if (uri == null) return false; + return uri.hasAbsolutePath && (uri.scheme == 'http' || uri.scheme == 'https'); + } +} + diff --git a/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart new file mode 100644 index 0000000..fd5a4d3 --- /dev/null +++ b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart @@ -0,0 +1,90 @@ +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../model/chatmessage_model.dart'; +import '../services/chatbot_services.dart'; + +class ChatBotViewModel extends ChangeNotifier { + static const String _historyKey = 'chatbot_history_v1'; + static const int _maxHistoryMessages = 200; + + final _aiService = ChatBotAssistantService(); + final List _messages = []; + + ChatBotViewModel() { + _loadHistory(); + } + + List _initialMessages() => [ + ChatMessageModel( + text: 'Chào bạn! Tôi là trợ lý năng suất. Hôm nay bạn cần tôi giúp gì?', + isUser: false, + ), + ]; + + List get messages => _messages; + + bool _isLoading = false; + + bool get isLoading => _isLoading; + + Future _loadHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_historyKey); + + if (raw == null || raw.trim().isEmpty) { + _messages + ..clear() + ..addAll(_initialMessages()); + await _saveHistory(); + } else { + final storedMessages = ChatMessageModel.decodeList(raw); + _messages + ..clear() + ..addAll( + storedMessages.isEmpty ? _initialMessages() : storedMessages, + ); + } + } catch (e) { + debugPrint('Error loading chatbot history: $e'); + _messages + ..clear() + ..addAll(_initialMessages()); + } + + notifyListeners(); + } + + Future _saveHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + if (_messages.length > _maxHistoryMessages) { + _messages.removeRange(0, _messages.length - _maxHistoryMessages); + } + await prefs.setString( + _historyKey, + ChatMessageModel.encodeList(_messages), + ); + } catch (e) { + debugPrint('Error saving chatbot history: $e'); + } + } + + Future sendMessage(String text) async { + final normalizedText = text.trim(); + if (normalizedText.isEmpty) return; + + _messages.add(ChatMessageModel(text: normalizedText, isUser: true)); + _isLoading = true; + notifyListeners(); + await _saveHistory(); + + final response = await _aiService.sendMessage(normalizedText); + + _messages.add(ChatMessageModel(text: response, isUser: false)); + _isLoading = false; + await _saveHistory(); + notifyListeners(); + } +} diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 8c8cffe..50c09e3 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -1,13 +1,18 @@ import 'package:flutter/material.dart'; +// import '../../../tasks/view/screens/home_screen.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/chatbot_view.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; -import 'settings_screen.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; + +import '../../../category/viewmodel/category_viewmodel.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; import '../../../statistics/view/screens/statistics_screen.dart'; -// import '../../../tasks/view/screens/home_screen.dart'; -import 'package:provider/provider.dart'; +import '../../../tag/viewmodel/tag_viewmodel.dart'; +import '../../../user/view/user_profile_view.dart'; +import 'settings_screen.dart'; class MainScreen extends StatefulWidget { const MainScreen({super.key}); @@ -21,42 +26,66 @@ class _MainScreenState extends State { final List _screens = [ const Center(child: HomeScreen()), - const Center(child: Text('Màn hình Lịch')), + const ChatBotView(), ChangeNotifierProvider( create: (_) => FocusViewModel(), child: const FocusScreen(), ), ChangeNotifierProvider( - create: (_) => StatisticsViewmodel(), - child: const StatisticsScreen(), + create: (_) => StatisticsViewmodel(), + child: const StatisticsScreen(), + ), + ChangeNotifierProvider( + create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), + child: const UserProfileView(), ), const SettingsScreen(), ]; + @override + void initState() { + super.initState(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().loadCategories(); + context.read().loadTags(); + }); + } + @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( extendBody: true, - body: IndexedStack( - index: _currentIndex, - children: _screens, - ), + body: IndexedStack(index: _currentIndex, children: _screens), bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), - boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 20, offset: const Offset(0, -5))], + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 20, + offset: const Offset(0, -5), + ), + ], ), child: SafeArea( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - _buildNavItem(Icons.checklist_rounded, 'Công việc', 0), - _buildNavItem(Icons.calendar_today_rounded, 'Lịch', 1), - _buildNavItem(Icons.timer_rounded, 'Tập trung', 2), - _buildNavItem(Icons.bar_chart_rounded, 'Thống kê', 3), - _buildNavItem(Icons.settings_rounded, 'Cài đặt', 4), + _buildNavItem(context, Icons.checklist_rounded, 'Công việc', 0), + _buildNavItem(context, Icons.smart_toy_rounded, 'Chat', 1), + _buildNavItem(context, Icons.timer_rounded, 'Tập trung', 2), + _buildNavItem(context, Icons.bar_chart_rounded, 'Thống kê', 3), + _buildNavItem(context, Icons.person_2_rounded, 'Cá nhân', 4), ], ), ), @@ -64,7 +93,12 @@ class _MainScreenState extends State { ); } - Widget _buildNavItem(IconData icon, String label, int index) { + Widget _buildNavItem( + BuildContext context, + IconData icon, + String label, + int index, + ) { bool isSelected = _currentIndex == index; return GestureDetector( @@ -72,27 +106,42 @@ class _MainScreenState extends State { child: AnimatedContainer( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, - padding: EdgeInsets.symmetric(horizontal: isSelected ? 15 : 10, vertical: 10), + padding: EdgeInsets.symmetric( + horizontal: isSelected ? 15 : 10, + vertical: 10, + ), decoration: BoxDecoration( - color: isSelected ? const Color(0xFFE8F0FE) : Colors.transparent, + color: isSelected + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF23395D) + : const Color(0xFFE8F0FE)) + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Icon(icon, color: isSelected ? AppColors.primaryBlue : AppColors.grayText, size: 24), + Icon( + icon, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + size: 24, + ), const SizedBox(height: 4), Text( label, style: TextStyle( fontSize: 10, fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - color: isSelected ? AppColors.primaryBlue : AppColors.grayText, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, ), - ) + ), ], ), ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/note/view/focus_screen.dart b/src/lib/features/note/view/focus_screen.dart index 9349b49..2702c2d 100644 --- a/src/lib/features/note/view/focus_screen.dart +++ b/src/lib/features/note/view/focus_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; import '../view/focus_widget.dart'; @@ -10,6 +9,7 @@ class FocusScreen extends StatelessWidget { // Shows the configuration dialog for timer and notification settings void _showSettingsDialog(BuildContext context) { final vm = context.read(); + final isDark = Theme.of(context).brightness == Brightness.dark; double currentPomodoro = (vm.pomodoroTime / 60).toDouble(); double currentBreak = (vm.shortBreakTime / 60).toDouble(); @@ -22,9 +22,16 @@ class FocusScreen extends StatelessWidget { return StatefulBuilder( builder: (context, setStateDialog) { return AlertDialog( - backgroundColor: Colors.white, + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - title: const Text('Cài đặt', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + title: Text( + 'Cài đặt', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, @@ -34,36 +41,98 @@ class FocusScreen extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Pomodoro', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - Text('${currentPomodoro.toInt()} phút', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + Text( + 'Pomodoro', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + '${currentPomodoro.toInt()} phút', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ], ), - Slider(value: currentPomodoro, min: 5, max: 60, divisions: 55, activeColor: AppColors.primaryBlue, onChanged: (val) => setStateDialog(() => currentPomodoro = val)), + Slider( + value: currentPomodoro, + min: 5, + max: 60, + divisions: 55, + activeColor: Theme.of(context).colorScheme.primary, + onChanged: (val) => setStateDialog(() => currentPomodoro = val), + ), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Nghỉ ngắn', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Nghỉ ngắn', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text('${currentBreak.toInt()} phút', style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold)), ], ), - Slider(value: currentBreak, min: 1, max: 30, divisions: 29, activeColor: Colors.orange, onChanged: (val) => setStateDialog(() => currentBreak = val)), - const Divider(height: 30), + Slider( + value: currentBreak, + min: 1, + max: 30, + divisions: 29, + activeColor: Colors.orange, + onChanged: (val) => setStateDialog(() => currentBreak = val), + ), + Divider( + height: 30, + color: Theme.of(context).colorScheme.outline, + ), // --- Hardware Settings --- SwitchListTile( - title: const Text('Rung', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - value: currentVibrate, activeColor: AppColors.primaryBlue, contentPadding: EdgeInsets.zero, + title: Text( + 'Rung', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + value: currentVibrate, + activeThumbColor: Theme.of(context).colorScheme.primary, + contentPadding: EdgeInsets.zero, onChanged: (val) => setStateDialog(() => currentVibrate = val), ), const SizedBox(height: 10), - const Text('Âm thanh', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Âm thanh', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 10), Container( padding: const EdgeInsets.symmetric(horizontal: 15), - decoration: BoxDecoration(color: const Color(0xFFF4F6F9), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(15), + ), child: DropdownButtonHideUnderline( child: DropdownButton( + dropdownColor: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, + style: TextStyle(color: Theme.of(context).colorScheme.onSurface), isExpanded: true, value: currentRingtone, items: const [ @@ -81,14 +150,24 @@ class FocusScreen extends StatelessWidget { ), ), actions: [ - TextButton(onPressed: () => Navigator.pop(context), child: const Text('Hủy', style: TextStyle(color: Colors.grey))), + TextButton( + onPressed: () => Navigator.pop(context), + child: Text( + 'Hủy', + style: + TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), ElevatedButton( onPressed: () { // Update settings in ViewModel vm.updateSettings(newPomodoroMinutes: currentPomodoro.toInt(), newBreakMinutes: currentBreak.toInt(), vibrate: currentVibrate, ringtone: currentRingtone); Navigator.pop(context); }, - style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryBlue, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))), + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), child: const Text('Lưu', style: TextStyle(color: Colors.white)), ), ], @@ -101,29 +180,64 @@ class FocusScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), - body: SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ // --- Header --- Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Row( + Row( children: [ - CircleAvatar(radius: 22, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d')), - SizedBox(width: 15), - Text('Tập trung', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + const CircleAvatar( + radius: 22, + backgroundImage: + NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d'), + ), + const SizedBox(width: 15), + Text( + 'Tập trung', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), // Settings Icon GestureDetector( onTap: () => _showSettingsDialog(context), - child: Container(padding: const EdgeInsets.all(10), decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: const Icon(Icons.settings_outlined, color: AppColors.primaryBlue)), + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), + child: Icon( + Icons.settings_outlined, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), @@ -142,6 +256,7 @@ class FocusScreen extends StatelessWidget { ), ), ), + ) ); } } \ No newline at end of file diff --git a/src/lib/features/note/view/focus_widget.dart b/src/lib/features/note/view/focus_widget.dart index 8037b4a..73fb73b 100644 --- a/src/lib/features/note/view/focus_widget.dart +++ b/src/lib/features/note/view/focus_widget.dart @@ -1,7 +1,6 @@ import 'dart:io'; // Import to display image files import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; // --- Tab Selector Widget --- @@ -11,38 +10,62 @@ class FocusTabSelector extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF132544) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10)], + boxShadow: [ + BoxShadow(color: Colors.black.withValues(alpha: 0.10), blurRadius: 10) + ], ), child: Row( mainAxisSize: MainAxisSize.min, children: [ - _buildTabBtn('Pomodoro', vm.isPomodoroMode, () => vm.setMode(true)), - _buildTabBtn('Nghỉ ngắn', !vm.isPomodoroMode, () => vm.setMode(false)), + _buildTabBtn( + context, + 'Pomodoro', + vm.isPomodoroMode, + () => vm.setMode(true), + ), + _buildTabBtn( + context, + 'Nghỉ ngắn', + !vm.isPomodoroMode, + () => vm.setMode(false), + ), ], ), ); } - Widget _buildTabBtn(String label, bool isSelected, VoidCallback onTap) { + Widget _buildTabBtn( + BuildContext context, + String label, + bool isSelected, + VoidCallback onTap, + ) { return GestureDetector( onTap: onTap, child: AnimatedContainer( duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.transparent, + color: isSelected + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF2A3D5D) + : Theme.of(context).colorScheme.primary) + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Text( label, style: TextStyle( - color: isSelected ? Colors.white : const Color(0xFF757575), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurfaceVariant, fontWeight: FontWeight.bold, fontSize: 14, ), @@ -59,13 +82,23 @@ class TimerDisplayWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Stack( alignment: Alignment.center, children: [ Container( width: 280, height: 280, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 14)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: isDark + ? const Color(0xFF182C4D) + : Theme.of(context).colorScheme.surface, + width: 14, + ), + ), ), SizedBox( width: 280, @@ -73,7 +106,7 @@ class TimerDisplayWidget extends StatelessWidget { child: CircularProgressIndicator( value: vm.progress, strokeWidth: 14, - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, backgroundColor: Colors.transparent, strokeCap: StrokeCap.round, ), @@ -82,21 +115,40 @@ class TimerDisplayWidget extends StatelessWidget { width: 210, height: 210, decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 20, offset: const Offset(0, 10))], + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.18), + blurRadius: 20, + offset: const Offset(0, 10), + ) + ], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( vm.timeString, - style: const TextStyle(fontSize: 56, fontWeight: FontWeight.w900, color: Color(0xFF2C3E50), letterSpacing: -2), + style: TextStyle( + fontSize: 56, + fontWeight: FontWeight.w900, + color: Theme.of(context).colorScheme.onSurface, + letterSpacing: -2, + ), ), const SizedBox(height: 4), Text( vm.isPomodoroMode ? 'TẬP TRUNG' : 'NGHỈ NGƠI', - style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: AppColors.primaryBlue.withOpacity(0.8), letterSpacing: 2), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.85), + letterSpacing: 2, + ), ), ], ), @@ -113,13 +165,15 @@ class TimerControlsWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildControlBtn( icon: Icons.replay_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.resetTimer, ), @@ -130,7 +184,9 @@ class TimerControlsWidget extends StatelessWidget { icon: vm.isRinging ? Icons.notifications_off_rounded // Muted bell icon : (vm.isRunning ? Icons.pause_rounded : Icons.play_arrow_rounded), - bgColor: vm.isRinging ? Colors.redAccent : AppColors.primaryBlue, + bgColor: vm.isRinging + ? Colors.redAccent + : Theme.of(context).colorScheme.primary, iconColor: Colors.white, size: 85, hasShadow: true, @@ -140,8 +196,8 @@ class TimerControlsWidget extends StatelessWidget { const SizedBox(width: 30), _buildControlBtn( icon: Icons.skip_next_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.skipTimer, ), @@ -164,8 +220,18 @@ class TimerControlsWidget extends StatelessWidget { color: bgColor, shape: BoxShape.circle, boxShadow: [ - if (hasShadow) BoxShadow(color: bgColor.withOpacity(0.4), blurRadius: 20, offset: const Offset(0, 10)), - if (!hasShadow) BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 10, offset: const Offset(0, 5)), + if (hasShadow) + BoxShadow( + color: bgColor.withValues(alpha: 0.40), + blurRadius: 20, + offset: const Offset(0, 10), + ), + if (!hasShadow) + BoxShadow( + color: Colors.black.withValues(alpha: 0.16), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), child: Material( @@ -187,19 +253,40 @@ class QuickNoteCard extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: double.infinity, padding: const EdgeInsets.all(25), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: const [ - Text('Ghi chú nhanh', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Đang thực hiện', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppColors.grayText)), + children: [ + Text( + 'Ghi chú nhanh', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Đang thực hiện', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), const SizedBox(height: 15), @@ -208,7 +295,9 @@ class QuickNoteCard extends StatelessWidget { Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( - color: const Color(0xFFF4F6F9), + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(15), ), child: Column( @@ -219,12 +308,21 @@ class QuickNoteCard extends StatelessWidget { maxLines: 3, decoration: InputDecoration( hintText: 'Thêm ý tưởng, tiến độ, hình ảnh...', - hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14), + hintStyle: TextStyle( + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.70), + fontSize: 14, + ), border: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero, ), - style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50)), + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), ), // SHOW IMAGE PREVIEW IF SELECTED @@ -277,12 +375,20 @@ class QuickNoteCard extends StatelessWidget { children: [ Row( children: [ - Icon(Icons.attach_file_rounded, color: Colors.grey.shade400, size: 22), + Icon( + Icons.attach_file_rounded, + color: Theme.of(context).colorScheme.onSurfaceVariant, + size: 22, + ), const SizedBox(width: 10), // IMAGE PICKER BUTTON GestureDetector( onTap: () => vm.pickImage(), - child: Icon(Icons.image_outlined, color: AppColors.primaryBlue, size: 22), + child: Icon( + Icons.image_outlined, + color: Theme.of(context).colorScheme.primary, + size: 22, + ), ), ], ), @@ -292,7 +398,7 @@ class QuickNoteCard extends StatelessWidget { context.read().addNote(); }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), elevation: 0, @@ -304,7 +410,10 @@ class QuickNoteCard extends StatelessWidget { // --- LOCAL NOTE LIST WITH IMAGE SUPPORT --- if (vm.notes.isNotEmpty) ...[ - const Padding(padding: EdgeInsets.symmetric(vertical: 15), child: Divider(color: Color(0xFFE2E8F0), height: 1)), + Padding( + padding: const EdgeInsets.symmetric(vertical: 15), + child: Divider(color: Theme.of(context).colorScheme.outline, height: 1), + ), ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), @@ -315,7 +424,11 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: note.pinned ? const Color(0xFFFFF8E1) : const Color(0xFFF8FAFC), + color: note.pinned + ? (isDark ? const Color(0xFF4A3B17) : const Color(0xFFFFF8E1)) + : (isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest), borderRadius: BorderRadius.circular(15), border: Border.all(color: note.pinned ? Colors.amber.shade200 : Colors.transparent), ), @@ -329,7 +442,13 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(top: 2, right: 12), width: 22, height: 22, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue, width: 2)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ), + ), ), ), // CONTENT (TEXT AND IMAGE) @@ -338,7 +457,14 @@ class QuickNoteCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (note.content.isNotEmpty) - Text(note.content, style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50), height: 1.4)), + Text( + note.content, + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + height: 1.4, + ), + ), // DISPLAY ATTACHED IMAGE IN NOTE if (note.imagePath != null && note.imagePath!.isNotEmpty) ...[ diff --git a/src/lib/features/statistics/model/StatisticsModel.dart b/src/lib/features/statistics/model/StatisticsModel.dart index b6376e4..1e2a720 100644 --- a/src/lib/features/statistics/model/StatisticsModel.dart +++ b/src/lib/features/statistics/model/StatisticsModel.dart @@ -42,7 +42,7 @@ class UserStatisticsModel { final int thisWeekTotal; final double growthPercentage; final List recentTasks; - final List dailyCounts; // <--- THÊM DÒNG NÀY (Hứng mảng 7 ngày) + final List dailyCounts; UserStatisticsModel({ required this.today, @@ -50,7 +50,7 @@ class UserStatisticsModel { required this.thisWeekTotal, required this.growthPercentage, required this.recentTasks, - required this.dailyCounts, // <--- Cập nhật constructor + required this.dailyCounts, }); factory UserStatisticsModel.fromJson(Map json) { diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index b8eb2b9..f7bd920 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../viewmodel/statistics_viewmodel.dart'; import '../widgets/statistics_widgets.dart'; @@ -24,26 +24,33 @@ class _StatisticsScreenState extends State { final userId = Supabase.instance.client.auth.currentUser?.id; if (userId != null) { context.read().getStatisticsData(userId); + final categoryViewModel = context.read(); + if (categoryViewModel.categories.isEmpty) { + categoryViewModel.loadCategories(); + } } }); } - Icon _getIconForCategory(String category) { - switch (category) { - case 'Design': return const Icon(Icons.checklist_rtl_rounded, color: AppColors.primaryBlue); - case 'Research': return const Icon(Icons.timer_outlined, color: Color(0xFFE67E22)); - case 'Development': return const Icon(Icons.calendar_month_outlined, color: Color(0xFF9B59B6)); - default: return const Icon(Icons.task_alt_rounded, color: Colors.green); - } - } - @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), - body: Consumer( - builder: (context, viewModel, child) { + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: Consumer( + builder: (context, viewModel, child) { if (viewModel.isLoading) { return const Center(child: CircularProgressIndicator()); @@ -63,34 +70,51 @@ class _StatisticsScreenState extends State { final currentTasks = data.recentTasks; - return SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ + return SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ // --- Header --- - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Row( - children: [ - CircleAvatar( + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + const CircleAvatar( radius: 22, - backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d') - ), - SizedBox(width: 15), - Text('Thống kê', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - ], - ), + backgroundImage: NetworkImage( + 'https://i.pravatar.cc/150?u=a042581f4e29026704d', + ), + ), + const SizedBox(width: 15), + Text( + 'Thống kê', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ], + ), Container( padding: const EdgeInsets.all(10), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.notifications_none_rounded, color: AppColors.primaryBlue), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), + child: Icon( + Icons.notifications_none_rounded, + color: Theme.of(context).colorScheme.primary, + ), ) - ], - ), - const SizedBox(height: 30), + ], + ), + const SizedBox(height: 30), DailyProgressCard( @@ -114,25 +138,44 @@ class _StatisticsScreenState extends State { const SizedBox(height: 30), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text('Hoàn thành gần đây', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Xem tất cả', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: AppColors.primaryBlue)), - ], - ), - const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Hoàn thành gần đây', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Xem tất cả', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + const SizedBox(height: 15), AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: currentTasks.isEmpty ? Container( - key: const ValueKey('empty_state'), - padding: const EdgeInsets.all(30), - alignment: Alignment.center, - child: Text('Chưa có công việc nào hoàn thành gần đây.', - style: TextStyle(color: Colors.grey.shade500), textAlign: TextAlign.center), - ) + key: const ValueKey('empty_state'), + padding: const EdgeInsets.all(30), + alignment: Alignment.center, + child: Text( + 'Chưa có công việc nào hoàn thành gần đây.', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + ) : Column( key: ValueKey('list_$_selectedDayIndex'), children: currentTasks.map((task) { @@ -148,12 +191,13 @@ class _StatisticsScreenState extends State { ), ), - const SizedBox(height: 80), - ], + const SizedBox(height: 80), + ], + ), ), - ), - ); - }, + ); + }, + ), ), ); } diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index a93344e..e1e3598 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -1,6 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/statistics/model/StatisticsModel.dart'; -import '../../../../core/theme/app_colors.dart'; + import '../../../tasks/model/task_model.dart'; import '../../../tasks/view/screens/task_detail_screen.dart'; @@ -8,20 +11,40 @@ class DailyProgressCard extends StatelessWidget { final int total; final int completed; final double percentage; - const DailyProgressCard({super.key, required this.total, required this.completed, required this.percentage}); + + const DailyProgressCard({ + super.key, + required this.total, + required this.completed, + required this.percentage, + }); @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), decoration: BoxDecoration( - color: Colors.white, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( children: [ - const Text('Tiến độ hôm nay', style: TextStyle(color: AppColors.grayText, fontSize: 16, fontWeight: FontWeight.w600)), + Text( + 'Tiến độ hôm nay', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 20), SizedBox( height: 140, @@ -32,14 +55,31 @@ class DailyProgressCard extends StatelessWidget { CircularProgressIndicator( value: (total > 0) ? percentage / 100 : 0, strokeWidth: 12, - backgroundColor: AppColors.backgroundBlue, - valueColor: AlwaysStoppedAnimation(AppColors.primaryBlue), + backgroundColor: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + valueColor: AlwaysStoppedAnimation( + Theme.of(context).colorScheme.primary, + ), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text('$completed/$total', style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Công việc', style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + '$completed/$total', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Công việc', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ], @@ -49,10 +89,19 @@ class DailyProgressCard extends StatelessWidget { RichText( textAlign: TextAlign.center, text: TextSpan( - style: const TextStyle(fontSize: 16, color: Colors.black87), + style: TextStyle( + fontSize: 16, + color: Theme.of(context).colorScheme.onSurface, + ), children: [ const TextSpan(text: 'Tuyệt vời! Bạn đã hoàn thành '), - TextSpan(text: '${percentage.toInt()}%', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + TextSpan( + text: '${percentage.toInt()}%', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), const TextSpan(text: '\nmục tiêu.'), ], ), @@ -63,7 +112,6 @@ class DailyProgressCard extends StatelessWidget { } } - class WeeklyChartCard extends StatelessWidget { final int selectedIndex; final int thisWeekTotal; @@ -82,18 +130,29 @@ class WeeklyChartCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; final bool isPositive = growthPercentage >= 0; - final Color trendColor = isPositive ? const Color(0xFF2ECC71) : Colors.redAccent; - final Color trendBgColor = isPositive ? const Color(0xFFE9F7EF) : const Color(0xFFFFEBEE); - final String trendText = "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; + final Color trendColor = isPositive + ? const Color(0xFF3DDC84) + : Colors.redAccent; + final Color trendBgColor = isPositive + ? (isDark ? const Color(0xFF173B3D) : const Color(0xFFE9F7EF)) + : (isDark ? const Color(0xFF402129) : const Color(0xFFFFEBEE)); + final String trendText = + "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; return Container( width: double.infinity, padding: const EdgeInsets.all(25), decoration: BoxDecoration( - color: Colors.white, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -105,15 +164,42 @@ class WeeklyChartCard extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text('Tuần này', style: TextStyle(color: AppColors.grayText, fontSize: 14, fontWeight: FontWeight.w600)), + Text( + 'Tuần này', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 5), - Text('$thisWeekTotal Tasks', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + '$thisWeekTotal Tasks', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: trendBgColor, borderRadius: BorderRadius.circular(15)), - child: Text(trendText, style: TextStyle(color: trendColor, fontSize: 12, fontWeight: FontWeight.bold)), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: trendBgColor, + borderRadius: BorderRadius.circular(15), + ), + child: Text( + trendText, + style: TextStyle( + color: trendColor, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), ), ], ), @@ -122,14 +208,48 @@ class WeeklyChartCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ - - _buildBar('T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), - _buildBar('T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), - _buildBar('T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), - _buildBar('T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), - _buildBar('T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), - _buildBar('T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), - _buildBar('CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), + _buildBar( + context, + 'T2', + weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, + 0, + ), + _buildBar( + context, + 'T3', + weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, + 1, + ), + _buildBar( + context, + 'T4', + weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, + 2, + ), + _buildBar( + context, + 'T5', + weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, + 3, + ), + _buildBar( + context, + 'T6', + weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, + 4, + ), + _buildBar( + context, + 'T7', + weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, + 5, + ), + _buildBar( + context, + 'CN', + weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, + 6, + ), ], ), ], @@ -137,7 +257,12 @@ class WeeklyChartCard extends StatelessWidget { ); } - Widget _buildBar(String label, double heightRatio, int index) { + Widget _buildBar( + BuildContext context, + String label, + double heightRatio, + int index, + ) { bool isActive = index == selectedIndex; return GestureDetector( onTap: () => onDaySelected(index), @@ -147,14 +272,27 @@ class WeeklyChartCard extends StatelessWidget { AnimatedContainer( duration: const Duration(milliseconds: 300), width: 35, - height: 100 * (heightRatio > 0 ? heightRatio : 0.1), // Tối thiểu 10% để cột không bị "biến mất" + height: 100 * (heightRatio > 0 ? heightRatio : 0.1), decoration: BoxDecoration( - color: isActive ? AppColors.primaryBlue : const Color(0xFFF5F7FA), + color: isActive + ? Theme.of(context).colorScheme.primary + : (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF334764) + : const Color(0xFFF5F7FA)), borderRadius: BorderRadius.circular(8), ), ), const SizedBox(height: 10), - Text(label, style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: isActive ? AppColors.primaryBlue : AppColors.grayText)), + Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: isActive + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ); @@ -170,9 +308,22 @@ class CompletedTaskCard extends StatelessWidget { @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + final CategoryModel fallbackCategory = CategoryModel( + id: 0, + name: 'General', + colorCode: '#5A8DF3', + profileId: '', + ); + final CategoryModel category = categoryViewModel.categories.isNotEmpty + ? categoryViewModel.categories.first + : fallbackCategory; final time = task.updatedAt; - final hour = time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour); + final hour = time.hour > 12 + ? time.hour - 12 + : (time.hour == 0 ? 12 : time.hour); final minute = time.minute.toString().padLeft(2, '0'); final period = time.hour >= 12 ? 'PM' : 'AM'; final timeString = 'Hoàn thành lúc $hour:$minute $period'; @@ -185,35 +336,56 @@ class CompletedTaskCard extends StatelessWidget { borderRadius: BorderRadius.circular(25), onTap: () { final mappedTask = TaskModel( - id: task.id.toString(), // Convert int to String if your TaskModel uses String IDs + id: task.id.toString(), + // Convert int to String if your TaskModel uses String IDs title: task.title, - description: 'Completed task details from Statistics.', // Default filler - category: 'Development', // Default filler - startTime: TimeOfDay(hour: task.updatedAt.hour, minute: task.updatedAt.minute), - endTime: TimeOfDay(hour: task.updatedAt.hour + 1, minute: task.updatedAt.minute), // Add 1 hour just for display + description: 'Completed task details from Statistics.', + category: category, + startTime: TimeOfDay( + hour: task.updatedAt.hour, + minute: task.updatedAt.minute, + ), + endTime: TimeOfDay( + hour: task.updatedAt.hour + 1, + minute: task.updatedAt.minute, + ), + // Add 1 hour just for display date: task.updatedAt, ); - Navigator.push(context, PageRouteBuilder( - transitionDuration: const Duration(milliseconds: 500), - pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), - transitionsBuilder: (_, animation, __, child) { - return FadeTransition(opacity: animation, child: child); - }, - )); + Navigator.push( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 500), + pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), + transitionsBuilder: (_, animation, __, child) { + return FadeTransition(opacity: animation, child: child); + }, + ), + ); }, child: Container( margin: const EdgeInsets.only(bottom: 15), padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Row( children: [ Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF23395D) + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(15), + ), child: icon, ), const SizedBox(width: 15), @@ -221,13 +393,30 @@ class CompletedTaskCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(task.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + task.title, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 4), - Text(timeString, style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + timeString, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ), - const Icon(Icons.check_circle, color: Color(0xFF2ECC71), size: 28), + const Icon( + Icons.check_circle, + color: Color(0xFF2ECC71), + size: 28, + ), ], ), ), @@ -235,4 +424,4 @@ class CompletedTaskCard extends StatelessWidget { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tag/model/tag_model.dart b/src/lib/features/tag/model/tag_model.dart new file mode 100644 index 0000000..5f5fdb8 --- /dev/null +++ b/src/lib/features/tag/model/tag_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class TagModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const TagModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory TagModel.fromJson(Map json) { + return TagModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#4A90E2', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF4A90E2); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF4A90E2); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/tag/repository/tag_repository.dart b/src/lib/features/tag/repository/tag_repository.dart new file mode 100644 index 0000000..d2c9158 --- /dev/null +++ b/src/lib/features/tag/repository/tag_repository.dart @@ -0,0 +1,45 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/tag_model.dart'; + +class TagRepository { + final SupabaseClient _client; + + TagRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchTags() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('tag') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => TagModel.fromJson(Map.from(e))) + .toList(); + } + + Future createCustomTag(String name, String colorCode) async { + final user = _client.auth.currentUser; + if (user == null) { + throw Exception('User is not authenticated'); + } + + final inserted = await _client + .from('tag') + .insert({ + 'name': name, + 'color_code': colorCode, + 'profile_id': user.id, + }) + .select('id, name, color_code, profile_id') + .single(); + + return TagModel.fromJson(Map.from(inserted)); + } +} + diff --git a/src/lib/features/tag/view/widgets/tag_selector.dart b/src/lib/features/tag/view/widgets/tag_selector.dart new file mode 100644 index 0000000..50753a6 --- /dev/null +++ b/src/lib/features/tag/view/widgets/tag_selector.dart @@ -0,0 +1,194 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + +import '../../viewmodel/tag_viewmodel.dart'; + +class TagSelector extends StatefulWidget { + const TagSelector({super.key}); + + @override + State createState() => _TagSelectorState(); +} + +class _TagSelectorState extends State { + final TextEditingController _customController = TextEditingController(); + + @override + void dispose() { + _customController.dispose(); + super.dispose(); + } + + void _showAddCustomDialog(BuildContext context, TagViewModel viewModel) { + _customController.clear(); + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Tạo tag mới'), + content: TextField( + controller: _customController, + maxLength: 12, + decoration: const InputDecoration( + hintText: 'Tên tag (tối đa 12 ký tự)', + border: OutlineInputBorder(), + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Huỷ'), + ), + ElevatedButton( + onPressed: () async { + final error = await viewModel.addCustomTag(_customController.text); + if (!context.mounted) return; + + if (error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); + } else { + Navigator.pop(context); + } + }, + child: const Text('Thêm'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Tags', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Custom', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + GestureDetector( + onTap: viewModel.isLoading + ? null + : () => _showAddCustomDialog(context, viewModel), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + children: [ + Icon( + Icons.add, + size: 14, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 3), + Text( + 'Tạo tag', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 8), + if (viewModel.tags.isEmpty) + Text( + 'Chưa có tag. Nhấn "Tạo tag" để thêm.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ) + else + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.tags + .map( + (tag) => _TagChip( + tag: tag, + isSelected: viewModel.isTagSelected(tag), + onTap: () => viewModel.toggleTag(tag), + ), + ) + .toList(), + ), + ], + ); + } +} + +class _TagChip extends StatelessWidget { + const _TagChip({ + required this.tag, + required this.isSelected, + required this.onTap, + }); + + final TagModel tag; + final bool isSelected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); + + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: isSelected + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon(Icons.check, color: Colors.white, size: 14), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected ? Colors.white : adaptiveTagColor, + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/tag/viewmodel/tag_viewmodel.dart b/src/lib/features/tag/viewmodel/tag_viewmodel.dart new file mode 100644 index 0000000..d361c77 --- /dev/null +++ b/src/lib/features/tag/viewmodel/tag_viewmodel.dart @@ -0,0 +1,113 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../model/tag_model.dart'; +import '../repository/tag_repository.dart'; + +class TagViewModel extends ChangeNotifier { + static const int _maxCustomTagLength = 12; + + final TagRepository _repository; + + TagViewModel({TagRepository? repository}) + : _repository = repository ?? TagRepository(); + + final List _tags = []; + final Set _selectedTagIds = {}; + + List get tags => List.unmodifiable(_tags); + + List get selectedTags => + _tags.where((tag) => _selectedTagIds.contains(tag.id)).toList(); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadTags() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchTags(); + _tags + ..clear() + ..addAll(data); + _selectedTagIds.removeWhere((id) => !_tags.any((tag) => tag.id == id)); + } catch (e) { + _error = e.toString(); + _tags.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + bool isTagSelected(TagModel tag) => _selectedTagIds.contains(tag.id); + + void toggleTag(TagModel tag) { + if (_selectedTagIds.contains(tag.id)) { + _selectedTagIds.remove(tag.id); + } else { + _selectedTagIds.add(tag.id); + } + notifyListeners(); + } + + void setSelectedTags(List tags) { + _selectedTagIds + ..clear() + ..addAll(tags.map((e) => e.id)); + notifyListeners(); + } + + void resetSelection() { + _selectedTagIds.clear(); + notifyListeners(); + } + + Future addCustomTag(String name) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) return 'Tên tag không được để trống'; + if (trimmed.length > _maxCustomTagLength) { + return 'Tối đa $_maxCustomTagLength ký tự'; + } + if (_tags.any((t) => t.name.toLowerCase() == trimmed.toLowerCase())) { + return 'Tag đã tồn tại'; + } + + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final colorCode = _generateColorCode(); + final created = await _repository.createCustomTag(trimmed, colorCode); + _tags.add(created); + _selectedTagIds.add(created.id); + return null; + } catch (e) { + _error = e.toString(); + return 'Không thể tạo tag. Vui lòng thử lại'; + } finally { + _isLoading = false; + notifyListeners(); + } + } + + String _generateColorCode() { + const palette = [ + '#E91E63', + '#673AB7', + '#795548', + '#009688', + '#FF5722', + '#4A90E2', + ]; + return palette[_tags.length % palette.length]; + } +} + diff --git a/src/lib/features/tasks/model/task_model.dart b/src/lib/features/tasks/model/task_model.dart index 8158b08..3fa2db1 100644 --- a/src/lib/features/tasks/model/task_model.dart +++ b/src/lib/features/tasks/model/task_model.dart @@ -1,13 +1,63 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + +// ─── Priority Enum ─────────────────────────────────────────── +enum Priority { low, medium, high, urgent } + +extension PriorityExtension on Priority { + String get label { + switch (this) { + case Priority.low: + return 'Low'; + case Priority.medium: + return 'Medium'; + case Priority.high: + return 'High'; + case Priority.urgent: + return 'Urgent'; + } + } + + Color get color { + switch (this) { + case Priority.low: + return const Color(0xFF4CAF50); // xanh lá + case Priority.medium: + return const Color(0xFF2196F3); // xanh dương + case Priority.high: + return const Color(0xFFFF9800); // cam + case Priority.urgent: + return const Color(0xFFF44336); // đỏ + } + } + + IconData get icon { + switch (this) { + case Priority.low: + return Icons.flag_outlined; + case Priority.medium: + return Icons.flag; + case Priority.high: + return Icons.flag; + case Priority.urgent: + return Icons.flag; + } + } +} + +// ─── Task Model ────────────────────────────────────────────── class TaskModel { - final String id; // ID duy nhất để làm Hero tag và gọi API sau này + final String id; String title; String description; - String category; + CategoryModel category; TimeOfDay startTime; TimeOfDay endTime; DateTime date; + Priority priority; + List tags; TaskModel({ required this.id, @@ -17,5 +67,7 @@ class TaskModel { required this.startTime, required this.endTime, required this.date, + this.priority = Priority.medium, + this.tags = const [], }); -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index a7f22c9..7e6fc3e 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,8 +1,16 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; +import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; +import '../widgets/priority_selector.dart'; class CreateTaskScreen extends StatefulWidget { const CreateTaskScreen({super.key}); @@ -12,30 +20,57 @@ class CreateTaskScreen extends StatefulWidget { } class _CreateTaskScreenState extends State { - final TextEditingController _nameController = TextEditingController(text: 'Team Meeting'); - final TextEditingController _descController = TextEditingController(text: 'Discuss all questions about new projects'); + final TextEditingController _nameController = TextEditingController( + text: 'Team Meeting', + ); + final TextEditingController _descController = TextEditingController( + text: 'Discuss all questions about new projects', + ); DateTime _selectedDate = DateTime.now(); TimeOfDay _startTime = const TimeOfDay(hour: 10, minute: 0); TimeOfDay _endTime = const TimeOfDay(hour: 11, minute: 0); - int _selectedCategoryIndex = 0; + int? _selectedCategoryId; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); + } @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(_selectedDate); + final categories = categoryViewModel.categories; + + if (_selectedCategoryId == null && categories.isNotEmpty) { + _selectedCategoryId = categories.first.id; + } return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: SafeArea( child: Column( children: [ + // ─── Header ─────────────────────────────────────── Container( decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)), + bottomLeft: Radius.circular(30), + bottomRight: Radius.circular(30), + ), boxShadow: [ BoxShadow( - color: Colors.black.withValues(alpha: 0.05), - blurRadius: 10, offset: const Offset(0, 5)) + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15), @@ -43,96 +78,152 @@ class _CreateTaskScreenState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - const Icon(Icons.menu_rounded, color: Colors.black), - const Icon(Icons.assignment_outlined, color: Colors.black), + Icon( + Icons.menu_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), + Icon( + Icons.assignment_outlined, + color: Theme.of(context).colorScheme.onSurface, + ), ], ), ), + + // ─── Body ───────────────────────────────────────── Expanded( child: SingleChildScrollView( padding: const EdgeInsets.all(25.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Create New Task', style: Theme.of(context).textTheme.headlineMedium), + Text( + 'Create New Task', + style: Theme.of(context).textTheme.headlineMedium, + ), const SizedBox(height: 25), - CustomInputField(label: 'Task Name', hint: 'Enter task name', controller: _nameController), + + // Task Name + CustomInputField( + label: 'Task Name', + hint: 'Enter task name', + controller: _nameController, + ), const SizedBox(height: 20), - Text('Select Category', style: Theme.of(context).textTheme.labelLarge), + + // Category + Text( + 'Select Category', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 10), SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: 4, - itemBuilder: (context, index) { - List categories = ['Development', 'Research', 'Design', 'Backend']; - bool isSelected = index == _selectedCategoryIndex; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), - backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), - showCheckmark: false, + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _selectedCategoryId, + onSelected: (category) { + setState(() => _selectedCategoryId = category.id); + }, ), - ); - }, - ), ), const SizedBox(height: 20), + + // ─── PRIORITY SELECTOR (MỚI) ────────────── + const PrioritySelector(), + const SizedBox(height: 20), + + // ─── TAG SELECTOR (MỚI) ─────────────────── + const TagSelector(), + const SizedBox(height: 20), + + // Date Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Date', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Date', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), InkWell( onTap: () async { final DateTime? picked = await showDatePicker( - context: context, initialDate: _selectedDate, - firstDate: DateTime(2000), lastDate: DateTime(2100)); - if (picked != null) setState(() => _selectedDate = picked); + context: context, + initialDate: _selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + if (picked != null) { + setState(() => _selectedDate = picked); + } }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 5), - Container(width: 150, height: 1, color: Colors.black26) + Container( + width: 150, + height: 1, + color: Theme.of(context).colorScheme.outline, + ) ], ), - ) + ), ], ), Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: AppColors.primaryBlue, borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(15), + ), child: const Icon(Icons.date_range_rounded, color: Colors.white), ) ], ), const SizedBox(height: 25), + + // Time Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Start time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Start time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _startTime, onChanged: (newTime) => setState(() => _startTime = newTime)), + TimePickerWidget( + time: _startTime, + onChanged: (t) => + setState(() => _startTime = t), + ), ], ), ), @@ -141,27 +232,82 @@ class _CreateTaskScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('End time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'End time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _endTime, onChanged: (newTime) => setState(() => _endTime = newTime)), + TimePickerWidget( + time: _endTime, + onChanged: (t) => setState(() => _endTime = t), + ), ], ), ), ], ), const SizedBox(height: 25), - CustomInputField(label: 'Description', hint: 'Enter task description', controller: _descController, maxLines: 2), + + // Description + CustomInputField( + label: 'Description', + hint: 'Enter task description', + controller: _descController, + maxLines: 2, + ), const SizedBox(height: 40), + + // ─── Create Button ──────────────────────── Center( child: ElevatedButton( - onPressed: () {}, + onPressed: () { + final viewModel = context.read(); + if (categories.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please create a category first.'), + ), + ); + return; + } + + final selectedCategory = categories.firstWhere( + (category) => category.id == _selectedCategoryId, + orElse: () => categories.first, + ); + + final newTask = TaskModel( + id: DateTime.now().millisecondsSinceEpoch + .toString(), + title: _nameController.text, + description: _descController.text, + category: selectedCategory, + startTime: _startTime, + endTime: _endTime, + date: _selectedDate, + priority: viewModel.selectedPriority, + tags: List.from(tagViewModel.selectedTags), + ); + viewModel.addTask(newTask); + viewModel.reset(); + context.read().resetSelection(); + Navigator.pop(context); + }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 15), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + padding: const EdgeInsets.symmetric( + horizontal: 100, + vertical: 15, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + child: const Text( + 'Create Task', + style: TextStyle(fontSize: 18), ), - child: const Text('Create Task', style: TextStyle(fontSize: 18)), ), ), ], @@ -173,4 +319,4 @@ class _CreateTaskScreenState extends State { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index c30697a..7a9f9b0 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; import 'create_task_screen.dart'; @@ -11,57 +13,73 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now()); + final viewModel = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; - // --- TẠO DỮ LIỆU GIẢ LẬP (MOCK DATA) --- - final task1 = TaskModel( - id: '1', // ID dùng để làm tag cho Hero Animation - title: 'Team Meeting', - description: 'Discuss all questions about new projects', - category: 'Development', - startTime: const TimeOfDay(hour: 10, minute: 0), - endTime: const TimeOfDay(hour: 11, minute: 0), - date: DateTime.now(), - ); - - final task2 = TaskModel( - id: '2', // ID phải khác nhau - title: 'Call the stylist', - description: 'Agree on an evening look', - category: 'Design', - startTime: const TimeOfDay(hour: 11, minute: 0), - endTime: const TimeOfDay(hour: 12, minute: 0), - date: DateTime.now(), - ); - // ---------------------------------------- + // Nhóm task theo priority + Map> grouped = {}; + for (var priority in Priority.values.reversed) { + final tasks = viewModel.tasks + .where((t) => t.priority == priority) + .toList(); + if (tasks.isNotEmpty) grouped[priority] = tasks; + } return Scaffold( body: Stack( children: [ Positioned( - top: 0, left: 0, right: 0, height: 250, - child: ClipPath(clipper: TopWaveClipper(), child: Container(color: AppColors.primaryBlue)), + top: 0, + left: 0, + right: 0, + height: 250, + child: ClipPath( + clipper: TopWaveClipper(), + child: Container(color: AppColors.primaryBlue), + ), ), SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + // ─── Header ─────────────────────────────────── Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 10, + ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Icon(Icons.menu_rounded, color: Colors.black), + Icon( + Icons.menu_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), Row( children: [ - const Icon(Icons.notifications_none_rounded, color: Colors.black), + Icon( + Icons.notifications_none_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), const SizedBox(width: 15), const CircleAvatar( radius: 20, - backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user1'), + backgroundImage: NetworkImage( + 'https://i.pravatar.cc/150?u=user1', + ), ), const SizedBox(width: 10), IconButton( - icon: const Icon(Icons.add_rounded, color: Colors.black), + icon: Icon( + Icons.add_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => const CreateTaskScreen())), ), ], @@ -69,23 +87,39 @@ class HomeScreen extends StatelessWidget { ], ), ), - const SizedBox(height: 10), + + // ─── Date Card ──────────────────────────────── Container( width: double.infinity, margin: const EdgeInsets.symmetric(horizontal: 20), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, + ), child: Padding( padding: const EdgeInsets.all(25.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('My Task', style: Theme.of(context).textTheme.headlineMedium), + Text( + 'My Task', + style: Theme.of(context).textTheme.headlineMedium, + ), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Today', style: Theme.of(context).textTheme.titleMedium), - Text(formattedDate, style: const TextStyle(color: AppColors.grayText, fontSize: 14)), + Text( + formattedDate, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + ), + ), ], ), const SizedBox(height: 20), @@ -95,8 +129,13 @@ class HomeScreen extends StatelessWidget { scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { - DateTime date = DateTime.now().add(Duration(days: index)); - return DateBox(date: date, isSelected: index == 0); + DateTime date = DateTime.now().add( + Duration(days: index), + ); + return DateBox( + date: date, + isSelected: index == 0, + ); }, ), ), @@ -104,42 +143,162 @@ class HomeScreen extends StatelessWidget { ), ), ), - const SizedBox(height: 25), - Expanded( - child: ListView( - padding: const EdgeInsets.symmetric(horizontal: 20), + const SizedBox(height: 15), + + // ─── Filter Bar ─────────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Row( children: [ - // --- SỬ DỤNG MOCK DATA VÀO TASKCARD --- - TaskCard( - task: task1, // Truyền task1 vào đây - leading: Stack( - children: [ - const CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user2')), - const Positioned(left: 10, child: CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user3'))), - const Positioned(left: 20, child: CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user4'))), - Positioned( - left: 30, - child: Container( - padding: const EdgeInsets.all(4), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.add_rounded, size: 20, color: AppColors.primaryBlue), + // Sort button + GestureDetector( + onTap: () => viewModel.toggleSortByPriority(), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 7, + ), + decoration: BoxDecoration( + color: viewModel.sortByPriority + ? AppColors.primaryBlue + : Colors.white, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: AppColors.primaryBlue, + width: 1, + ), + ), + child: Row( + children: [ + Icon( + Icons.sort, + size: 16, + color: viewModel.sortByPriority + ? Colors.white + : AppColors.primaryBlue, ), - ) - ], - ), + ] + ), + ) ), - TaskCard( - task: task2, // Truyền task2 vào đây - leading: Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), - child: const Icon(Icons.call_outlined, color: AppColors.primaryBlue), + const SizedBox(width: 8), + + // Filter theo priority + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + // Chip "All" + _FilterChip( + label: 'All', + isSelected: viewModel.filterPriority == null, + color: AppColors.primaryBlue, + onTap: () => viewModel.setFilterPriority(null), + ), + const SizedBox(width: 8), + // Chip cho từng priority + ...Priority.values.map( + (p) => Padding( + padding: const EdgeInsets.only(right: 8), + child: _FilterChip( + label: p.label, + isSelected: viewModel.filterPriority == p, + color: p.color, + onTap: () => viewModel.setFilterPriority(p), + ), + ), + ), + ], + ), ), ), - // ---------------------------------------- ], ), ), + const SizedBox(height: 10), + + // ─── Task List nhóm theo Priority ───────────── + Expanded( + child: grouped.isEmpty + ? _buildEmptyState() + : ListView( + padding: const EdgeInsets.symmetric(horizontal: 20), + children: grouped.entries.map((entry) { + final priority = entry.key; + final tasks = entry.value; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header nhóm + Padding( + padding: const EdgeInsets.only( + bottom: 10, + top: 5, + ), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 4, + height: 20, + decoration: BoxDecoration( + color: priority.color, + borderRadius: + BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + _priorityGroupLabel(priority), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + Text( + '${tasks.length} task', + style: const TextStyle( + fontSize: 12, + color: AppColors.grayText, + ), + ), + ], + ), + ), + + // Danh sách task trong nhóm + ...tasks.map( + (task) => TaskCard( + task: task, + leading: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: priority.color.withValues( + alpha: 0.1, + ), + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + priority.icon, + color: priority.color, + size: 22, + ), + ), + ), + ), + const SizedBox(height: 10), + ], + ); + }).toList(), + ), + ), ], ), ), @@ -147,4 +306,81 @@ class HomeScreen extends StatelessWidget { ), ); } -} \ No newline at end of file + + String _priorityGroupLabel(Priority priority) { + switch (priority) { + case Priority.urgent: + return 'Ưu tiên Khẩn cấp'; + case Priority.high: + return 'Ưu tiên Cao'; + case Priority.medium: + return 'Ưu tiên Trung bình'; + case Priority.low: + return 'Ưu tiên Thấp'; + } + } + + Widget _buildEmptyState() { + return const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.checklist_rounded, size: 60, color: AppColors.grayText), + SizedBox(height: 12), + Text( + 'Chưa có task nào', + style: TextStyle( + fontSize: 16, + color: AppColors.grayText, + fontWeight: FontWeight.w500, + ), + ), + SizedBox(height: 4), + Text( + 'Nhấn + để tạo task mới', + style: TextStyle(fontSize: 13, color: AppColors.grayText), + ), + ], + ), + ); + } +} + +// ─── Filter Chip Widget ────────────────────────────────────── +class _FilterChip extends StatelessWidget { + final String label; + final bool isSelected; + final Color color; + final VoidCallback onTap; + + const _FilterChip({ + required this.label, + required this.isSelected, + required this.color, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), + decoration: BoxDecoration( + color: isSelected ? color : Colors.white, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: color, width: 1), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: isSelected ? Colors.white : color, + ), + ), + ), + ); + } +} diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index 6297293..54b628e 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,13 +1,20 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; -import '../widgets/task_widgets.dart'; // Contains TimePickerWidget +import '../../viewmodel/task_viewmodel.dart'; +import '../widgets/task_widgets.dart'; class TaskDetailScreen extends StatefulWidget { final TaskModel task; - const TaskDetailScreen({super.key, required this.task}); @override @@ -19,77 +26,118 @@ class _TaskDetailScreenState extends State { late TextEditingController _descController; late TimeOfDay _startTime; late TimeOfDay _endTime; - late String _currentCategory; + late CategoryModel _currentCategory; + late List _currentTags; @override void initState() { super.initState(); - // Initialize state variables with services from the passed task object _titleController = TextEditingController(text: widget.task.title); _descController = TextEditingController(text: widget.task.description); _startTime = widget.task.startTime; _endTime = widget.task.endTime; _currentCategory = widget.task.category; + _currentTags = List.from(widget.task.tags); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); } @override void dispose() { - // Dispose controllers to prevent memory leaks _titleController.dispose(); _descController.dispose(); super.dispose(); } + void _toggleTag(TagModel tag) { + setState(() { + if (_currentTags.any((t) => t.id == tag.id)) { + _currentTags.removeWhere((t) => t.id == tag.id); + } else { + _currentTags.add(tag); + } + }); + } + + bool _isTagSelected(TagModel tag) => _currentTags.any((t) => t.id == tag.id); + void _saveChanges() { - // Update the local model - // (Note: Later, this will call TaskViewModel -> TaskService -> your ASP.NET Core API to update the database) widget.task.title = _titleController.text; widget.task.description = _descController.text; widget.task.startTime = _startTime; widget.task.endTime = _endTime; widget.task.category = _currentCategory; - // Show success message + // Lưu tags mới vào task qua ViewModel + context.read().updateTaskTags(widget.task.id, _currentTags); + ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Task updated successfully!'), backgroundColor: Colors.green), + SnackBar( + content: const Text('Task updated successfully!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); - - // Return to the previous screen Navigator.pop(context); } @override Widget build(BuildContext context) { - // Format date for display + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); + final isDark = Theme.of(context).brightness == Brightness.dark; - // Mock categories (Fetch from database later) - List categories = ['Development', 'Research', 'Design', 'Backend']; + final categories = categoryViewModel.categories; + final tags = tagViewModel.tags; + + if (categories.isNotEmpty && !categories.any((c) => c.id == _currentCategory.id)) { + _currentCategory = categories.first; + } return Scaffold( - backgroundColor: AppColors.backgroundBlue, + backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - title: const Text('Task Details', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold)), + title: Text( + 'Task Details', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.bold, + ), + ), centerTitle: true, ), body: SafeArea( child: Hero( - tag: 'task_card_${widget.task.id}', // Must match the Hero tag in the Home/Statistics screen - child: Material( // Required inside Hero to prevent yellow underline text rendering issues + tag: 'task_card_${widget.task.id}', + child: Material( type: MaterialType.transparency, child: Container( margin: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, boxShadow: [ - BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), child: SingleChildScrollView( @@ -97,59 +145,123 @@ class _TaskDetailScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Input for Task Name - CustomInputField(label: 'Task Name', hint: '', controller: _titleController), + // Task Name + CustomInputField( + label: 'Task Name', + hint: '', + controller: _titleController, + ), const SizedBox(height: 20), - Text('Category Tag', style: Theme.of(context).textTheme.labelLarge), + // Category + Text( + 'Category Tag', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 10), - - // Horizontal list of Category chips SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: categories.length, - itemBuilder: (context, index) { - bool isSelected = categories[index] == _currentCategory; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) { - if (selected) setState(() => _currentCategory = categories[index]); + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _currentCategory.id, + onSelected: (category) { + setState(() => _currentCategory = category); }, - backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), - showCheckmark: false, ), - ); - }, - ), ), const SizedBox(height: 25), - // Display Task Date + // Date Text('Date', style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 5), - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 25), - // Time Pickers for Start and End time + // ─── Tags ───────────────────────────────── + Text( + 'Tags', + style: Theme.of(context).textTheme.labelLarge, + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: tags.map((tag) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); + final isSelected = _isTagSelected(tag); + return GestureDetector( + onTap: () => _toggleTag(tag), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: isSelected + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon( + Icons.check, + color: Colors.white, + size: 14, + ), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected + ? Colors.white + : adaptiveTagColor, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 25), + + // Time Pickers Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Start time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Start time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _startTime, onChanged: (newTime) => setState(() => _startTime = newTime)), + TimePickerWidget( + time: _startTime, + onChanged: (t) => + setState(() => _startTime = t), + ), ], ), ), @@ -158,9 +270,15 @@ class _TaskDetailScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('End time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'End time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _endTime, onChanged: (newTime) => setState(() => _endTime = newTime)), + TimePickerWidget( + time: _endTime, + onChanged: (t) => setState(() => _endTime = t), + ), ], ), ), @@ -168,8 +286,13 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // Input for Description - CustomInputField(label: 'Description', hint: '', controller: _descController, maxLines: 3), + // Description + CustomInputField( + label: 'Description', + hint: '', + controller: _descController, + maxLines: 3, + ), const SizedBox(height: 40), // Save Button @@ -177,13 +300,24 @@ class _TaskDetailScreenState extends State { child: ElevatedButton( onPressed: _saveChanges, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + padding: const EdgeInsets.symmetric( + horizontal: 50, + vertical: 15, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + ), minimumSize: const Size(double.infinity, 50), ), - child: const Text('Save Changes', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + child: const Text( + 'Save Changes', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), ), ), ], @@ -195,4 +329,4 @@ class _TaskDetailScreenState extends State { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/widgets/priority_selector.dart b/src/lib/features/tasks/view/widgets/priority_selector.dart new file mode 100644 index 0000000..3beee4b --- /dev/null +++ b/src/lib/features/tasks/view/widgets/priority_selector.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; + +class PrioritySelector extends StatelessWidget { + const PrioritySelector({super.key}); + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Priority', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 10), + Row( + children: Priority.values.map((priority) { + final isSelected = viewModel.selectedPriority == priority; + return Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 8), + child: GestureDetector( + onTap: () => viewModel.setPriority(priority), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + color: isSelected + ? priority.color + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: isSelected ? priority.color : Colors.transparent, + ), + ), + child: Column( + children: [ + Icon( + priority.icon, + color: isSelected ? Colors.white : priority.color, + size: 20, + ), + const SizedBox(height: 4), + Text( + priority.label, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: isSelected ? Colors.white : priority.color, + ), + ), + ], + ), + ), + ), + ), + ); + }).toList(), + ), + ], + ); + } +} diff --git a/src/lib/features/tasks/view/widgets/tag_selector.dart b/src/lib/features/tasks/view/widgets/tag_selector.dart new file mode 100644 index 0000000..eee3cf6 --- /dev/null +++ b/src/lib/features/tasks/view/widgets/tag_selector.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart' + as tag_feature; + +class TagSelector extends StatelessWidget { + const TagSelector({super.key}); + + @override + Widget build(BuildContext context) { + return const tag_feature.TagSelector(); + } +} diff --git a/src/lib/features/tasks/view/widgets/task_widgets.dart b/src/lib/features/tasks/view/widgets/task_widgets.dart index 20b453b..426d182 100644 --- a/src/lib/features/tasks/view/widgets/task_widgets.dart +++ b/src/lib/features/tasks/view/widgets/task_widgets.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; import '../screens/task_detail_screen.dart'; @@ -39,14 +38,22 @@ class DateBox extends StatelessWidget { Widget build(BuildContext context) { String day = DateFormat('d').format(date); String weekday = DateFormat('E').format(date).toUpperCase(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: 55, margin: const EdgeInsets.only(right: 15), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.white, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.grey.shade300, width: 1), + border: Border.all( + color: isDark + ? Theme.of(context).colorScheme.outline + : Colors.grey.shade300, + width: 1, + ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -55,12 +62,16 @@ class DateBox extends StatelessWidget { style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, - color: isSelected ? Colors.white : Colors.black)), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurface)), const SizedBox(height: 5), Text(weekday, style: TextStyle( fontSize: 12, - color: isSelected ? AppColors.textLightBlue : AppColors.grayText)), + color: isSelected + ? Theme.of(context).colorScheme.secondary + : Theme.of(context).colorScheme.onSurfaceVariant)), ], ), ); @@ -105,7 +116,7 @@ class TaskCard extends StatelessWidget { child: Container( margin: const EdgeInsets.only(bottom: 20), decoration: BoxDecoration( - color: AppColors.taskCardBg, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) @@ -116,8 +127,8 @@ class TaskCard extends StatelessWidget { Positioned( left: 0, top: 25, bottom: 25, width: 4, child: Container( - decoration: const BoxDecoration( - color: AppColors.primaryBlue, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.only(topRight: Radius.circular(5), bottomRight: Radius.circular(5))), ), ), @@ -139,7 +150,10 @@ class TaskCard extends StatelessWidget { ), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: AppColors.timeBoxBg, borderRadius: BorderRadius.circular(10)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.secondary, + borderRadius: BorderRadius.circular(10), + ), child: Text(timeString, style: const TextStyle(color: Colors.white, fontSize: 12)), ), ], @@ -180,15 +194,21 @@ class TimePickerWidget extends StatelessWidget { Row( children: [ Text(formattedTime, - style: const TextStyle( - fontSize: 18, fontWeight: FontWeight.bold)), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + )), const SizedBox(width: 5), - const Icon(Icons.keyboard_arrow_down_rounded, - color: AppColors.primaryBlue, size: 20) + Icon( + Icons.keyboard_arrow_down_rounded, + color: Theme.of(context).colorScheme.primary, + size: 20, + ) ], ), const SizedBox(height: 5), - Container(height: 1, color: Colors.black26) + Container(height: 1, color: Theme.of(context).colorScheme.outline) ], ), ); diff --git a/src/lib/features/tasks/viewmodel/task_viewmodel.dart b/src/lib/features/tasks/viewmodel/task_viewmodel.dart new file mode 100644 index 0000000..c943500 --- /dev/null +++ b/src/lib/features/tasks/viewmodel/task_viewmodel.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + +import '../model/task_model.dart'; + +class TaskViewModel extends ChangeNotifier { + // ─── State tạo task ───────────────────────────────────── + Priority _selectedPriority = Priority.medium; + + Priority get selectedPriority => _selectedPriority; + + void setPriority(Priority priority) { + _selectedPriority = priority; + notifyListeners(); + } + + void reset() { + _selectedPriority = Priority.medium; + notifyListeners(); + } + + // ─── Task list + filter/sort ───────────────────────────── + final List _tasks = []; + List get tasks => _getFilteredAndSorted(); + + Priority? _filterPriority; + String? _filterTagId; + bool _sortByPriority = false; + + Priority? get filterPriority => _filterPriority; + String? get filterTagId => _filterTagId; + bool get sortByPriority => _sortByPriority; + + void setFilterPriority(Priority? priority) { + _filterPriority = priority; + notifyListeners(); + } + + void setFilterTag(String? tagId) { + _filterTagId = tagId; + notifyListeners(); + } + + void toggleSortByPriority() { + _sortByPriority = !_sortByPriority; + notifyListeners(); + } + + void addTask(TaskModel task) { + _tasks.add(task); + notifyListeners(); + } + + // Cập nhật tag cho task đã tạo (dùng ở Task Detail) + void updateTaskTags(String taskId, List newTags) { + final index = _tasks.indexWhere((t) => t.id == taskId); + if (index != -1) { + _tasks[index].tags = newTags; + notifyListeners(); + } + } + + List _getFilteredAndSorted() { + List result = List.from(_tasks); + if (_filterPriority != null) { + result = result.where((t) => t.priority == _filterPriority).toList(); + } + if (_filterTagId != null) { + result = result + .where((t) => t.tags.any((tag) => tag.id.toString() == _filterTagId)) + .toList(); + } + + // Sắp xếp theo priority (urgent → high → medium → low) + if (_sortByPriority) { + const order = [ + Priority.urgent, + Priority.high, + Priority.medium, + Priority.low, + ]; + result.sort( + (a, b) => + order.indexOf(a.priority).compareTo(order.indexOf(b.priority)), + ); + } + return result; + } +} diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart new file mode 100644 index 0000000..6f0fd50 --- /dev/null +++ b/src/lib/features/user/model/user_profile_model.dart @@ -0,0 +1,102 @@ +class UserProfileModel { + final String id; + final String name; + final int tasksDone; + final int streaks; + final String avatarUrl; + bool isNotificationEnabled; + String appearance; + final Map heatmapData; + + UserProfileModel({ + required this.id, + required this.name, + required this.tasksDone, + required this.streaks, + required this.avatarUrl, + this.isNotificationEnabled = true, + this.appearance = 'Light', + required this.heatmapData, + }); + + factory UserProfileModel.fromJson(Map json) { + int parseInt(dynamic value) { + if (value is int) return value; + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; + } + + Map parseHeatmap = {}; + if (json['heatmapData'] != null) { + final Map rawHeatmap = json['heatmapData']; + rawHeatmap.forEach((dateString, count) { + try { + parseHeatmap[DateTime.parse(dateString)] = parseInt(count); + } catch (e) { + // skip error + } + }); + } + return UserProfileModel( + id: json['id'] as String? ?? '', + name: + (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? + 'Unknown User', + tasksDone: parseInt(json['tasksDone'] ?? json['tasks_done']), + streaks: parseInt(json['streaks'] ?? json['streak_count']), + avatarUrl: + (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) + as String? ?? + '', + isNotificationEnabled: + (json['isNotificationEnabled'] ?? json['is_notification_enabled']) + as bool? ?? + true, + appearance: + (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + + heatmapData: parseHeatmap, + ); + } + + Map toJson() { + Map heatmapJson = {}; + heatmapData.forEach((date, count) { + heatmapJson[date.toIso8601String().split('T').first] = count; + }); + return { + 'id': id, + 'name': name, + 'tasksDone': tasksDone, + 'streaks': streaks, + 'avatarUrl': avatarUrl, + 'isNotificationEnabled': isNotificationEnabled, + 'appearance': appearance, + 'heatmapData': heatmapJson, + }; + } + + UserProfileModel copyWith({ + String? id, + String? name, + int? tasksDone, + int? streaks, + String? avatarUrl, + bool? isNotificationEnabled, + String? appearance, + Map? heatmapData, + }) { + return UserProfileModel( + id: id ?? this.id, + name: name ?? this.name, + tasksDone: tasksDone ?? this.tasksDone, + streaks: streaks ?? this.streaks, + avatarUrl: avatarUrl ?? this.avatarUrl, + isNotificationEnabled: + isNotificationEnabled ?? this.isNotificationEnabled, + appearance: appearance ?? this.appearance, + heatmapData: heatmapData ?? this.heatmapData, + ); + } +} diff --git a/src/lib/features/user/service/user_service.dart b/src/lib/features/user/service/user_service.dart new file mode 100644 index 0000000..c38a2db --- /dev/null +++ b/src/lib/features/user/service/user_service.dart @@ -0,0 +1,26 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/user_profile_model.dart'; + +class UserService { + final SupabaseClient _supabase = Supabase.instance.client; + /// Simulates fetching user profile data with a fake network delay + Future fetchUserProfile() async { + // Mimic API call delay for smooth state switching + try{ + final user = _supabase.auth.currentUser; + if (user == null) { + throw Exception("Không tìm thấy phiên đăng nhập. Hãy đăng nhập lại"); + } + final response = await _supabase.rpc('get_user_profile_stats'); + if(response == null){ + throw Exception("Không thể lấy thông tin người dùng. Hãy thử lại sau"); + } + response['id'] = _supabase.auth.currentUser!.id; + return UserProfileModel.fromJson(response); + } + catch(e){ + throw Exception("Failed to fetch user profile: $e"); + } + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart new file mode 100644 index 0000000..1e57bd2 --- /dev/null +++ b/src/lib/features/user/view/user_profile_view.dart @@ -0,0 +1,246 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_heatmap_calendar/flutter_heatmap_calendar.dart'; +import 'package:provider/provider.dart'; + +import '../viewmodel/user_profile_viewmodel.dart'; +import 'widgets/logout_button.dart'; +import 'widgets/profile_header.dart'; +import 'widgets/settings_list_tile.dart'; +import 'widgets/settings_section.dart'; +import 'widgets/stat_card.dart'; + +class UserProfileView extends StatelessWidget { + const UserProfileView({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + appBar: AppBar( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + elevation: 0, + centerTitle: true, + scrolledUnderElevation: 0, + title: Text( + 'Profile', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + actions: [ + IconButton( + icon: Icon( + Icons.settings, + color: Theme.of(context).colorScheme.primary, + ), + onPressed: () {}, + splashRadius: 24, + ), + ], + ), + body: Consumer( + builder: (context, vm, child) { + return AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + child: vm.isLoading + ? Center( + key: const ValueKey('loading'), + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.primary, + ), + ) + : vm.user == null + ? const Center( + key: ValueKey('error'), + child: Text("Error loading profile"), + ) + : Builder( + builder: (innerContext) { + vm.syncThemeWithProfile(innerContext); + return _buildProfileContent(innerContext, vm); + }, + ), + ); + }, + ), + ); + } + + Widget _buildProfileContent(BuildContext context, UserProfileViewModel vm) { + final user = vm.user!; + return SingleChildScrollView( + key: const ValueKey('content'), + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(24, 8, 24, 40), + child: Column( + children: [ + // 1. Header (Avatar & Name) + ProfileHeader(user: user), + const SizedBox(height: 32), + + // 2. Stats Row + Row( + children: [ + Expanded( + child: StatCard( + value: user.tasksDone.toString(), + label: 'Tasks Done', + onTap: () {}, + ), + ), + const SizedBox(width: 16), + Expanded( + child: StatCard( + value: user.streaks.toString(), + label: 'Streaks', + onTap: () => _showHeatmapBottomSheet(context, vm), + ), + ), + ], + ), + const SizedBox(height: 32), + + SettingsSection( + title: 'Preferences', + children: [ + SettingsListTile( + icon: Icons.notifications, + title: 'Notifications', + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, + onTap: () => vm.toggleNotification(!user.isNotificationEnabled), + trailing: Switch( + value: user.isNotificationEnabled, + activeColor: Theme.of(context).colorScheme.surface, + activeTrackColor: Theme.of(context).colorScheme.primary, + inactiveThumbColor: Theme.of( + context, + ).colorScheme.onSurfaceVariant, + inactiveTrackColor: Theme.of(context).colorScheme.outline, + onChanged: (val) => vm.toggleNotification(val), + ), + ), + Divider( + height: 1, + indent: 64, + endIndent: 24, + color: Theme.of(context).colorScheme.outline, + ), + SettingsListTile( + icon: Icons.dark_mode, + title: 'Appearance', + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, + trailing: Text( + user.appearance, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + onTap: () => vm.updateAppearance( + context, + user.appearance == 'Dark' ? 'Light' : 'Dark', + ), + ), + ], + ), + const SizedBox(height: 40), + + // 4. Logout Button + LogoutButton(onPressed: () => vm.logout(context)), + ], + ), + ); + } + + void _showHeatmapBottomSheet(BuildContext context, UserProfileViewModel vm) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Theme.of(context).colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (bottomSheetContext) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.outline, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 24), + + Text( + 'Bản đồ hoạt động', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + const SizedBox(height: 8), + Text( + 'Giữ vững phong độ nhé! 🔥', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 24), + + Center( + child: HeatMap( + datasets: vm.user!.heatmapData, + colorMode: ColorMode.opacity, + showText: false, + scrollable: true, + size: 30, + + colorsets: { + 1: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.2), + 3: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.4), + 5: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.6), + 7: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.8), + 9: Theme.of(context).colorScheme.primary, + }, + onClick: (value) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Đã hoàn thành $value công việc'), + behavior: SnackBarBehavior.floating, + ), + ); + }, + ), + ), + const SizedBox(height: 16), + ], + ), + ), + ); + }, + ); + } +} diff --git a/src/lib/features/user/view/widgets/logout_button.dart b/src/lib/features/user/view/widgets/logout_button.dart new file mode 100644 index 0000000..dd8fae1 --- /dev/null +++ b/src/lib/features/user/view/widgets/logout_button.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +class LogoutButton extends StatelessWidget { + final VoidCallback onPressed; + + const LogoutButton({super.key, required this.onPressed}); + + @override + Widget build(BuildContext context) { + final errorColor = Theme.of(context).colorScheme.error; + + return Material( + color: errorColor.withOpacity(0.05), + borderRadius: BorderRadius.circular(24), + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(24), + splashColor: errorColor.withOpacity(0.1), + highlightColor: errorColor.withOpacity(0.05), + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 20), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: errorColor.withOpacity(0.2)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.logout, color: errorColor, size: 22), + const SizedBox(width: 12), + Text( + 'Logout', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: errorColor, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/profile_header.dart b/src/lib/features/user/view/widgets/profile_header.dart new file mode 100644 index 0000000..2e61342 --- /dev/null +++ b/src/lib/features/user/view/widgets/profile_header.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import '../../model/user_profile_model.dart'; + +class ProfileHeader extends StatelessWidget { + final UserProfileModel user; + + const ProfileHeader({super.key, required this.user}); + + @override + Widget build(BuildContext context) { + final avatarUri = Uri.tryParse(user.avatarUrl.trim()); + final hasValidAvatar = + avatarUri != null && + (avatarUri.scheme == 'http' || avatarUri.scheme == 'https') && + avatarUri.host.isNotEmpty; + + return Column( + children: [ + Stack( + alignment: Alignment.bottomRight, + children: [ + // Rounded Square Avatar + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(32), + boxShadow: [ + BoxShadow( + color: + Theme.of(context).colorScheme.primary.withValues(alpha: 0.15), + blurRadius: 20, + offset: const Offset(0, 10), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: hasValidAvatar + ? Image.network( + user.avatarUrl, + width: 120, + height: 120, + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => _buildFallbackAvatar(context), + // Smooth image loading transition + frameBuilder: + (context, child, frame, wasSynchronouslyLoaded) { + if (wasSynchronouslyLoaded) return child; + return AnimatedOpacity( + opacity: frame == null ? 0 : 1, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOut, + child: child, + ); + }, + ) + : _buildFallbackAvatar(context), + ), + ), + // Edit Button with Ripple + Material( + color: Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Theme.of(context).scaffoldBackgroundColor, + width: 4, + ), + ), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () { + // TODO: Handle Edit Profile action + }, + child: Padding( + padding: EdgeInsets.all(8.0), + child: Icon( + Icons.edit, + color: Theme.of(context).colorScheme.surface, + size: 20, + ), + ), + ), + ), + ], + ), + const SizedBox(height: 20), + + // Name Only + Text( + user.name, + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + // Badges row removed here + ], + ); + } + + Widget _buildFallbackAvatar(BuildContext context) { + return Container( + width: 120, + height: 120, + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Icon( + Icons.person, + size: 64, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_list_tile.dart b/src/lib/features/user/view/widgets/settings_list_tile.dart new file mode 100644 index 0000000..6d18666 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_list_tile.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +class SettingsListTile extends StatelessWidget { + final IconData icon; + final String title; + final Widget trailing; + final Color? iconBgColor; + final Color? iconColor; + final VoidCallback? onTap; + + const SettingsListTile({ + super.key, + required this.icon, + required this.title, + required this.trailing, + this.iconBgColor, + this.iconColor, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + final resolvedIconBgColor = + iconBgColor ?? Theme.of(context).colorScheme.surfaceContainerHighest; + final resolvedIconColor = iconColor ?? Theme.of(context).colorScheme.primary; + + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: resolvedIconBgColor, + shape: BoxShape.circle, + ), + child: Icon(icon, color: resolvedIconColor, size: 22), + ), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ), + trailing, + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_section.dart b/src/lib/features/user/view/widgets/settings_section.dart new file mode 100644 index 0000000..44cdff7 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_section.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; + +class SettingsSection extends StatelessWidget { + final String title; + final List children; + + const SettingsSection({super.key, required this.title, required this.children}); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 16, bottom: 12), + child: Text( + title.toUpperCase(), + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurfaceVariant, + letterSpacing: 1.2, + ), + ), + ), + Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(24), + child: ClipRRect( + borderRadius: BorderRadius.circular(24), + child: Column( + children: children, + ), + ), + ), + ], + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/stat_card.dart b/src/lib/features/user/view/widgets/stat_card.dart new file mode 100644 index 0000000..e0fef26 --- /dev/null +++ b/src/lib/features/user/view/widgets/stat_card.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +class StatCard extends StatelessWidget { + final String value; + final String label; + final VoidCallback? onTap; + + const StatCard({super.key, required this.value, required this.label, this.onTap}); + + @override + Widget build(BuildContext context) { + return Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(24), + elevation: 0, + child: InkWell( + onTap: onTap ?? () {}, // Interactive ripple effect + borderRadius: BorderRadius.circular(24), + child: Container( + padding: const EdgeInsets.symmetric(vertical: 24), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: Theme.of(context).colorScheme.outline.withOpacity(0.5)), + ), + child: Column( + children: [ + Text( + value, + style: TextStyle( + fontSize: 28, + fontWeight: FontWeight.w800, + color: Theme.of(context).colorScheme.primary, + ), + ), + const SizedBox(height: 4), + Text( + label.toUpperCase(), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurfaceVariant, + letterSpacing: 1.2, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart new file mode 100644 index 0000000..df62fcd --- /dev/null +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -0,0 +1,124 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; +import 'package:provider/provider.dart'; // Import thêm Provider + +import '../../../core/theme/theme_provider.dart'; +import '../../auth/presentation/view/auth_gate.dart'; +import '../model/user_profile_model.dart'; +import '../service/user_service.dart'; + +class UserProfileViewModel extends ChangeNotifier { + final UserService _userService = UserService(); + final _supabase = Supabase.instance.client; + final bool useMockData; + String? _lastAppliedAppearance; + + UserProfileViewModel({this.useMockData = true}); + + UserProfileModel? _user; + UserProfileModel? get user => _user; + + bool _isLoading = true; + bool get isLoading => _isLoading; + + /// Load profile data + Future loadProfile() async { + _isLoading = true; + notifyListeners(); + + try { + if (useMockData) { + await Future.delayed(const Duration(milliseconds: 400)); + _user = _buildMockUser(); + } else { + _user = await _userService.fetchUserProfile(); + } + _lastAppliedAppearance = null; + } catch (e) { + debugPrint("Error loading profile: $e"); + + if (useMockData) { + _user = _buildMockUser(); + } else { + _user = null; + } + } finally { + _isLoading = false; + notifyListeners(); + } + } + + UserProfileModel _buildMockUser() { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + + final Map mockHeatmapData = { + today.subtract(const Duration(days: 1)): 3, + today.subtract(const Duration(days: 2)): 7, + today.subtract(const Duration(days: 3)): 4, + today.subtract(const Duration(days: 4)): 8, + today.subtract(const Duration(days: 5)): 2, + today.subtract(const Duration(days: 8)): 5, + }; + return UserProfileModel( + id: 'mock-user-001', + name: 'Alex Thompson', + avatarUrl: 'https://i.pravatar.cc/300?img=12', + appearance: 'Dark', + tasksDone: 24, + streaks: 12, + isNotificationEnabled: true, + heatmapData: mockHeatmapData, + ); + } + + /// Toggle notification preference + void toggleNotification(bool value) { + if (_user != null) { + _user!.isNotificationEnabled = value; + notifyListeners(); + } + } + + void updateAppearance(BuildContext context, String newAppearance) { + if (_user != null) { + _user!.appearance = newAppearance; + _lastAppliedAppearance = newAppearance; + notifyListeners(); + + if (context.mounted) { + context.read().updateTheme(newAppearance); + } + } + } + + void syncThemeWithProfile(BuildContext context) { + if (_user == null) return; + if (_lastAppliedAppearance == _user!.appearance) return; + + _lastAppliedAppearance = _user!.appearance; + context.read().updateTheme(_user!.appearance); + } + + /// Logout + Future logout(BuildContext context) async { + try { + await _supabase.auth.signOut(); + debugPrint("Đã clear session trên Supabase."); + + if (context.mounted) { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const AuthGate()), + (route) => false, + ); + } + } catch (e) { + debugPrint("Lỗi đăng xuất: $e"); + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Lỗi đăng xuất: $e'))); + } + } + } +} diff --git a/src/lib/main.dart b/src/lib/main.dart index e0f3857..3be01b7 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -1,16 +1,23 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; -import 'core/theme/app_colors.dart'; -import 'features/auth/presentation/view/login_view.dart'; -import 'features/auth/presentation/view/auth_gate.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; +import 'package:task_management_app/features/tasks/viewmodel/task_viewmodel.dart'; +import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +import 'core/theme/theme_provider.dart'; + Future main() async { WidgetsFlutterBinding.ensureInitialized(); + // Tải cấu hình từ file .env await dotenv.load(fileName: ".env"); String supabaseUrl = dotenv.env['SUPABASE_URL'] ?? ''; @@ -20,43 +27,42 @@ Future main() async { debugPrint('Error: SUPABASE_URL or SUPABASE_ANON_KEY is missing'); } - // 3. Khởi tạo kết nối Supabase - await Supabase.initialize( - url: supabaseUrl, - anonKey: supabaseAnonKey, - ); + await Supabase.initialize(url: supabaseUrl, anonKey: supabaseAnonKey); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle(statusBarColor: Colors.transparent)); - runApp(const TaskApp()); + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => ThemeProvider()), + ChangeNotifierProvider( + create: (_) => TaskViewModel(), + ), + ChangeNotifierProvider( + create: (_) => CategoryViewModel(), + ), + ChangeNotifierProvider( + create: (_) => TagViewModel(), + ), + ], + child: const TaskApp())); } -// 4. Create a global variable for ViewModel to call API quickly final supabase = Supabase.instance.client; - - class TaskApp extends StatelessWidget { const TaskApp({super.key}); @override Widget build(BuildContext context) { + final themeProvider = Provider.of(context); return MaterialApp( title: 'Task Management App', - theme: ThemeData( - scaffoldBackgroundColor: AppColors.backgroundBlue, - primaryColor: AppColors.primaryBlue, - useMaterial3: true, - fontFamily: 'Montserrat', - textTheme: const TextTheme( - headlineMedium: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Colors.black), - titleMedium: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black), - bodyMedium: TextStyle(fontSize: 14, color: AppColors.grayText), - labelLarge: TextStyle(fontSize: 16, color: AppColors.primaryBlue), - ), - ), + themeMode: themeProvider.themeMode, + theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong + darkTheme: AppTheme.darkTheme, home: const AuthGate(), debugShowCheckedModeBanner: false, ); } -} \ No newline at end of file +} diff --git a/src/pubspec.lock b/src/pubspec.lock index 1b845aa..72a5d4a 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -198,6 +198,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_heatmap_calendar: + dependency: "direct main" + description: + name: flutter_heatmap_calendar + sha256: "0933071844cd604b938e38358984244292ba1ba8f4b4b6f0f091f5927a23e958" + url: "https://pub.dev" + source: hosted + version: "1.0.5" flutter_lints: dependency: "direct dev" description: @@ -256,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.3" + google_generative_ai: + dependency: "direct main" + description: + name: google_generative_ai + sha256: "71f613d0247968992ad87a0eb21650a566869757442ba55a31a81be6746e0d1f" + url: "https://pub.dev" + source: hosted + version: "0.4.7" gotrue: dependency: transitive description: @@ -604,10 +620,10 @@ packages: dependency: "direct main" description: name: shared_preferences - sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.5.5" shared_preferences_android: dependency: transitive description: diff --git a/src/pubspec.yaml b/src/pubspec.yaml index 65c8e9c..9afc694 100644 --- a/src/pubspec.yaml +++ b/src/pubspec.yaml @@ -42,6 +42,8 @@ dependencies: flutter_ringtone_player: ^4.0.0+4 image_picker: ^1.2.1 shared_preferences: ^2.2.2 + flutter_heatmap_calendar: ^1.0.5 + google_generative_ai: ^0.4.7 dev_dependencies: flutter_test: diff --git a/supabase/migrations/20260409084009_create_user_profile_rpc.sql b/supabase/migrations/20260409084009_create_user_profile_rpc.sql new file mode 100644 index 0000000..cfc71d1 --- /dev/null +++ b/supabase/migrations/20260409084009_create_user_profile_rpc.sql @@ -0,0 +1,58 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats() +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + + WITH completed_dates AS ( + -- Get the day that had task done + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'UTC') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + -- Calculate streak length for each group + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + -- get streak if the end date is within the yesterday + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= (CURRENT_DATE - INTERVAL '1 day'); + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0) + ); +END; +$$; \ No newline at end of file diff --git a/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql new file mode 100644 index 0000000..aa82198 --- /dev/null +++ b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql @@ -0,0 +1,66 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats(p_days INT DEFAULT 90) +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; + v_heatmap_data JSON; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + -- Get task done per day for heatmap + SELECT json_object_agg(task_date::TEXT, task_count) INTO v_heatmap_data + FROM ( + SELECT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date, COUNT(*) AS task_count + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + AND updated_at >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - (p_days || ' days')::INTERVAL) + GROUP BY DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') + ) t; + + WITH completed_dates AS ( + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - INTERVAL '1 day'); + + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0), + 'heatmapData', COALESCE(v_heatmap_data, '{}'::JSON) + ); +END; +$$; \ No newline at end of file diff --git a/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql new file mode 100644 index 0000000..197e189 --- /dev/null +++ b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql @@ -0,0 +1,52 @@ +CREATE OR REPLACE FUNCTION create_task_full( + p_title TEXT, + p_priority INT4, + p_profile_id UUID, + p_tag_names TEXT[] +) +RETURNS JSON +LANGUAGE plpgsql +AS $$ +DECLARE + v_task_id INT8; + v_tag_name TEXT; + v_tag_id INT8; +BEGIN + + INSERT INTO task (title, priority, profile_id, status) + VALUES (p_title, p_priority, p_profile_id, 0) + RETURNING id INTO v_task_id; + + IF p_tag_names IS NOT NULL THEN + FOREACH v_tag_name IN ARRAY p_tag_names + LOOP + v_tag_name := trim(v_tag_name); + + IF v_tag_name != '' THEN + INSERT INTO tag (name, profile_id, color_code) + VALUES (v_tag_name, p_profile_id, '#6200EE') + ON CONFLICT (name, profile_id) + DO UPDATE SET name = EXCLUDED.name + RETURNING id INTO v_tag_id; + + + INSERT INTO task_tags (task_id, tag_id) + VALUES (v_task_id, v_tag_id) + ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END IF; + + RETURN json_build_object( + 'success', true, + 'task_id', v_task_id, + 'message', 'Đã tạo task với priority ' || p_priority + ); + +EXCEPTION WHEN OTHERS THEN + RETURN json_build_object( + 'success', false, + 'error', SQLERRM + ); +END; +$$; \ No newline at end of file diff --git a/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql b/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql new file mode 100644 index 0000000..8005f71 --- /dev/null +++ b/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql @@ -0,0 +1,64 @@ +CREATE OR REPLACE FUNCTION create_task_full( + p_title TEXT, + p_priority INT4, + p_profile_id UUID, + p_tag_names TEXT[], + p_category_name TEXT, + p_start_time TIMESTAMPTZ default null, + p_due_time TIMESTAMPTZ default null +) +RETURNS JSON +LANGUAGE plpgsql +AS $$ +DECLARE + v_task_id INT8; + v_tag_name TEXT; + v_tag_id INT8; + v_category_id INT8; +BEGIN + SELECT id INTO v_category_id + FROM category + WHERE profile_id = p_profile_id AND name ILIKE p_category_name + LIMIT 1; + + IF v_category_id IS NULL THEN + SELECT id INTO v_category_id FROM category WHERE profile_id = p_profile_id AND name = 'Cá nhân' LIMIT 1; + END IF; + + INSERT INTO task (title, priority, profile_id, status, category_id,start_time,due_time) + VALUES (p_title, p_priority, p_profile_id, 0,v_category_id,p_start_time,p_due_time) + RETURNING id INTO v_task_id; + + IF p_tag_names IS NOT NULL THEN + FOREACH v_tag_name IN ARRAY p_tag_names + LOOP + v_tag_name := trim(v_tag_name); + + IF v_tag_name != '' THEN + INSERT INTO tag (name, profile_id, color_code) + VALUES (v_tag_name, p_profile_id, '#6200EE') + ON CONFLICT (name, profile_id) + DO UPDATE SET name = EXCLUDED.name + RETURNING id INTO v_tag_id; + + + INSERT INTO task_tags (task_id, tag_id) + VALUES (v_task_id, v_tag_id) + ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END IF; + + RETURN json_build_object( + 'success', true, + 'task_id', v_task_id, + 'message', 'Đã tạo task với priority ' || p_priority + ); + +EXCEPTION WHEN OTHERS THEN + RETURN json_build_object( + 'success', false, + 'error', SQLERRM + ); +END; +$$; \ No newline at end of file