import 'package:flutter/material.dart';
import 'dart:async';

import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';
import '../../dialogs/room_detail_dialog.dart';

// Import for finished (종료된) rooms
import '../room/finish_private_page.dart';
import '../room/finish_team_page.dart';

// Config
import '../../config/config.dart';

// Ads
import '../../plugins/admob.dart';

class RoomSearchListPage extends StatefulWidget {
  final String roomStatus; // WAIT / RUNNING / FINISH

  const RoomSearchListPage({Key? key, required this.roomStatus}) : super(key: key);

  @override
  State<RoomSearchListPage> createState() => _RoomSearchListPageState();
}

class _RoomSearchListPageState extends State<RoomSearchListPage> {
  final TextEditingController _searchController = TextEditingController();

  List<Map<String, dynamic>> _roomList = [];

  bool _isLoading = false;     // 로딩중
  bool _hasMore = true;        // 더 가져올 데이터 있는지
  int _currentPage = 1;
  final int _pageSize = 10;

  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()..addListener(_onScroll);
    _fetchRoomList(isRefresh: true);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  // Scroll event listener (스크롤 이벤트)
  void _onScroll() {
    if (!_scrollController.hasClients) return;
    final thresholdPixels = 200;
    final maxScroll = _scrollController.position.maxScrollExtent;
    final currentScroll = _scrollController.position.pixels;

    // If near bottom, load more (바닥 근처면 더 불러오기)
    if (maxScroll - currentScroll <= thresholdPixels) {
      _fetchRoomList(isRefresh: false);
    }
  }

