Files
kent_logistics_app/lib/screens/chat_screen.dart

328 lines
9.0 KiB
Dart
Raw Normal View History

2025-12-03 11:57:05 +05:30
import 'package:flutter/material.dart';
2025-12-15 11:10:52 +05:30
import 'package:provider/provider.dart';
2025-12-23 11:44:56 +05:30
import 'dart:io';
import 'package:file_selector/file_selector.dart';
2025-12-03 11:57:05 +05:30
2025-12-15 11:10:52 +05:30
import '../services/chat_service.dart';
import '../services/reverb_socket_service.dart';
import '../services/dio_client.dart';
import '../providers/chat_unread_provider.dart';
2025-12-16 10:24:16 +05:30
import '../widgets/chat_file_preview.dart';
2025-12-23 11:44:56 +05:30
import 'chat_file_viewer.dart';
2025-12-15 11:10:52 +05:30
class ChatScreen extends StatefulWidget {
2025-12-03 11:57:05 +05:30
const ChatScreen({super.key});
2025-12-15 11:10:52 +05:30
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _messageCtrl = TextEditingController();
final ScrollController _scrollCtrl = ScrollController();
2025-12-23 11:44:56 +05:30
2025-12-18 11:03:25 +05:30
Map<String, dynamic>? uploadingMessage;
2025-12-15 11:10:52 +05:30
late ChatService _chatService;
final ReverbSocketService _socket = ReverbSocketService();
int? ticketId;
List<Map<String, dynamic>> messages = [];
bool isLoading = true;
@override
void initState() {
super.initState();
_chatService = ChatService(DioClient.getInstance(context));
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<ChatUnreadProvider>().setChatOpen(true);
});
_initChat();
}
2025-12-23 11:44:56 +05:30
2025-12-18 11:03:25 +05:30
String _guessMimeType(String path) {
final lower = path.toLowerCase();
if (lower.endsWith('.jpg') || lower.endsWith('.png')) return 'image/*';
if (lower.endsWith('.mp4')) return 'video/*';
if (lower.endsWith('.pdf')) return 'application/pdf';
return 'application/octet-stream';
}
2025-12-15 11:10:52 +05:30
2025-12-16 10:24:16 +05:30
Future<void> _pickAndSendFile() async {
2025-12-18 11:03:25 +05:30
final XFile? picked = await openFile();
if (picked == null || ticketId == null) return;
final file = File(picked.path);
setState(() {
uploadingMessage = {
'local_file': file,
'file_type': _guessMimeType(file.path),
'progress': 0.0,
};
});
2025-12-16 10:24:16 +05:30
2025-12-18 11:03:25 +05:30
await _chatService.sendFile(
ticketId!,
file,
onProgress: (progress) {
if (!mounted) return;
2025-12-23 11:44:56 +05:30
setState(() => uploadingMessage!['progress'] = progress);
2025-12-18 11:03:25 +05:30
},
);
2025-12-16 10:24:16 +05:30
2025-12-18 11:03:25 +05:30
if (!mounted) return;
2025-12-23 11:44:56 +05:30
setState(() => uploadingMessage = null);
2025-12-16 10:24:16 +05:30
}
2025-12-15 11:10:52 +05:30
Future<void> _initChat() async {
final ticketRes = await _chatService.startChat();
ticketId = ticketRes['ticket']['id'];
final msgs = await _chatService.getMessages(ticketId!);
messages = List<Map<String, dynamic>>.from(msgs);
await _socket.connect(
context: context,
ticketId: ticketId!,
onMessage: (msg) {
2025-12-18 11:03:25 +05:30
final incomingClientId = msg['client_id'];
setState(() {
2025-12-23 11:44:56 +05:30
messages.removeWhere((m) => m['client_id'] == incomingClientId);
2025-12-18 11:03:25 +05:30
messages.add(msg);
});
2025-12-15 11:10:52 +05:30
_scrollToBottom();
},
onAdminMessage: () {
if (!mounted) {
context.read<ChatUnreadProvider>().increment();
}
},
);
if (!mounted) return;
setState(() => isLoading = false);
_scrollToBottom();
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollCtrl.hasClients) {
2025-12-23 11:44:56 +05:30
_scrollCtrl.animateTo(
_scrollCtrl.position.maxScrollExtent,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
);
2025-12-15 11:10:52 +05:30
}
});
}
Future<void> _sendMessage() async {
final text = _messageCtrl.text.trim();
2025-12-18 11:03:25 +05:30
if (text.isEmpty || ticketId == null) return;
2025-12-15 11:10:52 +05:30
_messageCtrl.clear();
2025-12-18 11:03:25 +05:30
final clientId = DateTime.now().millisecondsSinceEpoch.toString();
setState(() {
messages.add({
'client_id': clientId,
'sender_type': 'App\\Models\\User',
'message': text,
'file_path': null,
'file_type': null,
'sending': true,
});
});
_scrollToBottom();
2025-12-15 11:10:52 +05:30
await _chatService.sendMessage(
ticketId!,
message: text,
2025-12-18 11:03:25 +05:30
clientId: clientId,
2025-12-15 11:10:52 +05:30
);
}
@override
void dispose() {
context.read<ChatUnreadProvider>().setChatOpen(false);
_socket.disconnect();
_messageCtrl.dispose();
_scrollCtrl.dispose();
super.dispose();
}
2025-12-03 11:57:05 +05:30
@override
Widget build(BuildContext context) {
2025-12-15 11:10:52 +05:30
return Scaffold(
2025-12-23 11:44:56 +05:30
appBar: PreferredSize(
preferredSize: const Size.fromHeight(56),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF2196F3),
Color(0xFF1565C0),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(0, 3),
),
],
),
child: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: Padding(
padding: const EdgeInsets.only(left: 12),
child: CircleAvatar(
radius: 18,
backgroundColor: Colors.white,
child: Icon(
Icons.support_agent,
color: Colors.blue,
size: 20,
),
),
),
title: const Text(
"Support Chat",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 18,
),
),
centerTitle: false,
iconTheme: const IconThemeData(color: Colors.white),
),
),
),
2025-12-15 11:10:52 +05:30
body: isLoading
? const Center(child: CircularProgressIndicator())
: Column(
children: [
Expanded(child: _buildMessages()),
_buildInput(),
],
),
);
}
Widget _buildMessages() {
2025-12-18 11:03:25 +05:30
return ListView(
2025-12-15 11:10:52 +05:30
controller: _scrollCtrl,
2025-12-23 11:44:56 +05:30
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
2025-12-18 11:03:25 +05:30
children: [
...messages.map((msg) {
final isUser = msg['sender_type'] == 'App\\Models\\User';
return Align(
2025-12-23 11:44:56 +05:30
alignment:
isUser ? Alignment.centerRight : Alignment.centerLeft,
2025-12-18 11:03:25 +05:30
child: Container(
2025-12-23 11:44:56 +05:30
constraints: const BoxConstraints(maxWidth: 280),
2025-12-18 11:03:25 +05:30
margin: const EdgeInsets.symmetric(vertical: 6),
2025-12-23 11:44:56 +05:30
padding: const EdgeInsets.all(12),
2025-12-18 11:03:25 +05:30
decoration: BoxDecoration(
2025-12-23 11:44:56 +05:30
color: isUser ? null : Colors.white,
gradient: isUser
? LinearGradient(
colors: [
Colors.lightBlueAccent,
Colors.blue.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(16),
topRight: const Radius.circular(16),
bottomLeft:
isUser ? const Radius.circular(16) : Radius.zero,
bottomRight:
isUser ? Radius.zero : const Radius.circular(16),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
),
],
2025-12-18 11:03:25 +05:30
),
child: msg['file_path'] == null
? Text(
msg['message'] ?? '',
style: TextStyle(
2025-12-23 11:44:56 +05:30
color: isUser ? Colors.white : Colors.blue,
fontSize: 15,
2025-12-18 11:03:25 +05:30
),
)
: ChatFilePreview(
filePath: msg['file_path'],
fileType: msg['file_type'] ?? '',
isUser: isUser,
),
2025-12-15 11:10:52 +05:30
),
2025-12-18 11:03:25 +05:30
);
}),
],
2025-12-15 11:10:52 +05:30
);
}
Widget _buildInput() {
return SafeArea(
2025-12-23 11:44:56 +05:30
child: Padding(
padding: const EdgeInsets.all(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
2025-12-16 10:24:16 +05:30
),
2025-12-23 11:44:56 +05:30
],
2025-12-15 11:10:52 +05:30
),
2025-12-23 11:44:56 +05:30
child: Row(
children: [
IconButton(
icon: const Icon(Icons.attach_file),
onPressed: _pickAndSendFile,
),
Expanded(
child: TextField(
controller: _messageCtrl,
decoration: const InputDecoration(
hintText: "Type a message…",
border: InputBorder.none,
),
),
),
IconButton(
icon: const Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
),
],
2025-12-15 11:10:52 +05:30
),
2025-12-23 11:44:56 +05:30
),
2025-12-15 11:10:52 +05:30
),
2025-12-03 11:57:05 +05:30
);
}
}