Files
2026-05-25 01:12:09 +03:00

554 lines
23 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../data/models/whatsapp_status_model.dart';
import '../../data/models/meta_session_model.dart';
import '../cubit/dashboard_cubit.dart';
class ChannelsView extends StatefulWidget {
final WhatsAppStatusModel? whatsappStatus;
final List<MetaSessionModel> metaSessions;
final VoidCallback onRefresh;
const ChannelsView({
super.key,
required this.whatsappStatus,
required this.metaSessions,
required this.onRefresh,
});
@override
State<ChannelsView> createState() => _ChannelsViewState();
}
class _ChannelsViewState extends State<ChannelsView> with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
_tabController = TabController(length: 3, vsync: this);
super.initState();
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
// English: Open confirmation dialog to disconnect WhatsApp.
void _showWhatsAppDisconnectDialog(BuildContext context) {
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: const Text('قطع اتصال الواتساب', style: TextStyle(color: Colors.white)),
content: const Text(
'هل أنت متأكد من رغبتك في قطع اتصال الواتساب؟ سيؤدي ذلك إلى تعطيل الردود التلقائية لعملاء الواتساب.',
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().disconnectWhatsApp();
},
child: const Text('نعم، اقطع الاتصال', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
// English: Open confirmation dialog to disconnect a Meta session.
void _showMetaDisconnectDialog(BuildContext context, MetaSessionModel session) {
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: Text(
session.channelType == 'messenger' ? 'قطع اتصال ماسنجر' : 'قطع اتصال إنستغرام',
style: const TextStyle(color: Colors.white),
),
content: Text(
'هل أنت متأكد من رغبتك في قطع الاتصال عن ${session.pageName}؟',
style: const TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().disconnectMetaSession(session.id);
},
child: const Text('نعم، اقطع الاتصال', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
// English: Show connect dialog for Facebook Page or Instagram Business Account.
void _showConnectMetaDialog(BuildContext context, String type) {
final pageNameController = TextEditingController();
final pageIdController = TextEditingController();
final tokenController = TextEditingController();
final formKey = GlobalKey<FormState>();
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: Text(
type == 'messenger' ? 'ربط صفحة فيسبوك' : 'ربط حساب إنستغرام',
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
content: Form(
key: formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.03),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.white10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.info_outline, color: Colors.purpleAccent, size: 16),
const SizedBox(width: 6),
Text(
type == 'messenger'
? 'تعليمات ربط صفحة فيسبوك:'
: 'تعليمات ربط حساب إنستغرام:',
style: const TextStyle(
color: Colors.purpleAccent,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 8),
if (type == 'messenger') ...[
_buildStep('1. اذهب إلى developers.facebook.com وأنشئ تطبيقاً.'),
_buildStep('2. أضف منتج Messenger إلى لوحة تحكم تطبيقك.'),
_buildStep('3. اربط صفحتك وولد رمز الوصول (Page Access Token).'),
_buildStep('4. انسخ معرّف الصفحة والرمز وضعهما أدناه.'),
] else ...[
_buildStep('1. حول حساب إنستغرام لحساب أعمال واربطه بصفحة فيسبوك.'),
_buildStep('2. اذهب لـ developers.facebook.com وأضف Messenger.'),
_buildStep('3. انسخ معرّف حساب الأعمال من إعدادات الصفحة المرتبطة.'),
_buildStep('4. ولد رمز وصول الصفحة المرتبطة وضعه في الحقل أدناه.'),
],
],
),
),
TextFormField(
controller: pageNameController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: type == 'messenger' ? 'اسم الصفحة' : 'اسم الحساب',
labelStyle: const TextStyle(color: Colors.white60),
enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال الاسم' : null,
),
const SizedBox(height: 12),
TextFormField(
controller: pageIdController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: type == 'messenger' ? 'معرّف الصفحة (Page ID)' : 'معرّف الحساب (Account ID)',
labelStyle: const TextStyle(color: Colors.white60),
enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال المعرّف' : null,
),
const SizedBox(height: 12),
TextFormField(
controller: tokenController,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'رمز الوصول للصفحة (Access Token)',
labelStyle: TextStyle(color: Colors.white60),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال رمز الوصول' : null,
),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.purpleAccent),
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().connectMetaSession(
type,
pageIdController.text.trim(),
pageNameController.text.trim(),
tokenController.text.trim(),
);
}
},
child: const Text('ربط وتفعيل'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// English: Channel selector TabBar.
Container(
color: const Color(0xFF15102A),
child: TabBar(
controller: _tabController,
indicatorColor: Colors.purpleAccent,
labelColor: Colors.purpleAccent,
unselectedLabelColor: Colors.white60,
tabs: const [
Tab(icon: Icon(Icons.phone_android), text: 'واتساب'),
Tab(icon: Icon(Icons.facebook), text: 'فيسبوك ماسنجر'),
Tab(icon: Icon(Icons.camera_alt), text: 'إنستغرام'),
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: TabBarView(
controller: _tabController,
children: [
_buildWhatsAppTab(),
_buildMetaTab('messenger'),
_buildMetaTab('instagram'),
],
),
),
],
);
}
Widget _buildWhatsAppTab() {
final session = widget.whatsappStatus;
return SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'📱 إعدادات اتصال الواتساب',
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
const Text(
'اربط حسابك مع بوابة واتساب لتفعيل الردود التلقائية وروبوت خدمة العملاء.',
style: TextStyle(color: Colors.white60, fontSize: 12),
),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF15102A),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.05)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('حالة الجلسة الحالية', style: TextStyle(color: Colors.white70, fontSize: 14)),
_buildWhatsAppStatusBadge(session?.status ?? 'disconnected'),
],
),
const Divider(color: Colors.white10, height: 24),
_buildDetailsRow('اسم الجلسة', session?.name ?? 'WhatsApp Team'),
_buildDetailsRow('مفتاح التعريف', session?.sessionKey ?? 'لا يوجد'),
if (session?.phone != null) _buildDetailsRow('رقم الهاتف المرتبط', session!.phone!),
const SizedBox(height: 20),
if (session == null || session.status == 'disconnected') ...[
const Text(
'⚠️ الحساب غير متصل. يرجى توليد رمز الاستجابة السريعة ومسحه ضوئياً لتفعيل الخدمة.',
style: TextStyle(color: Colors.orangeAccent, fontSize: 12),
),
const SizedBox(height: 20),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purpleAccent,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.qr_code_scanner),
label: const Text('توليد رمز الاستجابة QR'),
onPressed: () {
context.read<DashboardCubit>().requestWhatsAppQr();
},
),
] else if (session.status == 'waiting_qr') ...[
const Text(
'🔍 رمز الاستجابة جاهز. افتح الواتساب واختر الأجهزة المرتبطة لمسح الرمز:',
style: TextStyle(color: Colors.yellowAccent, fontSize: 12),
),
const SizedBox(height: 20),
Center(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.qr_code_2, size: 180, color: Colors.black),
),
),
const SizedBox(height: 20),
] else if (session.status == 'connected') ...[
const Text(
'✅ الحساب متصل وجاهز للعمل. الردود التلقائية وروبوت خدمة العملاء نشطان.',
style: TextStyle(color: Colors.greenAccent, fontSize: 12),
),
const SizedBox(height: 20),
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.redAccent,
side: const BorderSide(color: Colors.redAccent),
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.link_off),
label: const Text('قطع الاتصال'),
onPressed: () => _showWhatsAppDisconnectDialog(context),
),
],
],
),
),
],
),
);
}
Widget _buildMetaTab(String type) {
final filtered = widget.metaSessions.where((s) => s.channelType == type).toList();
final title = (type == 'messenger') ? 'فيسبوك ماسنجر' : 'إنستغرام الأعمال';
final desc = (type == 'messenger')
? 'اربط صفحات فيسبوك الخاصة بك لتفعيل الرد الآلي والمحادثات مع العملاء.'
: 'اربط حسابات إنستغرام للأعمال لتفعيل روبوت المحادثة المخصص.';
return SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'💬 إعدادات $title',
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
Text(
desc,
style: const TextStyle(color: Colors.white60, fontSize: 12),
),
],
),
],
),
const SizedBox(height: 20),
if (filtered.isEmpty) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: const Color(0xFF15102A),
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
Icon(type == 'messenger' ? Icons.facebook : Icons.camera_alt, size: 48, color: Colors.white30),
const SizedBox(height: 12),
const Text('لا توجد قنوات مرتبطة حالياً', style: TextStyle(color: Colors.white70, fontSize: 14)),
const SizedBox(height: 16),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purpleAccent,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.add),
label: Text('ربط قناة $title new'),
onPressed: () => _showConnectMetaDialog(context, type),
),
],
),
),
] else ...[
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: filtered.length,
itemBuilder: (context, index) {
final item = filtered[index];
return Card(
color: const Color(0xFF15102A),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.purpleAccent.withOpacity(0.1),
child: Icon(type == 'messenger' ? Icons.messenger_outline : Icons.camera_alt, color: Colors.purpleAccent),
),
title: Text(item.pageName, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
subtitle: Text('ID: ${item.pageId}', style: const TextStyle(color: Colors.white60, fontSize: 12)),
trailing: IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.redAccent),
onPressed: () => _showMetaDisconnectDialog(context, item),
),
),
);
},
),
const SizedBox(height: 16),
Center(
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.purpleAccent,
side: const BorderSide(color: Colors.purpleAccent),
),
icon: const Icon(Icons.add),
label: const Text('ربط صفحة إضافية'),
onPressed: () => _showConnectMetaDialog(context, type),
),
),
],
],
),
);
}
Widget _buildDetailsRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(color: Colors.white70, fontSize: 13)),
Text(value, style: const TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.bold)),
],
),
);
}
Widget _buildWhatsAppStatusBadge(String status) {
Color color;
String text;
switch (status) {
case 'connected':
color = Colors.green;
text = 'متصل';
break;
case 'waiting_qr':
color = Colors.orange;
text = 'بانتظار المسح';
break;
case 'connecting':
color = Colors.blue;
text = 'جاري الاتصال';
break;
default:
color = Colors.red;
text = 'غير متصل';
break;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: color),
),
child: Text(text, style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.bold)),
);
}
Widget _buildStep(String text) {
const String linkText = 'developers.facebook.com';
if (text.contains(linkText)) {
final List<String> parts = text.split(linkText);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2.0),
child: RichText(
text: TextSpan(
style: const TextStyle(color: Colors.white70, fontSize: 11, height: 1.4, fontFamily: 'Outfit'), // or default font family
children: [
TextSpan(text: parts[0]),
TextSpan(
text: linkText,
style: const TextStyle(
color: Colors.purpleAccent,
decoration: TextDecoration.underline,
fontWeight: FontWeight.bold,
),
recognizer: TapGestureRecognizer()
..onTap = () async {
final Uri url = Uri.parse('https://developers.facebook.com');
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
}
},
),
if (parts.length > 1) TextSpan(text: parts[1]),
],
),
),
);
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2.0),
child: Text(
text,
style: const TextStyle(color: Colors.white70, fontSize: 11, height: 1.4),
),
);
}
}