import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../../../../core/services/it_support_service.dart';

const supportGreen=Color(0xFF086A43),supportGold=Color(0xFFBE7D18),supportInk=Color(0xFF19362B),supportBorder=Color(0xFFE1E9E4);
String supportLabel(dynamic value)=>'$value'.replaceAll('_',' ').split(' ').map((s)=>s.isEmpty?s:s[0].toUpperCase()+s.substring(1)).join(' ');
void supportSnack(BuildContext context,Object text){ScaffoldMessenger.of(context).showSnackBar(SnackBar(content:Text('$text'),behavior:SnackBarBehavior.floating));}
InputDecoration supportInput(String label)=>InputDecoration(labelText:label,isDense:true,filled:true,fillColor:const Color(0xFFF7F9F8),border:const OutlineInputBorder(borderRadius:BorderRadius.zero,borderSide:BorderSide(color:supportBorder)),enabledBorder:const OutlineInputBorder(borderRadius:BorderRadius.zero,borderSide:BorderSide(color:supportBorder)),focusedBorder:const OutlineInputBorder(borderRadius:BorderRadius.zero,borderSide:BorderSide(color:supportGreen,width:1.4)));
class SupportBadge extends StatelessWidget {
 final String label;final Color color;
 const SupportBadge(this.label,{super.key,this.color=supportGreen});
 @override Widget build(BuildContext context)=>Container(padding:const EdgeInsets.symmetric(horizontal:8,vertical:4),decoration:BoxDecoration(color:color.withOpacity(.09)),child:Text(label,style:TextStyle(color:color,fontSize:11,fontWeight:FontWeight.w700)));
}
// Uses the file_picker 12.x / 13.x API.
Future<SupportFile?> pickSupportFile() async {
  final PlatformFile? file = await FilePicker.pickFile(
    type: FileType.custom,
    allowedExtensions: [
      'pdf', 'doc', 'docx', 'xls', 'xlsx',
      'ppt', 'pptx', 'txt', 'csv', 'log',
      'zip', 'png', 'jpg', 'jpeg', 'webp', 'gif',
    ],
  );

  if (file == null) return null;

  final int? expectedSize = await file.length();
  if (expectedSize != null &&
      (expectedSize < 1 || expectedSize > ITSupportService.maxFileBytes)) {
    throw SupportError(413, 'Each file must be between 1 byte and 5 MB.');
  }

  final BytesBuilder bytes = BytesBuilder(copy: false);
  int total = 0;

  await for (final Uint8List chunk in file.readAsByteStream()) {
    total += chunk.length;
    if (total > ITSupportService.maxFileBytes) {
      throw SupportError(413, 'Maximum attachment size is 5 MB.');
    }
    bytes.add(chunk);
  }

  if (total < 1) {
    throw SupportError(413, 'Each file must be between 1 byte and 5 MB.');
  }
  if (expectedSize != null && total != expectedSize) {
    throw SupportError(422, 'The selected file changed. Select it again.');
  }

  return SupportFile(file.name, bytes.takeBytes());
}