  // Fetch room list (방 목록 불러오기)
  Future<void> _fetchRoomList({required bool isRefresh}) async {
    if (_isLoading) return;
    if (!isRefresh && !_hasMore) return;

    setState(() => _isLoading = true);

    if (isRefresh) {
      _currentPage = 1;
      _hasMore = true;
      _roomList.clear();
    }

    final String searchType = widget.roomStatus.toUpperCase(); 
    // ex) WAIT, RUNNING, FINISH
    final String searchValue = _searchController.text.trim();
    final String searchPage = _currentPage.toString();

    final requestBody = {
      "search_type": searchType,
      "search_value": searchValue,
      "search_page": searchPage,
    };

    try {
      final response = await Api.serverRequest(uri: '/room/score/room/list', body: requestBody);

      if (response == null || response['result'] != 'OK') {
        showResponseDialog(context, 'Error', 'Failed to load room list.'); 
        // '오류', '방 목록을 불러오지 못했습니다.'
      } else {
        final innerResp = response['response'];
        if (innerResp == null || innerResp['result'] != 'OK') {
          showResponseDialog(context, 'Error', 'Invalid internal response.'); 
          // '오류', '내부 응답이 잘못되었습니다.'
        } else {
          final respData = innerResp['data'];
          if (respData is List) {
            if (respData.isEmpty) {
              _hasMore = false;
            } else {
              for (var item in respData) {
                final parsedItem = {
                  'room_seq': item['room_seq'] ?? 0,
                  'nickname': item['nickname'] ?? 'User', // '사용자'
                  // Convert WAIT/RUNNING/FINISH to Korean, stored in 'room_status'
                  'room_status': _statusToKr(item['room_status'] ?? ''), 
                  // Store raw English status in 'raw_room_status'
                  'raw_room_status': (item['room_status'] ?? '').toString().toUpperCase(),
                  'open_yn': (item['open_yn'] == 'Y') ? 'Public' : 'Private', 
                  // '공개' 또는 '비공개'
                  'room_type': (item['room_type_name'] ?? 'PRIVATE').toString().toLowerCase(),
                  'room_title': item['room_title'] ?? '(No Title)',  // '(방제목 없음)'
                  'room_intro': item['room_intro'] ?? '',
                  'now_people': item['now_number_of_people']?.toString() ?? '0',
                  'max_people': item['number_of_people']?.toString() ?? '0',
                  'start_dt': item['start_dt'],
                  'end_dt': item['end_dt'],
                };
                _roomList.add(parsedItem);
              }

              if (respData.length < _pageSize) {
                _hasMore = false;
              }
              _currentPage++;
            }
          }
        }
      }
    } catch (e) {
      showResponseDialog(context, 'Error', 'Exception occurred while requesting server: $e'); 
      // '오류', '서버 요청 중 예외 발생'
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // Convert raw status to Korean (영문 상태 → 한글)
  String _statusToKr(String status) {
    switch (status.toUpperCase()) {
      case 'WAIT':
        return 'Waiting';   // '대기중'
      case 'RUNNING':
        return 'Running';   // '진행중'
      case 'FINISH':
        return 'Finished';  // '종료'
      default:
        return status;
    }
  }

  // On tap search icon or submit (검색 실행)
  void _onSearch() {
    _fetchRoomList(isRefresh: true);
  }

  // When a room item is tapped (방 항목 클릭 시)
  void _onRoomItemTap(Map<String, dynamic> item) {
    final rawStatus = (item['raw_room_status'] ?? '').toString().toUpperCase(); 
    // WAIT / RUNNING / FINISH

    if (rawStatus == 'FINISH') {
      // If the room is finished, go to FinishPrivatePage or FinishTeamPage
      final roomType = (item['room_type'] ?? 'private').toString().toLowerCase(); 
      final roomSeq  = (item['room_seq'] ?? 0) as int;
      final roomTitle = (item['room_title'] ?? '(Finished room)') as String; 
      // '(종료된 방)'

      if (roomType == 'private') {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => FinishPrivatePage(
              roomSeq: roomSeq,
              enterType: 'search',
            ),
          ),
        );
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => FinishTeamPage(
              roomSeq: roomSeq,
              enterType: 'search',
            ),
          ),
        );
      }
    } else {
      // If the room is waiting/running, open detail dialog (대기중/진행중: 기존 로직)
      showDialog(
        context: context,
        builder: (_) => RoomDetailDialog(roomData: item),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // Convert incoming roomStatus to Korean to show in the title (한글 변환)
    final statusKr = _statusToKr(widget.roomStatus);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text(
          '$statusKr Rooms Search', // '$statusKr 방 검색'
          style: const TextStyle(color: Colors.white),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      // Bottom ad banner (화면 하단 광고 영역)
      bottomNavigationBar: AdBannerWidget(),

      body: Column(
        children: [
          // Search box (검색창)
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _searchController,
              onSubmitted: (_) => _onSearch(),
              style: const TextStyle(color: Colors.black),
              decoration: InputDecoration(
                hintText: 'Enter room title', // '방 제목 입력'
                hintStyle: TextStyle(color: Colors.grey.shade400),
                prefixIcon: const Icon(Icons.search, color: Colors.black54),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.close, color: Colors.black54),
                  onPressed: () {
                    _searchController.clear();
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.black),
                  borderRadius: BorderRadius.circular(20),
                ),
                contentPadding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
              ),
            ),
          ),

          Expanded(
            child: _isLoading && _roomList.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _buildRoomListView(),
          ),
        ],
      ),
    );
  }

  Widget _buildRoomListView() {
    if (_roomList.isEmpty) {
      return const Center(
        child: Text(
          'No results found.', // '검색 결과가 없습니다.'
          style: TextStyle(color: Colors.black),
        ),
      );
    }
    return ListView.builder(
      controller: _scrollController,
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      itemCount: _roomList.length,
      itemBuilder: (context, index) {
        final item = _roomList[index];
        return _buildRoomItem(item);
      },
    );
  }

  // Each room item (방 목록 아이템)
  Widget _buildRoomItem(Map<String, dynamic> item) {
    final roomTitle  = item['room_title'] ?? '(No Title)'; // '(방제목 없음)'
    final nickname   = item['nickname'] ?? 'User';        // '유저'
    final roomStatus = item['room_status'] ?? 'Waiting';  // '대기중'
    final openYn     = item['open_yn'] ?? 'Public';       // '공개' / '비공개'
    final nowPeople  = item['now_people'] ?? '0';
    final maxPeople  = item['max_people'] ?? '0';
    final roomIntro  = item['room_intro'] ?? '';

    return GestureDetector(
      onTap: () => _onRoomItemTap(item),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black54),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              roomTitle,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
            const SizedBox(height: 4),
            Text('$nickname / $roomStatus / $openYn / $nowPeople/$maxPeople', overflow: TextOverflow.ellipsis, maxLines: 1), 
            // ex) '유저 / 대기중 / 공개 / 3/10명'
            const SizedBox(height: 4),
            Text(roomIntro, style: const TextStyle(fontSize: 12), overflow: TextOverflow.ellipsis, maxLines: 1),
          ],
        ),
      ),
    );
  }
}
