hym_ui/lib/home_page.dart
2025-08-11 17:35:29 -04:00

582 lines
27 KiB
Dart

import 'package:crab_ui/sonicEmailView.dart';
import 'folder_drawer.dart';
import 'structs.dart';
import 'api_service.dart';
import 'package:flutter/material.dart';
import 'email.dart';
import 'Compose.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey<EmailPageState> _emailPageKey = GlobalKey<EmailPageState>();
ApiService apiService = ApiService();
bool _isSidebarOpen = true;
bool querySearches = false;
String? _selectedOption = "INBOX";
List<String> _checkBulk = [
"All",
"None",
"Read",
"Unread",
"Starred",
"Unstarred"
];
bool _checkboxState = false;
bool bulkOptionsState = false;
List<String> _tabs = ['Emails'];
Map<String, Widget> _tabWidgets = {};
TabController? _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: _tabs.length, vsync: this);
_tabWidgets['Emails'] = EmailPage(
key: _emailPageKey,
);
}
// Add a new tab based on the search
void _performSearch(String query, String? list) {
setState(() {
if (!_tabs.contains(query)) {
_tabs.add(query);
_tabWidgets[query] = _buildSearchResultsWidget(
query, list); // Store a different widget for this tab
_tabController = TabController(length: _tabs.length, vsync: this);
}
});
}
void _showOptionsSearchDialog() async {
List<String> folders = await apiService.fetchFolders();
if (mounted) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Choose an Option'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: folders.map((option) {
return ListTile(
title: Text(option),
leading: Radio<String>(
value: option,
groupValue: _selectedOption, // Bind with _selectedOption
onChanged: (String? value) {
setState(() {
_selectedOption = value;
});
Navigator.of(context)
.pop(); // Close the dialog on selection
},
),
);
}).toList(),
),
actions: <Widget>[
ElevatedButton(
child: Text('Submit'),
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You selected: $_selectedOption'),
));
},
),
],
);
},
);
}
}
// Remove a tab
void _removeTab(int index) {
if (_tabs[index] != 'Emails') {
setState(() {
String tabToRemove = _tabs[index];
_tabs.removeAt(index);
_tabWidgets
.remove(tabToRemove); // Remove widget associated with the tab
_tabController = TabController(length: _tabs.length, vsync: this);
});
}
}
// Build a custom widget for each search query
Widget _buildSearchResultsWidget(String query, String? list) {
return FutureBuilder<List<SerializableMessage>>(
future: apiService.sonicSearch(list ?? "INBOX", 50, 0, query),
builder: (BuildContext context,
AsyncSnapshot<List<SerializableMessage>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return Center(child: Text('No results found for: $query'));
} else {
List<SerializableMessage> result = snapshot.data!;
return Scaffold(
body: ListView.separated(
itemCount: result.length,
itemBuilder: (context, index) {
final SerializableMessage email = result[index];
return ListTile(
title: Text(email.from,
style: TextStyle(fontWeight: FontWeight.bold)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(email.subject)],
),
trailing: Text(email.date.toString()),
onTap: () async {
// print('tapped');
// List<String> emailContent =
// await apiService.fetchEmailContent([email.id], email.list);
//call the foldable
List<String> emailContent = // list of the html
await apiService
.fetchEmailContent([email.id], email.list);
// List<String> emailIds = email.messages;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SonicEmailView(
email: email, emailHTML: emailContent[0])),
);
},
);
},
separatorBuilder: (context, index) => Divider(),
),
);
}
},
);
}
@override
void dispose() {
_tabController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.onPrimary,
body: Padding(
padding: const EdgeInsets.fromLTRB(0, 20, 0, 20),
child: Scaffold(
key: _scaffoldKey,
drawer: FolderDrawer(
apiService: apiService,
onFolderTap: (folder) {
_emailPageKey.currentState?.updateSelectedFolder(folder);
},
),
body: Scaffold(
backgroundColor: Theme.of(context).colorScheme.onPrimary,
body: Padding(
padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
child: Stack(
children: [
Row(
children: [
// Sidebar
if (_isSidebarOpen)
Container(
width: 70,
color: Color.fromARGB(17, 96, 122, 135),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ListTile(
leading: Icon(Icons.edit_note_sharp),
onTap: () {
OverlayService()
.showPersistentWidget(context);
}),
ListTile(
leading: Icon(Icons.home),
onTap: () {
// Navigate to Home
},
),
ListTile(
leading: Icon(Icons.settings),
onTap: () {
// Navigate to Settings
},
),
ListTile(
leading: Icon(Icons.email),
onTap: () {
_scaffoldKey.currentState?.openDrawer();
},
),
Spacer(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: Alignment.bottomLeft,
child: IconButton(
icon:
Icon(Icons.close, color: Colors.white),
onPressed: () {
setState(() {
_isSidebarOpen = false;
});
},
),
),
),
],
),
),
// Main content
Expanded(
child: Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 4.0),
color: Color.fromARGB(42, 36, 102, 132),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 800,
),
child: SizedBox(
height: 40,
child: TextField(
decoration: InputDecoration(
hintText: 'Search...',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.search),
),
onSubmitted: (value) {
if (value.isNotEmpty) {
_performSearch(
value, _selectedOption);
}
//this is the input box i mentioned
// if (value == '') {
// setState(() {
// querySearches = false;
// });
// }
// Future<List<String>> results = apiService
// .sonicSearch('INBOX', 20, 0, value);
// // print(value);
// print(results);
// setState(() {
// querySearches = true;
// });
},
),
),
),
),
SizedBox(
width: 8,
),
Container(
height: 40,
child: ElevatedButton(
onPressed: _showOptionsSearchDialog,
child: Icon(Icons.manage_search),
),
)
],
),
),
Container(
padding: EdgeInsets.all(0.0),
color: Color.fromARGB(42, 36, 102, 132),
child: Row(
children: [
Container(
height: 2,
)
],
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 4, 0, 4),
color: Theme.of(context).colorScheme.onPrimary,
child: Row(
children: [
Padding(
padding:
const EdgeInsets.fromLTRB(4, 0, 0, 0),
child: Checkbox(
value: _checkboxState,
onChanged: (value) {
setState(() {
_checkboxState = !_checkboxState;
});
if (_checkboxState) {
// var a = _tabWidgets["Emails"].;
print(_emailPageKey.currentState!
.selectAllEmails(
true)); //now i got them all but how do i go down to select them all?
print("all");
bulkOptionsState = true;
} else {
_emailPageKey.currentState!
.selectAllEmails(false);
bulkOptionsState = false;
print("none");
}
}),
),
const SizedBox(
width: 0,
),
PopupMenuButton<String>(
icon: const Icon(
Icons.arrow_drop_down_outlined),
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<String>>[
const PopupMenuItem<String>(
child: Text("All")),
const PopupMenuItem<String>(
child: Text("None")),
const PopupMenuItem<String>(
child: Text("Read")),
const PopupMenuItem<String>(
child: Text("Unread")),
const PopupMenuItem<String>(
child: Text("Starred")),
const PopupMenuItem<String>(
child: Text("Unstarred")),
],
onSelected: (String result) {
print("result $result");
},
),
if (bulkOptionsState) ...<Widget>[
IconButton(
onPressed: null,
icon: Icon(Icons.archive_outlined)),
IconButton(
onPressed: null,
icon: Icon(Icons.delete_outlined)),
IconButton(
onPressed: null,
icon: Icon(
Icons.mark_email_read_outlined)),
IconButton(
onPressed: null,
icon: Icon(
Icons.drive_file_move_outlined)),
],
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
itemBuilder: (BuildContext context) {
if (!bulkOptionsState) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
child: Row(
children: [
Icon(Icons
.mark_email_read_outlined),
const SizedBox(
width: 4.0,
),
Text("Mark all as read")
],
),
),
const PopupMenuDivider(),
PopupMenuItem(
child: Text(
"Select messages to see more actions",
style: TextStyle(
color: Colors
.blueGrey.shade300),
))
];
} else {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
child: Row(
children: [
Icon(Icons
.mark_email_unread_outlined),
const SizedBox(
width: 4.0,
),
Text("Mark as unread")
],
),
),
const PopupMenuItem<String>(
child: Row(
children: [
Icon(Icons.snooze_outlined),
const SizedBox(
width: 4.0,
),
Text("Snooze")
],
),
),
const PopupMenuItem<String>(
child: Row(
children: [
Icon(Icons.star_border_outlined),
const SizedBox(
width: 4.0,
),
Text("Add star")
],
),
),
];
}
}),
],
)),
Container(
color: Color.fromARGB(255, 131, 110, 143),
child: TabBar(
controller: _tabController,
isScrollable: true,
tabs: _tabs
.asMap()
.entries
.map((entry) => Tab(
child: Row(
children: [
Text(entry.value),
if (entry.value != 'Emails')
GestureDetector(
onTap: () =>
_removeTab(entry.key),
child: Icon(Icons.close,
size: 16),
),
],
),
))
.toList(),
labelColor: Colors.white,
indicatorColor: Colors.white,
),
),
Container(
// alignment: Alignment.topLeft,
padding: EdgeInsets.all(8.0),
color: Colors.white,
child: Row(
children: [
ElevatedButton(
onPressed: () {
_emailPageKey.currentState!.isBackDisabled
? null
: _emailPageKey.currentState
?.updatePagenation('back');
},
child: Icon(Icons.navigate_before),
),
Builder(
builder: (context) {
final emailState =
_emailPageKey.currentState;
if (emailState == null) {
// Schedule a rebuild once the state is available
Future.microtask(() => setState(() {}));
return Text('Loading...');
}
return ValueListenableBuilder<int>(
valueListenable:
emailState.currentPageNotifier,
builder: (context, value, _) =>
Text('$value'),
);
},
),
ElevatedButton(
onPressed: () {
_emailPageKey.currentState
?.updatePagenation('next');
},
child: Icon(Icons.navigate_next),
),
],
),
),
Expanded(
child: TabBarView(
controller: _tabController,
children: _tabs.map((tab) {
return _tabWidgets[tab] ??
Center(child: Text("No content found"));
// return Center(
// child: EmailPage(
// key: _emailPageKey,
// ));
}).toList(),
),
),
// if (_tabs.isEmpty)
// Expanded(
// child: EmailPage(key: _emailPageKey),
// ),
// if (_tabs.isNotEmpty)
// Expanded(
// // child: Text('supposed to be mails'),
// child: TabBarView(
// controller: _tabController,
// children: _tabs
// .map((tab) => Center(child: Text('Results for $tab')))
// .toList(),
// ),
// ),
],
),
),
],
),
if (!_isSidebarOpen)
Positioned(
bottom: 16,
left: 16,
child: FloatingActionButton(
child: Icon(Icons.menu),
onPressed: () {
setState(() {
_isSidebarOpen = true;
});
},
),
),
],
),
),
),
),
),
);
}
}