/// Keeps an old account's open dialogs from exposing data after session disposal.
class SupportAccountGuard extends StatelessWidget {
 final ITSupportService service;final Widget child;
 const SupportAccountGuard({super.key,required this.service,required this.child});
 @override Widget build(BuildContext context)=>AnimatedBuilder(animation:service,builder:(context,_)=>service.closed?AlertDialog(title:const Text('Session changed'),content:const Text('Close this window and reopen IT Support.'),actions:[TextButton(onPressed:()=>Navigator.pop(context),child:const Text('Close'))]):child);
}
Future<SupportJson?> chooseSupportUser(BuildContext context,ITSupportService service,{bool technician=false})=>showDialog<SupportJson>(context:context,builder:(_)=>SupportAccountGuard(service:service,child:_UserPicker(service:service,technician:technician)));
class _UserPicker extends StatefulWidget {
 final ITSupportService service;final bool technician;
 const _UserPicker({required this.service,required this.technician});
 @override State<_UserPicker> createState()=>_UserPickerState();
}
class _UserPickerState extends State<_UserPicker> {
 final _query=TextEditingController();Timer? _timer;int _generation=0;List<SupportJson> _users=[];String? _error;bool _busy=false;
 @override void initState(){super.initState();if(widget.technician)_search();}
 @override void dispose(){_timer?.cancel();_query.dispose();super.dispose();}
 Future<void> _search()async{
  final gen=++_generation;if(!widget.technician&&_query.text.trim().length<2){setState(()=>_users=[]);return;}
  setState((){_busy=true;_error=null;});
  try{final page=await widget.service.read(widget.technician?'members':'people',{'q':_query.text.trim()});if(!mounted||gen!=_generation)return;
   setState(()=>_users=supportRows(page['items']).where((u)=>!widget.technician||['manager','technician'].contains(u['role'])).toList());
  }catch(e){if(mounted&&gen==_generation)setState(()=>_error='$e');}finally{if(mounted&&gen==_generation)setState(()=>_busy=false);}
 }
 @override Widget build(BuildContext context)=>AlertDialog(title:Text(widget.technician?'Assign to IT team':'Find university member'),content:SizedBox(width:480,height:350,child:Column(children:[
  TextField(controller:_query,decoration:supportInput('Name or email (at least 2 characters)'),onChanged:(_){_timer?.cancel();_timer=Timer(const Duration(milliseconds:300),_search);}),
  if(_busy)const LinearProgressIndicator(color:supportGreen),if(_error!=null)Text(_error!),
  Expanded(child:_users.isEmpty?const Center(child:Text('Search for a member.')):ListView.builder(itemCount:_users.length,itemBuilder:(context,i){final u=_users[i];return ListTile(leading:const CircleAvatar(backgroundColor:Color(0xFFE8F1EC),child:Icon(Icons.person_outline,color:supportGreen)),title:Text('${u['name']}'),subtitle:Text('${u['email']}'),onTap:()=>Navigator.pop(context,u));})),
 ])),actions:[TextButton(onPressed:()=>Navigator.pop(context),child:const Text('Cancel'))]);
}
Future<void> showSupportOutbox(BuildContext context,ITSupportService service)=>showDialog<void>(context:context,builder:(_)=>SupportAccountGuard(service:service,child:_Outbox(service:service)));
class _Outbox extends StatelessWidget {
 final ITSupportService service;const _Outbox({required this.service});
 @override Widget build(BuildContext context)=>AnimatedBuilder(animation:service,builder:(context,_){final jobs=service.jobs;return AlertDialog(title:const Text('Support outbox'),content:SizedBox(width:560,height:400,child:Column(children:[
  const Text('Pending entries send when connected. Review entries need attention; refresh the ticket before resubmitting a conflicting change.',style:TextStyle(fontSize:12)),const SizedBox(height:12),
  Expanded(child:jobs.isEmpty?const Center(child:Text('Everything has been sent.')):ListView.builder(itemCount:jobs.length,itemBuilder:(context,i){final j=jobs[i];final p=supportMap(j['payload']);return ListTile(contentPadding:EdgeInsets.zero,
   title:Text('${supportLabel(j['op'])} · ${j['state']}',style:const TextStyle(fontWeight:FontWeight.w700)),
   subtitle:SelectableText('${p['subject']??p['body']??j['filename']??jsonSummary(p)}${p['description']==null?'':'\n${p['description']}'}${j['error']==null?'':'\n${j['error']}'}'),
   trailing:IconButton(tooltip:'Remove local entry',onPressed:j['state']=='sending'?null:()async{
    final yes=await showDialog<bool>(context:context,builder:(c)=>AlertDialog(title:const Text('Remove saved entry?'),content:const Text('Removing this entry does not undo anything already received by the server. Copy any draft text you need 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)try{await service.discard('${j['key']}');}catch(e){if(context.mounted)supportSnack(context,e);}
   },icon:const Icon(Icons.close)),);}),),
 ])),actions:[TextButton(onPressed:()=>Navigator.pop(context),child:const Text('Close')),FilledButton.icon(onPressed:()=>service.sync(force:true),icon:const Icon(Icons.sync),label:const Text('Send pending'))]);});
 String jsonSummary(SupportJson p)=>p.entries.map((e)=>'${supportLabel(e.key)}: ${e.value}').join('\n');
}
