import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../../../core/services/news_offline_service.dart';
import '../../../../core/networks/api_client.dart';

class NewsSyncBar extends StatelessWidget {
  const NewsSyncBar({super.key});
  @override Widget build(BuildContext context)=>ValueListenableBuilder<String>(
    valueListenable:NewsOfflineService.status,builder:(context,status,_)=>Container(
      padding:const EdgeInsets.symmetric(horizontal:10,vertical:2),
      decoration:BoxDecoration(color:const Color(0xFFF0F5F2),borderRadius:BorderRadius.circular(8)),
      child:Row(children:[const Icon(Icons.offline_pin_outlined,size:16,color:Color(0xFF026930)),const SizedBox(width:6),
        Expanded(child:Text(status,maxLines:2,overflow:TextOverflow.ellipsis,style:const TextStyle(fontSize:11))),
        IconButton(tooltip:'Sync now',onPressed:()=>NewsOfflineService.sync(force:true),icon:const Icon(Icons.sync,size:18)),
        TextButton(onPressed:()=>showDialog<void>(context:context,builder:(_)=>const NewsAccountGuard(child:_NewsOutbox())),child:const Text('Outbox')),
      ]),
    ));
}
class _NewsOutbox extends StatefulWidget {
  const _NewsOutbox();
  @override State<_NewsOutbox> createState()=>_NewsOutboxState();
}
class _NewsOutboxState extends State<_NewsOutbox> {
  List<Map<String,dynamic>> _jobs=[];String? _error;
  @override void initState(){super.initState();NewsOfflineService.revision.addListener(_load);_load();}
  @override void dispose(){NewsOfflineService.revision.removeListener(_load);super.dispose();}
  Future<void> _load()async{
    try{final jobs=await NewsOfflineService.outbox();if(mounted)setState(()=>_jobs=jobs);}
    catch(e){if(mounted)setState(()=>_error=e.toString());}
  }
  Future<void> _discard(Map<String,dynamic> job)async{
    final yes=await showDialog<bool>(context:context,builder:(c)=>AlertDialog(
      title:const Text('Remove local outbox entry?'),
      content:const Text('This removes the saved draft from this device. It does not undo anything already received by the server. For an uncertain send, check the story or conversation first.'),
      actions:[TextButton(onPressed:()=>Navigator.pop(c,false),child:const Text('Cancel')),FilledButton(onPressed:()=>Navigator.pop(c,true),child:const Text('Remove'))]));
    if(yes!=true)return;
    try{await NewsOfflineService.discardJob('${job['key']}');await _load();}
    catch(e){if(mounted)setState(()=>_error=e.toString());}
  }
  @override Widget build(BuildContext context)=>AlertDialog(
    title:const Text('Newsplace outbox'),
    content:SizedBox(width:540,height:360,child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
      const Text('Pending items wait on this device. “Review” means delivery was not confirmed; check the server before creating a replacement.',style:TextStyle(fontSize:12)),
      if(_error!=null)Text(_error!,style:const TextStyle(color:Colors.red)),
      const SizedBox(height:10),
      Expanded(child:_jobs.isEmpty?const Center(child:Text('Nothing waiting to send.')):ListView.builder(itemCount:_jobs.length,itemBuilder:(context,index){
        final job=_jobs[index];final p=job['payload'] as Map;
        return ListTile(contentPadding:EdgeInsets.zero,
          leading:Icon(job['state']=='review'?Icons.error_outline:Icons.schedule,color:job['state']=='review'?Colors.orange:Colors.green),
          title:Text('${job['kind']} · ${job['state']}',style:const TextStyle(fontWeight:FontWeight.w700)),
          subtitle:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
            Text('${p['title']??p['text']??p['reason']??'Story ${job['item']}'}',maxLines:2,overflow:TextOverflow.ellipsis),
            if(job['error']!=null)Padding(padding:const EdgeInsets.only(top:6),child:Container(
              padding:const EdgeInsets.all(8),decoration:BoxDecoration(color:const Color(0xFFFFF4E5),borderRadius:BorderRadius.circular(6)),
              child:Text('${job['error']}',maxLines:4,overflow:TextOverflow.ellipsis,style:const TextStyle(color:Color(0xFF8A4B08),fontSize:11)),
            )),
            if(job['server_id']!=null)Text('Server story ID: ${job['server_id']}',style:const TextStyle(fontSize:10)),
            if(p['hasVideo']==true||((p['imageCount'] as num?)?.toInt()??0)>0)
              Text('${p['imageCount']??0} photos${p['hasVideo']==true?' · video attached':''}',style:const TextStyle(fontSize:10)),
          ]),
          trailing:IconButton(tooltip:'Remove saved entry',onPressed:job['state']=='sending'?null:()=>_discard(job),icon:const Icon(Icons.close)));
      })),
    ])),
    actions:[TextButton(onPressed:()=>Navigator.pop(context),child:const Text('Close')),FilledButton(onPressed:()=>NewsOfflineService.sync(force:true),child:const Text('Send pending'))],
  );
}

