2025-12-30 15:02:51 +05:30

240 lines
8.0 KiB
Dart

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/constants/colors.dart';
import '../../../core/constants/api_constants.dart';
class ChannelsScreen extends StatefulWidget {
const ChannelsScreen({super.key});
@override
State<ChannelsScreen> createState() => _ChannelsScreenState();
}
class _ChannelsScreenState extends State<ChannelsScreen> {
List<dynamic> _channels = [];
Map<String, dynamic>? _accountData;
bool _isLoading = true;
String? _connectedChannelId;
@override
void initState() {
super.initState();
_loadData();
}
Future<void> _loadData() async {
setState(() => _isLoading = true);
try {
final prefs = await SharedPreferences.getInstance();
final email = prefs.getString('user_email');
_connectedChannelId = prefs.getString('connectedChannel');
final response = await http.get(
Uri.parse('${ApiConstants.liveBaseUrl}/social/channels?userId=$email'),
);
if (response.statusCode == 200) {
_channels = jsonDecode(response.body);
}
if (_connectedChannelId != null) {
await _loadAccountDetails();
}
} catch (e) {
print("Error loading channels: $e");
} finally {
setState(() => _isLoading = false);
}
}
Future<void> _loadAccountDetails() async {
try {
final prefs = await SharedPreferences.getInstance();
final email = prefs.getString('user_email');
final response = await http.get(
Uri.parse('${ApiConstants.liveBaseUrl}/social/account?userId=$email'),
);
if (response.statusCode == 200) {
_accountData = jsonDecode(response.body);
}
} catch (e) {
print("Error loading account details: $e");
}
}
Future<void> _connectChannel(String channelId, String channelName) async {
setState(() => _isLoading = true);
try {
final prefs = await SharedPreferences.getInstance();
final email = prefs.getString('user_email');
final response = await http.post(
Uri.parse('${ApiConstants.liveBaseUrl}/social/connect?userId=$email'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'channel_id': channelId}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final savedId = data['data']['channel_id'] ?? channelId;
await prefs.setString('connectedChannel', savedId);
setState(() => _connectedChannelId = savedId);
await _loadAccountDetails();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("$channelName connected successfully!")),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Failed to connect $channelName")),
);
} finally {
setState(() => _isLoading = false);
}
}
Future<void> _removeChannel() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('connectedChannel');
setState(() {
_connectedChannelId = null;
_accountData = null;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Channel removed successfully!")),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.darkBg,
body: _isLoading
? const Center(child: CircularProgressIndicator(color: AppColors.primary))
: _connectedChannelId != null
? _buildAccountDetails()
: _buildChannelSelection(),
);
}
Widget _buildAccountDetails() {
if (_accountData == null) {
return const Center(child: CircularProgressIndicator(color: AppColors.primary));
}
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: AppColors.cardBg,
borderRadius: BorderRadius.circular(30),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: Column(
children: [
CircleAvatar(
radius: 60,
backgroundImage: NetworkImage(_accountData!['profile_picture_url'] ?? ''),
),
const SizedBox(height: 20),
Text(
_accountData!['username'] ?? 'User',
style: GoogleFonts.nunito(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildStatItem(_accountData!['media_count'].toString(), "Posts"),
_buildStatItem(_accountData!['followers_count'].toString(), "Followers"),
_buildStatItem(_accountData!['follows_count'].toString(), "Following"),
],
),
const SizedBox(height: 24),
if (_accountData!['biography'] != null)
Text(
_accountData!['biography'],
textAlign: TextAlign.center,
style: GoogleFonts.nunito(color: Colors.white70),
),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _removeChannel,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade700,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
child: const Text("Remove Channel"),
),
),
],
),
),
],
),
);
}
Widget _buildStatItem(String value, String label) {
return Column(
children: [
Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white)),
Text(label, style: const TextStyle(fontSize: 12, color: Colors.white54)),
],
);
}
Widget _buildChannelSelection() {
return ListView.builder(
padding: const EdgeInsets.all(24),
itemCount: _channels.length,
itemBuilder: (context, index) {
final ch = _channels[index];
final hasLinked = ch['has_linked_account'] == true;
return Container(
margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.cardBg,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: Column(
children: [
Text(
ch['name'],
style: GoogleFonts.nunito(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: hasLinked ? () => _connectChannel(ch['id'], ch['name']) : null,
style: ElevatedButton.styleFrom(
backgroundColor: hasLinked ? AppColors.primary : Colors.grey.shade800,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
child: Text(hasLinked ? "Connect" : "Not Linked"),
),
),
],
),
);
},
);
}
}