import 'dart:async';
import 'package:flutter/material.dart';
import 'package:file_saver/file_saver.dart';
import '../../../../core/services/it_support_service.dart';
import 'it_support_widgets.dart';

class ITTicketDetail extends StatefulWidget {
 final ITSupportService service;final int ticketId;final bool manager;
 const ITTicketDetail({super.key,required this.service,required this.ticketId,required this.manager});
 @override State<ITTicketDetail> createState()=>_ITTicketDetailState();
}
class _ITTicketDetailState extends State<ITTicketDetail> {
 SupportJson _ticket={};List<SupportJson> _watchers=[],_files=[],_activity=[];
 final _message=TextEditingController();Timer? _draftTimer;
 bool _reading=false,_sending=false,_attaching=false,_more=false;int _offset=0;String _kind='messages',_draftState='Private draft';String? _error;
 ITSupportService get s=>widget.service;
 String get draftKey=>'message:${widget.ticketId}';
 @override void initState(){super.initState();_message.text='${s.draft(draftKey)['body']??''}';s.addListener(_changed);_load();}
 @override void dispose(){_draftTimer?.cancel();unawaited(s.saveDraft(draftKey,{'body':_message.text}).catchError((Object _){}));s.removeListener(_changed);_message.dispose();super.dispose();}
 void _changed(){if(mounted&&!_reading&&!s.closed)_load();}
 Future<void> _load({bool force=false,bool more=false})async{
  if(_reading||s.closed)return;_reading=true;
  try{
   final data=await s.read('ticket',{'id':'${widget.ticketId}'},force);
   if(!mounted)return;setState((){_ticket=supportMap(data['ticket']);_watchers=supportRows(data['watchers']);_files=supportRows(data['attachments']);_error=null;});
   final offset=more?_offset:0;
   final page=await s.read('activity',{'id':'${widget.ticketId}','kind':_kind,'offset':'$offset'},force);
   if(!mounted)return;setState((){final rows=supportRows(page['items']);if(!more)_activity=[];_activity.addAll(rows);_offset=offset+rows.length;_more=supportBool(page['has_more']);});
  }catch(e){if(mounted)setState((){_error='$e';if(e is SupportError&&[401,403,404].contains(e.code)){_ticket={};_files=[];_watchers=[];_activity=[];}});}
  finally{_reading=false;}
 }
 Future<void> _draft({bool announce=false})async{
  _draftTimer?.cancel();final text=_message.text;
  try{await s.saveDraft(draftKey,{'body':text});if(mounted)setState(()=>_draftState='Draft saved on this device');if(announce&&mounted)supportSnack(context,'Draft saved.');}
  catch(e){if(mounted)setState(()=>_draftState='Draft could not be saved: $e');}
 }
 Future<void> _send()async{
  if(_sending||_message.text.trim().isEmpty)return;
  if(supportInt(_ticket['assignee_id'])==0){await _draft();if(mounted)supportSnack(context,'Draft saved. Wait for the manager to assign this ticket.');return;}
  _draftTimer?.cancel();setState(()=>_sending=true);
  try{await s.queue('message',{'ticket_id':widget.ticketId,'recipient_id':supportInt(_ticket['assignee_id']),'body':_message.text.trim()},clearDraft:draftKey);if(mounted){_message.clear();setState(()=>_draftState='Message saved to outbox');supportSnack(context,'Message queued for the assignee. Watchers receive an update after delivery.');}}
  catch(e){if(mounted)supportSnack(context,e);}finally{if(mounted)setState(()=>_sending=false);}
 }
 Future<void> _attach()async{
  if(_attaching)return;setState(()=>_attaching=true);
  try{final file=await pickSupportFile();if(file!=null){await s.queue('attach',{'ticket_id':widget.ticketId},file:file);if(mounted)supportSnack(context,'Attachment saved to outbox.');}}
  catch(e){if(mounted)supportSnack(context,e);}finally{if(mounted)setState(()=>_attaching=false);}
 }
 Future<void> _download(SupportJson file)async{
  try{
   final bytes=await s.download(file);final filename='${file['filename']}';final dot=filename.lastIndexOf('.');
   final path=await FileSaver.instance.saveFile(name:dot>0?filename.substring(0,dot):filename,bytes:bytes,fileExtension:dot>0?filename.substring(dot+1):'',mimeType:MimeType.other);
   if(mounted)supportSnack(context,'Attachment saved${path.isEmpty?'':': $path'}');
  }catch(e){if(mounted)supportSnack(context,e);}
 }
 Future<void> _assign({bool watchersOnly=false})async{
  await showDialog<void>(context:context,builder:(_)=>SupportAccountGuard(service:s,child:_AssignmentDialog(service:s,ticket:_ticket,watchers:_watchers,watchersOnly:watchersOnly)));
 }
 Future<void> _progress()async{
  await showDialog<void>(context:context,builder:(_)=>SupportAccountGuard(service:s,child:_ProgressDialog(service:s,ticket:_ticket,manager:widget.manager)));
 }
 @override Widget build(BuildContext context)=>Dialog(insetPadding:const EdgeInsets.all(12),backgroundColor:const Color(0xFFF5F8F6),shape:const RoundedRectangleBorder(borderRadius:BorderRadius.zero),child:SizedBox(width:MediaQuery.sizeOf(context).width<1024?MediaQuery.sizeOf(context).width-24:1000,height:MediaQuery.sizeOf(context).height*.9,child:Column(children:[
  Padding(padding:const EdgeInsets.fromLTRB(18,12,8,8),child:Row(children:[const Icon(Icons.confirmation_number_outlined,color:supportGreen),const SizedBox(width:10),Expanded(child:Text('Ticket #${widget.ticketId}',style:const TextStyle(fontWeight:FontWeight.w800,fontSize:17,color:supportInk))),IconButton(tooltip:'Refresh ticket',onPressed:()=>_load(force:true),icon:const Icon(Icons.refresh,color:supportGreen)),IconButton(tooltip:'Outbox',onPressed:()=>showSupportOutbox(context,s),icon:const Icon(Icons.outbox_outlined)),IconButton(tooltip:'Close window',onPressed:()async{await _draft();if(context.mounted)Navigator.pop(context);},icon:const Icon(Icons.close))])),
  if(_error!=null)Padding(padding:const EdgeInsets.all(12),child:Text(_error!,style:const TextStyle(color:Colors.deepOrange))),
  Expanded(child:_ticket.isEmpty?Center(child:Text(_error??'Opening saved ticket…')):ListView(padding:const EdgeInsets.fromLTRB(18,4,18,20),children:[
   _panel(Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
    SelectableText('${_ticket['subject']}',style:const TextStyle(fontSize:20,fontWeight:FontWeight.w800,color:supportInk)),const SizedBox(height:10),
    Wrap(spacing:8,runSpacing:8,children:[SupportBadge(supportLabel(_ticket['status'])),SupportBadge('${_ticket['tracker']}',color:supportGold),SupportBadge(supportLabel(_ticket['priority']),color:_ticket['priority']=='urgent'?Colors.red:supportGold)]),const SizedBox(height:14),
    SelectableText('${_ticket['description']}',style:const TextStyle(fontSize:14,height:1.5,color:supportInk)),const SizedBox(height:16),
    Wrap(spacing:22,runSpacing:12,children:[_meta('Campus','${_ticket['campus']}'),_meta('Reported by','${_ticket['reporter']}'),_meta('Assigned to','${_ticket['assignee']??'Awaiting manager'}'),_meta('Assigned by','${_ticket['assigner']??'—'}'),_meta('Due date','${_ticket['due_date']??'Not set'}')]),
    const SizedBox(height:16),Row(children:[Expanded(child:LinearProgressIndicator(value:supportInt(_ticket['percent'])/100,minHeight:6,color:supportGreen,backgroundColor:const Color(0xFFE8F0EB))),const SizedBox(width:12),Text('${_ticket['percent']}% complete',style:const TextStyle(fontWeight:FontWeight.w700,color:supportGreen,fontSize:12))]),
    if('${_ticket['resolution']??''}'.isNotEmpty)...[const SizedBox(height:12),const Text('Resolution',style:TextStyle(fontWeight:FontWeight.w800)),SelectableText('${_ticket['resolution']}')],
    const SizedBox(height:12),Wrap(spacing:8,runSpacing:8,children:[
     if(supportBool(_ticket['can_assign'])&&_ticket['status']!='closed')FilledButton.icon(onPressed:()=>_assign(),icon:const Icon(Icons.assignment_ind_outlined,size:18),label:const Text('Assign task')),
     if(supportBool(_ticket['can_progress'])&&(_ticket['status']!='closed'||widget.manager))OutlinedButton.icon(onPressed:_progress,icon:const Icon(Icons.trending_up,size:18),label:Text(_ticket['status']=='closed'?'Reopen ticket':'Update progress')),
    ]),
   ])),const SizedBox(height:12),
   _panel(Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Row(children:[const Expanded(child:Text('Watchers',style:TextStyle(fontWeight:FontWeight.w800,color:supportInk))),if(supportBool(_ticket['can_watch']))TextButton.icon(onPressed:()=>_assign(watchersOnly:true),icon:const Icon(Icons.person_add_alt,size:17),label:const Text('Manage'))]),
    if(_watchers.isEmpty)const Text('The assigner can add people who should follow this ticket.',style:TextStyle(color:Color(0xFF748279),fontSize:12)),
    Wrap(spacing:8,runSpacing:8,children:[for(final w in _watchers)Chip(avatar:const Icon(Icons.visibility_outlined,size:16),label:Text('${w['name']}'))]),
   ])),const SizedBox(height:12),
   _panel(Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Row(children:[const Expanded(child:Text('Attachments · up to 5 MB each',style:TextStyle(fontWeight:FontWeight.w800,color:supportInk))),if(_ticket['status']!='closed')IconButton(tooltip:'Attach file',onPressed:_attaching?null:_attach,icon:const Icon(Icons.attach_file,color:supportGreen))]),
    if(_files.isEmpty)const Text('Attach screenshots, documents or logs.',style:TextStyle(fontSize:12,color:Color(0xFF748279))),
    for(final f in _files)ListTile(dense:true,contentPadding:EdgeInsets.zero,leading:const Icon(Icons.description_outlined,color:supportGold),title:Text('${f['filename']}'),subtitle:Text('${(supportInt(f['size_bytes'])/1024).toStringAsFixed(0)} KB'),trailing:IconButton(tooltip:'Download',onPressed:()=>_download(f),icon:const Icon(Icons.download_outlined))),
   ])),const SizedBox(height:12),
   _panel(Column(crossAxisAlignment:CrossAxisAlignment.start,children:[const Text('Draft a message',style:TextStyle(fontWeight:FontWeight.w800,color:supportInk)),const SizedBox(height:4),Text('To: ${_ticket['assignee']??'Awaiting assignment'} · shared with ticket participants',style:const TextStyle(fontSize:11,color:Color(0xFF748279))),const SizedBox(height:10),
    TextField(controller:_message,enabled:!_sending,minLines:3,maxLines:8,maxLength:20000,decoration:supportInput('Message to assignee'),onChanged:(_){setState(()=>_draftState='Saving draft…');_draftTimer?.cancel();_draftTimer=Timer(const Duration(milliseconds:600),_draft);}),
    Wrap(spacing:10,runSpacing:8,crossAxisAlignment:WrapCrossAlignment.center,children:[Text(_draftState,style:const TextStyle(fontSize:11,color:Color(0xFF748279))),TextButton(onPressed:_sending?null:()=>_draft(announce:true),child:const Text('Save draft')),FilledButton.icon(onPressed:_sending?null:_send,icon:const Icon(Icons.send_outlined,size:17),label:Text(_sending?'Saving…':'Send to assignee'))]),
   ])),const SizedBox(height:12),
   _panel(Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Wrap(spacing:8,children:[for(final k in ['messages','events'])ChoiceChip(label:Text(k=='messages'?'Conversation':'Activity history'),selected:_kind==k,onSelected:_reading?null:(_){setState((){_kind=k;_activity=[];});_load();})]),const SizedBox(height:10),
    if(_activity.isEmpty)const Padding(padding:EdgeInsets.all(10),child:Text('No activity to display.')),
    for(final a in _activity)Padding(padding:const EdgeInsets.symmetric(vertical:8),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text('${a['author']} · ${a['created_at']}',style:const TextStyle(fontWeight:FontWeight.w700,fontSize:11,color:supportGreen)),const SizedBox(height:4),SelectableText(_kind=='messages'?'${a['body']}':'${supportLabel(a['action'])}\n${a['details']}',style:const TextStyle(fontSize:13,height:1.4))])),
    if(_more)TextButton(onPressed:()=>_load(more:true),child:const Text('Load older entries')),
   ])),
  ])),
 ])));
 Widget _panel(Widget child)=>Container(padding:const EdgeInsets.all(16),decoration:BoxDecoration(color:Colors.white,borderRadius:BorderRadius.circular(13),border:Border.all(color:supportBorder)),child:child);
 Widget _meta(String title,String value)=>Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text(title,style:const TextStyle(fontSize:10,color:Color(0xFF748279))),const SizedBox(height:3),Text(value,style:const TextStyle(fontSize:12,fontWeight:FontWeight.w600,color:supportInk))]);
}
class _AssignmentDialog extends StatefulWidget {
 final ITSupportService service;final SupportJson ticket;final List<SupportJson> watchers;final bool watchersOnly;
 const _AssignmentDialog({required this.service,required this.ticket,required this.watchers,required this.watchersOnly});
 @override State<_AssignmentDialog> createState()=>_AssignmentDialogState();
}
class _AssignmentDialogState extends State<_AssignmentDialog> {
 late List<SupportJson> _watchers;SupportJson? _assignee;late TextEditingController _due;bool _saving=false;
 @override void initState(){super.initState();_watchers=List.of(widget.watchers);if(widget.ticket['assignee_id']!=null)_assignee={'id':widget.ticket['assignee_id'],'name':widget.ticket['assignee']};_due=TextEditingController(text:'${widget.ticket['due_date']??''}');}
 @override void dispose(){_due.dispose();super.dispose();}
 Future<void> _person(bool assigned)async{final u=await chooseSupportUser(context,widget.service,technician:assigned);if(u==null||!mounted)return;setState((){if(assigned){_assignee=u;}else if(!_watchers.any((w)=>supportInt(w['id'])==supportInt(u['id']))){_watchers.add(u);}});}
 Future<void> _save()async{
  if(_saving)return;if(!widget.watchersOnly&&(_assignee==null||_watchers.isEmpty)){supportSnack(context,'Select an assignee and at least one watcher.');return;}
  setState(()=>_saving=true);
  try{await widget.service.queue(widget.watchersOnly?'watchers':'assign',{'ticket_id':supportInt(widget.ticket['id']),'version':supportInt(widget.ticket['version']),'watchers':_watchers.map((w)=>supportInt(w['id'])).toList(),if(!widget.watchersOnly)...{'assignee_id':supportInt(_assignee!['id']),'due_date':_due.text.trim()}});if(mounted){supportSnack(context,'Assignment changes saved to outbox.');Navigator.pop(context);}}
  catch(e){if(mounted)supportSnack(context,e);}finally{if(mounted)setState(()=>_saving=false);}
 }
 @override Widget build(BuildContext context)=>AlertDialog(title:Text(widget.watchersOnly?'Manage watchers':'Assign ticket'),content:SizedBox(width:520,child:SingleChildScrollView(child:Column(mainAxisSize:MainAxisSize.min,crossAxisAlignment:CrossAxisAlignment.start,children:[
  if(!widget.watchersOnly)...[OutlinedButton.icon(onPressed:()=>_person(true),icon:const Icon(Icons.person_outline),label:Text('${_assignee?['name']??'Choose IT technician'}')),const SizedBox(height:12),TextField(controller:_due,decoration:supportInput('Due date (YYYY-MM-DD, optional)')),const SizedBox(height:16)],
  const Text('Watchers',style:TextStyle(fontWeight:FontWeight.w800)),const Text('Watchers can read this ticket and receive updates.',style:TextStyle(fontSize:12)),const SizedBox(height:8),
  Wrap(spacing:8,children:[for(final w in _watchers)InputChip(label:Text('${w['name']}'),onDeleted:()=>setState(()=>_watchers.remove(w)))]),TextButton.icon(onPressed:_watchers.length>=30?null:()=>_person(false),icon:const Icon(Icons.person_add_alt),label:const Text('Add watcher')),
 ]))),actions:[TextButton(onPressed:_saving?null:()=>Navigator.pop(context),child:const Text('Cancel')),FilledButton(onPressed:_saving?null:_save,child:const Text('Save changes'))]);
}
class _ProgressDialog extends StatefulWidget {
 final ITSupportService service;final SupportJson ticket;final bool manager;
 const _ProgressDialog({required this.service,required this.ticket,required this.manager});
 @override State<_ProgressDialog> createState()=>_ProgressDialogState();
}
class _ProgressDialogState extends State<_ProgressDialog> {
 late int _percent;late String _status;late TextEditingController _resolution;bool _saving=false;
 bool get reopening=>widget.ticket['status']=='closed';
 @override void initState(){super.initState();_percent=reopening?90:supportInt(widget.ticket['percent']);_status=['in_progress','waiting','resolved'].contains(widget.ticket['status'])?'${widget.ticket['status']}':'in_progress';_resolution=TextEditingController(text:'${widget.ticket['resolution']??''}');}
 @override void dispose(){_resolution.dispose();super.dispose();}
 Future<void> _save()async{
  if(_saving)return;if(['closed','resolved'].contains(_status)&&_percent!=100){supportSnack(context,'Choose 100% to resolve or close the ticket.');return;}if(_status=='closed'&&_resolution.text.trim().isEmpty){supportSnack(context,'Describe how the ticket was fulfilled.');return;}
  setState(()=>_saving=true);try{await widget.service.queue('progress',{'ticket_id':supportInt(widget.ticket['id']),'version':supportInt(widget.ticket['version']),'percent':_percent,'status':_status,'resolution':_resolution.text.trim()});if(mounted){supportSnack(context,'Progress update saved to outbox.');Navigator.pop(context);}}catch(e){if(mounted)supportSnack(context,e);}finally{if(mounted)setState(()=>_saving=false);}
 }
 @override Widget build(BuildContext context)=>AlertDialog(title:Text(reopening?'Reopen ticket':'Update ticket progress'),content:SizedBox(width:480,child:SingleChildScrollView(child:Column(mainAxisSize:MainAxisSize.min,children:[
  DropdownButtonFormField<int>(value:_percent,decoration:supportInput('Percentage completed'),items:[for(var i=0;i<=100;i+=10)DropdownMenuItem(value:i,child:Text('$i%'))],onChanged:(v)=>setState(()=>_percent=v!)),const SizedBox(height:14),
  DropdownButtonFormField<String>(value:_status,decoration:supportInput('Status'),items:[for(final st in reopening?['in_progress']:['in_progress','waiting','resolved','closed'])DropdownMenuItem(value:st,child:Text(st=='closed'?'Fulfilled — close ticket':supportLabel(st)))],onChanged:(v)=>setState(()=>_status=v!)),const SizedBox(height:14),
  TextField(controller:_resolution,minLines:3,maxLines:7,maxLength:10000,decoration:supportInput('Resolution / progress notes')),
  const Text('Closing requires 100% progress and a resolution note.',style:TextStyle(fontSize:12,color:Color(0xFF748279))),
 ]))),actions:[TextButton(onPressed:_saving?null:()=>Navigator.pop(context),child:const Text('Cancel')),FilledButton(onPressed:_saving?null:_save,child:Text(_status=='closed'?'Close fulfilled ticket':'Save progress'))]);
}