/// Load from the account-bound byte cache first. Never prefetch the full gallery.
class NewsCachedImage extends StatefulWidget {
  final String url;final BoxFit fit;final int decodeWidth;
  const NewsCachedImage({super.key,required this.url,this.fit=BoxFit.cover,this.decodeWidth=640});
  @override State<NewsCachedImage> createState()=>_NewsCachedImageState();
}
class _NewsCachedImageState extends State<NewsCachedImage> {
  static const int _maxMemoryImages = 48;
  static const int _maxMemoryBytes = 24 * 1024 * 1024;
  static const int _maxImageBytes = 4 * 1024 * 1024;
  static const int _maxConcurrentDownloads = 6;
  static final LinkedHashMap<String, Uint8List> _memoryCache = LinkedHashMap();
  static int _memoryByteCount = 0;
  static String _activeScope = '';
  Uint8List? _bytes;
  DateTime? _lastAttempt;
  void _retry(){if(_bytes==null&&(_lastAttempt==null||DateTime.now().difference(_lastAttempt!)>const Duration(seconds:30)))_load();}
  static final Map<String,Future<Uint8List?>> _pending={};
  static int _active=0;
  @override void initState(){super.initState();NewsOfflineService.revision.addListener(_retry);_load();}
  @override void didUpdateWidget(covariant NewsCachedImage old){super.didUpdateWidget(old);if(old.url!=widget.url){_bytes=null;_load();}}
  @override void dispose(){NewsOfflineService.revision.removeListener(_retry);super.dispose();}
  Future<void> _load()async{
    _lastAttempt=DateTime.now();
    final url=widget.url;final scope=NewsOfflineService.accountScope.value;
    if(scope.isEmpty)return;
    if(_activeScope!=scope){_memoryCache.clear();_memoryByteCount=0;_activeScope=scope;}
    final key='$scope:$url';
    try{
      final memory=_memoryCache.remove(key);
      if(memory!=null){
        _memoryCache[key]=memory;
        if(mounted&&widget.url==url&&NewsOfflineService.accountScope.value==scope)setState(()=>_bytes=memory);
        return;
      }
      final cached=await NewsOfflineService.cachedImage(url);
      final bytes=cached??await _pending.putIfAbsent(key,()=>_download(url,scope).whenComplete(()=>_pending.remove(key)));
      if(bytes!=null)_remember(key,bytes);
      if(mounted&&widget.url==url&&NewsOfflineService.accountScope.value==scope)setState(()=>_bytes=bytes);
    }catch(_){}
  }
  static void _remember(String key,Uint8List bytes){
    if(bytes.length>_maxMemoryBytes)return;
    final old=_memoryCache.remove(key);
    if(old!=null)_memoryByteCount-=old.length;
    _memoryCache[key]=bytes;
    _memoryByteCount+=bytes.length;
    while(_memoryCache.length>_maxMemoryImages||_memoryByteCount>_maxMemoryBytes){
      final oldest=_memoryCache.remove(_memoryCache.keys.first);
      if(oldest!=null)_memoryByteCount-=oldest.length;
    }
  }
  static Future<Uint8List?> _download(String url,String scope)async{
    // Keep scrolling smooth while several visible news photos load together.
    while(_active>=_maxConcurrentDownloads){await Future<void>.delayed(const Duration(milliseconds:50));if(NewsOfflineService.accountScope.value!=scope)return null;}
    _active++;final client=http.Client();
    try{
      if(NewsOfflineService.accountScope.value!=scope)return null;
      var uri=Uri.tryParse(url);if(uri==null||!['http','https'].contains(uri.scheme))return null;
      final base=Uri.parse(ApiClient.baseUrl);
      final authHeaders=uri.origin==base.origin?await ApiClient.getHeaders():<String,String>{};
      http.StreamedResponse? response;
      // Follow safe image redirects without forwarding the bearer token off-site.
      for(var redirect=0;redirect<4;redirect++){
        final request=http.Request('GET',uri!)..followRedirects=false;
        if(uri.origin==base.origin)request.headers.addAll(authHeaders);
        response=await client.send(request).timeout(const Duration(seconds:12));
        if(response.statusCode>=300&&response.statusCode<400){
          final location=response.headers['location'];
          if(location==null)return null;
          await response.stream.drain<void>();
          final next=uri.resolve(location);
          if(!['http','https'].contains(next.scheme))return null;
          uri=next;
          continue;
        }
        break;
      }
      if(response==null||response.statusCode!=200||(response.contentLength??0)>_maxImageBytes)return null;
      final builder=BytesBuilder(copy:false);int size=0;
      await for(final chunk in response.stream.timeout(const Duration(seconds:12))){size+=chunk.length;if(size>_maxImageBytes)return null;builder.add(chunk);}
      if(NewsOfflineService.accountScope.value!=scope)return null;
      final bytes=builder.takeBytes();await NewsOfflineService.saveImage(url,bytes,expectedScope:scope);return bytes;
    }catch(_){return null;}finally{_active--;client.close();}
  }
  @override Widget build(BuildContext context)=>_bytes==null
    ?Container(color:const Color(0xFFF0F3F5),child:const Center(child:Icon(Icons.photo_outlined,color:Color(0xFF9DA8AF),size:28)))
    :Image.memory(_bytes!,fit:widget.fit,cacheWidth:widget.decodeWidth,filterQuality:FilterQuality.medium,gaplessPlayback:true,
      frameBuilder:(context,child,frame,synchronous)=>synchronous?child:AnimatedOpacity(opacity:frame==null?0:1,duration:const Duration(milliseconds:180),child:child),
      errorBuilder:(_,__,___)=>const Icon(Icons.broken_image_outlined));
}

/// Dialogs must not keep another account's cached content visible after a switch.
class NewsAccountGuard extends StatefulWidget {
  final Widget child;
  const NewsAccountGuard({super.key,required this.child});
  @override State<NewsAccountGuard> createState()=>_NewsAccountGuardState();
}
class _NewsAccountGuardState extends State<NewsAccountGuard> {
  late final String _scope=NewsOfflineService.accountScope.value;
  @override Widget build(BuildContext context)=>ValueListenableBuilder<String>(
    valueListenable:NewsOfflineService.accountScope,builder:(context,scope,_)=>scope.isNotEmpty&&scope==_scope
      ?widget.child:AlertDialog(title:const Text('Account changed'),content:const Text('Close this window and reopen it from your current account.'),actions:[TextButton(onPressed:()=>Navigator.pop(context),child:const Text('Close'))]));
}
