import 'package:flutter/material.dart';
import '../models/channel.dart';
import '../services/api_service.dart';
import '../services/auth_service.dart';
import 'widgets/channel_circle_item.dart';
import '../screens/channel_screen.dart';

class ChannelListScreen extends StatefulWidget {
  const ChannelListScreen({super.key});

  @override
  State<ChannelListScreen> createState() => _ChannelListScreenState();
}

class _ChannelListScreenState extends State<ChannelListScreen> {
  final _authService = AuthService();
  late final ApiService _api;
  List<Channel> _channels = [];
  bool _loading = true;
  String? _currentUserId;
  PageController? _pageCtrl;
  int _currentPage = 0;
  bool _initialized = false;

  @override
  void initState() {
    super.initState();
    _api = ApiService(_authService);
    _init();
  }

  Future<void> _init() async {
    _currentUserId = await _authService.getUserId();
    await _loadChannels();
  }

  Future<void> _loadChannels() async {
    setState(() => _loading = true);
    final channels = await _api.getChannels();
    if (!mounted) return;
    setState(() {
      _channels = channels;
      _loading = false;
      if (!_initialized) {
        // صفحه ۰ می‌شود خانه، صفحه ۱ اولین کانال
        final startPage = channels.isNotEmpty ? 1 : 0;
        _pageCtrl = PageController(initialPage: startPage);
        _currentPage = startPage;
        _initialized = true;
      }
    });
  }

  void _goHome() {
    Navigator.pop(context); // بازگشت به صفحه HomeScreen
  }

  void _enterChannel(Channel ch) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) =>
            ChannelScreen(channel: ch, currentUserId: _currentUserId),
      ),
    );
  }

  @override
  void dispose() {
    _pageCtrl?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_loading || _pageCtrl == null) {
      return const Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: CircularProgressIndicator(
            color: Color(0xFF00C853),
            strokeWidth: 2,
          ),
        ),
      );
    }

    final totalPages = _channels.length + 1; // +1 برای صفحه خانه

    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: PageView.builder(
                controller: _pageCtrl!,
                scrollDirection: Axis.vertical,
                onPageChanged: (i) => setState(() => _currentPage = i),
                itemCount: totalPages,
                itemBuilder: (ctx, i) {
                  if (i == 0) return _buildHomeOption();
                  return _buildChannelPage(_channels[i - 1]);
                },
              ),
            ),
            _buildPageIndicator(totalPages),
          ],
        ),
      ),
    );
  }

  Widget _buildPageIndicator(int totalPages) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 6, top: 2),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(totalPages, (i) {
          final isActive = i == _currentPage;
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            child: Container(
              width: isActive ? 6 : 4,
              height: isActive ? 6 : 4,
              decoration: BoxDecoration(
                color: isActive ? const Color(0xFF00C853) : Colors.white24,
                shape: BoxShape.circle,
              ),
            ),
          );
        }),
      ),
    );
  }

  // صفحه اول: دکمه خانه
  Widget _buildHomeOption() {
    return Center(
      child: GestureDetector(
        onTap: _goHome,
        child: Container(
          width: 180, // کمی بزرگتر از کانال‌ها
          height: 180,
          decoration: BoxDecoration(
            color: const Color(0xFF1C1C1E),
            shape: BoxShape.circle,
            border: Border.all(color: Colors.white24, width: 2),
            boxShadow: [
              BoxShadow(
                color: Colors.white.withOpacity(0.05),
                blurRadius: 20,
                spreadRadius: 2,
              ),
            ],
          ),
          child: const Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.home, color: Colors.white70, size: 40),
              SizedBox(height: 10),
              Text(
                'خانه',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // صفحات کانال
  Widget _buildChannelPage(Channel channel) {
    return Center(
      child: ChannelCircleItem(
        channel: channel,
        onTap: () => _enterChannel(channel),
      ),
    );
  }
}
