import 'dart:async';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../../../../core/services/file_management_service.dart';
import '../../../../core/services/file_model.dart';

const _green = Color(0xFF026930);
const _ink = Color(0xFF24362C);
const _muted = Color(0xFF6F7C74);
const _line = Color(0xFFDFE7E1);

class FilesMainTab extends StatefulWidget {
  const FilesMainTab({super.key});
  @override State<FilesMainTab> createState() => _FilesMainTabState();
}
class _FilesMainTabState extends State<FilesMainTab> with WidgetsBindingObserver {
  FileManagementService? _service;
  Timer? _timer;
  Timer? _searchTimer;
  bool _refreshing = false;
  bool _loading = false;
  String _query = '';
  String _sort = 'title';
  final _search = TextEditingController();
  String? _error;
  String _campus = 'All campuses';
  int _tab = 3;
  bool _headerExpanded = false;
  int? _folderId;
  bool _creatingFolder = false;
  Map<String,dynamic>? _folderDetails;
  String? _folderError;
  bool _folderLoading = false;
  bool _membersExpanded = true;
  final Set<int> _respondingInvites = {};
  bool _choosing = false;
  @override void initState() {super.initState();WidgetsBinding.instance.addObserver(this);_load();}
  // Keep one service and one refresh in flight for this screen.
  Future<void> _load() async {
    if (_loading) return;
    _loading = true;
    if (mounted) setState(() => _error = null);
    try {
      final service = await FileManagementService.open();
      if (!mounted) { service.dispose(); return; }
      _service = service;
      service.addListener(_changed);
      setState(() {});
      await _refresh();
      _startTimer();
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      _loading = false;
    }
  }

  void _startTimer() {
    if (!mounted || WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) return;
    _timer ??= Timer.periodic(const Duration(seconds: 60), (_) => _refresh());
  }

  void _changed() { if (mounted) setState(() {}); }

  Future<void> _refresh() async {
    final service = _service;
    if (!mounted || service == null || _refreshing) return;
    setState(() => _refreshing = true);
    try {
      await service.sync();
      if (!mounted) return;
      await service.drainQueue();
      if(mounted && _folderId!=null)await _loadFolderDetails(_folderId!);
      if (mounted) setState(() => _error = null);
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _refreshing = false);
    }
  }

  void _searchChanged(String value) {
    _searchTimer?.cancel();
    _searchTimer = Timer(const Duration(milliseconds: 250), () {
      if (mounted) setState(() => _query = value.trim().toLowerCase());
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _refresh();
      _startTimer();
    } else {
      _timer?.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _searchTimer?.cancel();
    WidgetsBinding.instance.removeObserver(this);
    _search.dispose();
    _service?.removeListener(_changed);
    _service?.dispose();
    super.dispose();
  }
  void _message(String message){if(mounted)ScaffoldMessenger.of(context).showSnackBar(SnackBar(content:Text(message)));}
  Future<void> _run(Future<void> Function() action) async {try{await action();}catch(e){_message(e.toString());}}
  Future<bool> _confirm(String title,String text) async => await showDialog<bool>(
    context:context,builder:(context)=>AlertDialog(title:Text(title),content:Text(text),actions:[
      TextButton(onPressed:()=>Navigator.pop(context,false),child:const Text('Cancel')),
      FilledButton(onPressed:()=>Navigator.pop(context,true),child:const Text('Continue')),
    ]))??false;
  Future<void> _upload({ManagedFile? replacing, int? folderId}) async {
    if(_choosing)return;setState(()=>_choosing=true);
    try{
      // file_picker 13.1.0: static single-file API.
      final file = await FilePicker.pickFile(
        type: FileType.custom,
        allowedExtensions: const [
          'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
          'txt', 'csv', 'png', 'jpg', 'jpeg',
        ],
      );
      if (file == null || !mounted) return;
      final fileSize = await file.length();
      if (!mounted) return;
      if (fileSize == null) {
        throw StateError('Cannot determine this file’s size. Save it locally and select it again.');
      }
      if (fileSize <= 0) throw StateError('The selected file is empty.');
      if (fileSize > FileManagementService.maxFileBytes) {
        throw StateError('Maximum file size is 25 MB.');
      }
      final controller=TextEditingController(text:replacing?.title??file.name);
      String? title;
      try{
        title=await showDialog<String>(context:context,builder:(dialogContext)=>AlertDialog(
          title:Text(replacing!=null?'Upload a new version':folderId!=null?'Upload to folder':'Upload document'),
          content:SizedBox(width:380,child:Column(mainAxisSize:MainAxisSize.min,crossAxisAlignment:CrossAxisAlignment.start,children:[
            Text('${file.name} · ${formatFileBytes(fileSize)}',style:const TextStyle(color:_muted,fontSize:12)),
            const SizedBox(height:16),
            TextField(controller:controller,maxLength:150,decoration:const InputDecoration(labelText:'Document title',border:OutlineInputBorder())),
            const SizedBox(height:10),
            Text(folderId!=null?'This document inherits this folder’s access. Accepted members, executives and campus registrars can read it. Public folders are visible to all staff.':replacing==null?'Executive offices can view this document. Your campus registrar and existing authorised offices can also view it.':'Existing readers keep access. The previous version remains saved until the new upload finishes.',style:const TextStyle(color:_muted,fontSize:12)),
          ])),actions:[
            TextButton(onPressed:()=>Navigator.pop(dialogContext),child:const Text('Cancel')),
            FilledButton(onPressed:(){if(controller.text.trim().isNotEmpty)Navigator.pop(dialogContext,controller.text.trim());},child:const Text('Add to upload queue')),
          ]));
      }finally{controller.dispose();}
      if(title==null||!mounted)return;
      // Read bytes only after the user confirms the upload.
      final bytes = await file.readAsBytes();
      if (!mounted) return;
      if (bytes.isEmpty || bytes.length > FileManagementService.maxFileBytes) {
        throw StateError('Choose a non-empty file no larger than 25 MB.');
      }
      await _service!.queueUpload(file.name,title,bytes,replacing:replacing,folderId:folderId);
    }catch(e){_message(e.toString());}finally{if(mounted)setState(()=>_choosing=false);}
  }
  Widget _statusChip(String text,IconData icon,Color color)=>Container(
    padding:const EdgeInsets.symmetric(horizontal:9,vertical:5),
    decoration:BoxDecoration(color:color.withOpacity(.07),border:Border.all(color:color.withOpacity(.2)),borderRadius:BorderRadius.circular(20)),
    child:Row(mainAxisSize:MainAxisSize.min,children:[Icon(icon,size:13,color:color),const SizedBox(width:5),Text(text,style:TextStyle(color:color,fontSize:11,fontWeight:FontWeight.w600))]),
  );
  @override Widget build(BuildContext context){
    final s=_service;
    if(s==null)return Center(child:_error==null?const CircularProgressIndicator():Column(mainAxisSize:MainAxisSize.min,children:[
      Text(_error!,textAlign:TextAlign.center),const SizedBox(height:12),FilledButton(onPressed:_load,child:const Text('Retry'))]));
    final all=s.hasValidLease?s.files:<ManagedFile>[];
    final campuses=<String>{...all.map((f)=>f.campus),...s.publicFolders.map((f)=>'${f['campus'] ?? ''}')}.where((c)=>c.isNotEmpty).toList()..sort();
    final selectedCampus=campuses.contains(_campus)?_campus:'All campuses';
    final query=_query;
    final folderIds=s.fileFolderIds;
    final folders=s.publicFolders;
    final selectedFolders=folders.where((f)=>f['id']==_folderId).toList();
    final selectedFolder=selectedFolders.isEmpty?null:selectedFolders.first;
    final folderRoot=_tab==4&&selectedFolder==null;
    final canUpload=_tab!=5&&(_tab!=4||(selectedFolder?['can_upload']==true));
    final rows=all.where((f){
      final scope=_tab==5?false:_tab==4?selectedFolder!=null&&folderIds[f.id]==_folderId:_tab==0?f.canEdit:_tab==1?!f.canEdit:_tab==2?s.cached(f)!=null:true;
      return scope&&(selectedCampus=='All campuses'||f.campus==selectedCampus)&&'${f.title} ${f.filename} ${f.owner} ${f.campus}'.toLowerCase().contains(query);
    }).toList();
    rows.sort((a, b) {
      if (_sort == 'size') return b.size.compareTo(a.size);
      if (_sort == 'owner') return a.owner.toLowerCase().compareTo(b.owner.toLowerCase());
      return a.title.toLowerCase().compareTo(b.title.toLowerCase());
    });
    final grouped=<String,List<ManagedFile>>{};
    for(final f in rows){grouped.putIfAbsent(f.campus.isEmpty?'Campus not assigned':f.campus,()=>[]).add(f);}
    final groupNames=grouped.keys.toList()..sort();
    final entries=<Object>[for(final campus in groupNames)...[campus,...grouped[campus]!]];
    if(folderRoot) {
      entries.addAll(folders.where((f)=>(selectedCampus=='All campuses'||f['campus']==selectedCampus)&&'${f['name']} ${f['owner_name']} ${f['owner_role']} ${f['description']}'.toLowerCase().contains(query)));
    }
    if(_tab==5)entries.addAll(s.folderInvitations);
    final folderHeader=_tab==4&&selectedFolder!=null;
    return Scaffold(backgroundColor:const Color(0xFFF4F7F5),body:SafeArea(child:Column(children:[
      // The compact toolbar remains available when the large header is hidden.
      Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        child: Row(children: [
          const Icon(Icons.folder_copy_outlined, color: _green, size: 20),
          const SizedBox(width: 8),
          const Expanded(child: Text('University Documents', maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: _ink, fontSize: 15, fontWeight: FontWeight.w700))),
          IconButton(tooltip: 'Refresh file list', onPressed: _refreshing ? null : _refresh,
            icon: const Icon(Icons.sync, color: _green)),
          IconButton(
            tooltip: _headerExpanded ? 'Collapse header and filters' : 'Show header and filters',
            onPressed: () => setState(() => _headerExpanded = !_headerExpanded),
            icon: Icon(_headerExpanded ? Icons.unfold_less : Icons.unfold_more, color: _green),
          ),
          PopupMenuButton<String>(tooltip: 'Offline storage', onSelected: (_) async {
            if (await _confirm('Clear saved downloads?', 'Uploaded server files and queued uploads will remain.')) {
              await _run(s.clearDownloads);
            }
          }, itemBuilder: (_) => [const PopupMenuItem(value: 'clear', child: Text('Clear saved downloads'))]),
        ]),
      ),
      if (_headerExpanded) ...[
        Container(width: double.infinity, color: Colors.white,
          padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            const Text('ROCKVIEW UNIVERSITY', style: TextStyle(color: _green, fontSize: 16, fontWeight: FontWeight.w800)),
            const SizedBox(height: 4),
            const Text('Official Document Management', style: TextStyle(color: _ink, fontSize: 14)),
            const SizedBox(height: 8),
            Text(s.canCreatePublicFolder ? 'Executive access · All campuses, including HR offices'
                : s.profile['role']=='registrar' ? 'Registrar access · All documents from your campus'
                : 'Staff access · Your documents and authorised shared files',
              style: const TextStyle(color: _muted, fontSize: 12)),
            const SizedBox(height: 8),
            Text(s.status, style: const TextStyle(color: _muted, fontSize: 12)),
          ]),
        ),
      Padding(padding:const EdgeInsets.fromLTRB(16,14,16,8),child:LayoutBuilder(builder:(context,c){
        final search=TextField(controller:_search,onChanged:_searchChanged,decoration:InputDecoration(
          hintText:'Search title, filename, staff or campus',prefixIcon:const Icon(Icons.search,color:_green),filled:true,fillColor:Colors.white,
          border:OutlineInputBorder(borderRadius:BorderRadius.circular(10),borderSide:const BorderSide(color:_line)),
          suffixIcon:query.isEmpty?null:IconButton(onPressed:(){_searchTimer?.cancel();_search.clear();setState(()=>_query='');},icon:const Icon(Icons.close)),
        ));
        final campus=DropdownButtonFormField<String>(value:selectedCampus,isExpanded:true,decoration:const InputDecoration(labelText:'Campus',border:OutlineInputBorder(),filled:true,fillColor:Colors.white),
          items:['All campuses',...campuses].map((v)=>DropdownMenuItem(value:v,child:Text(v,overflow:TextOverflow.ellipsis))).toList(),onChanged:(v)=>setState(()=>_campus=v??'All campuses'));
        if(c.maxWidth<620)return Column(children:[search,const SizedBox(height:10),campus]);
        return Row(children:[Expanded(child:search),const SizedBox(width:12),SizedBox(width:240,child:campus)]);
      })),
      ],
      Padding(padding:const EdgeInsets.symmetric(horizontal:16,vertical:8),child:Row(children:[
        Expanded(child:SingleChildScrollView(scrollDirection:Axis.horizontal,child:Row(children:List.generate(6,(i)=>Padding(
          padding:const EdgeInsets.only(right:7),child:ChoiceChip(label:Text(['My Files','Shared with Me','Saved Offline','All Accessible','Folders','Invitations (${s.folderInvitations.length})'][i]),selected:_tab==i,onSelected:(_)=>setState((){_tab=i;_folderId=null;_folderDetails=null;_folderError=null;})),
        ))))),
        const SizedBox(width:8),FilledButton.icon(onPressed:_choosing||!s.hasValidLease||!canUpload?null:()=>_upload(folderId:_tab==4?_folderId:null),icon:const Icon(Icons.upload_file,size:18),label:const Text('Upload'),style:FilledButton.styleFrom(backgroundColor:_green)),
      ])),
      if (_tab==4) Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Row(children: [
          if (selectedFolder!=null) IconButton(tooltip:'Back to public folders',
            onPressed:()=>setState(()=>_folderId=null),icon:const Icon(Icons.arrow_back)),
          Expanded(child: Text(selectedFolder==null?'Official staff folders':'${selectedFolder['name']}',
            maxLines:1,overflow:TextOverflow.ellipsis,
            style:const TextStyle(color:_green,fontWeight:FontWeight.w700))),
          if (s.canCreateFolder) TextButton.icon(
            onPressed:_creatingFolder?null:()=>_createFolder(s),
            icon:const Icon(Icons.create_new_folder_outlined,size:18),label:const Text('New folder')),
        ]),
      ),
      if (!_headerExpanded && (query.isNotEmpty||selectedCampus!='All campuses')) Padding(
        padding:const EdgeInsets.symmetric(horizontal:16),
        child:Row(children:[
          const Expanded(child:Text('Search or campus filter is active',style:TextStyle(color:_muted,fontSize:12))),
          TextButton(onPressed:(){_searchTimer?.cancel();_search.clear();setState((){_query='';_campus='All campuses';});},child:const Text('Clear filters')),
        ]),
      ),
      Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Row(children: [
          Expanded(child: Text(_tab==5?'${entries.length} pending invitations':folderRoot?'${entries.length} folders': '${rows.length} documents · ${formatFileBytes(rows.fold<int>(0, (total, f) => total + f.size))}',
            style: const TextStyle(color: _muted, fontSize: 12))),
          PopupMenuButton<String>(
            tooltip: 'Sort documents within each campus',
            initialValue: _sort,
            onSelected: (value) => setState(() => _sort = value),
            itemBuilder: (_) => const [
              PopupMenuItem(value: 'title', child: Text('Title: A–Z')),
              PopupMenuItem(value: 'owner', child: Text('Owner: A–Z')),
              PopupMenuItem(value: 'size', child: Text('Largest first')),
            ],
            icon: const Icon(Icons.sort, color: _green),
          ),
        ]),
      ),
      if (_refreshing) const LinearProgressIndicator(minHeight: 2, color: _green),
      if (_error != null) Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
        child: Row(children: [
          const Icon(Icons.info_outline, size: 18, color: _muted),
          const SizedBox(width: 8),
          Expanded(child: Text('Refresh failed. $_error', maxLines: 2,
            overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12))),
          TextButton(onPressed: _refreshing ? null : _refresh, child: const Text('Retry')),
        ]),
      ),
      if(s.queue.isNotEmpty)_queue(s),
      Expanded(child:RefreshIndicator(onRefresh:_refresh,child:ListView.builder(
        physics:const AlwaysScrollableScrollPhysics(),padding:const EdgeInsets.fromLTRB(16,8,16,24),
        itemCount:(entries.isEmpty?1:entries.length)+(folderHeader?1:0),
        itemBuilder:(context,index){
          if(folderHeader&&index==0)return _folderInterior(s,selectedFolder!);
          final entryIndex=index-(folderHeader?1:0);
          if(entries.isEmpty)return Padding(padding:const EdgeInsets.all(32),child:Column(children:[
            const Icon(Icons.folder_open_rounded,size:48,color:_muted),const SizedBox(height:12),
            Text(!s.hasValidLease?'Connect to verify your access':query.isNotEmpty?'No matching documents or folders':_tab==5?'No pending invitations':folderRoot?'No folders yet. Create your first folder':'No documents in this section',textAlign:TextAlign.center,style:const TextStyle(color:_muted)),
          ]));
          final entry=entries[entryIndex];
          if(entry is Map<String,dynamic>)return _tab==5?_invitationCard(s,entry):_folderCard(entry);
          if(entry is ManagedFile)return _fileCard(s,entry);
          final campus=entry as String;
          return Container(
            margin:const EdgeInsets.only(top:10,bottom:10),padding:const EdgeInsets.symmetric(vertical:12),
            decoration:const BoxDecoration(border:Border(bottom:BorderSide(color:_line))),
            child:Row(children:[
              const Icon(Icons.location_city_outlined,color:_green,size:18),const SizedBox(width:8),
              Expanded(child:Text(campus.toUpperCase(),style:const TextStyle(color:_green,fontWeight:FontWeight.w800,fontSize:12))),
              Text('${grouped[campus]!.length}',style:const TextStyle(color:_muted)),
            ]),
          );
        },
      ))),
    ])));
  }
  Widget _queue(FileManagementService s)=>Container(
    constraints:const BoxConstraints(maxHeight:180),margin:const EdgeInsets.fromLTRB(16,0,16,8),
    decoration:BoxDecoration(color:const Color(0xFFFFFAEF),border:Border.all(color:const Color(0xFFECD8AF)),borderRadius:BorderRadius.circular(10)),
    child:ListView.builder(shrinkWrap:true,itemCount:s.queue.length,itemBuilder:(context,index){
      final job=s.queue[index];
      final size=(job['size_bytes'] as num?)?.toDouble() ?? 0;
      final offset=(job['offset'] as num?)?.toDouble() ?? 0;
      return ListTile(dense:true,
      leading:const Icon(Icons.cloud_upload_outlined,color:_green),
      title:Text('${job['title']}',maxLines:1,overflow:TextOverflow.ellipsis),
      subtitle:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
        Text('${job['state']}${job['error']==null?'':' · ${job['error']}'}',maxLines:2,overflow:TextOverflow.ellipsis),
        if(job['state']=='Uploading')LinearProgressIndicator(value:size>0?(offset/size).clamp(0.0,1.0).toDouble():null,color:_green),
      ]),trailing:Row(mainAxisSize:MainAxisSize.min,children:[
        IconButton(tooltip:'Retry upload',onPressed:s.isUploading?null:()=>_run(()=>s.retryJob('${job['key']}')),icon:const Icon(Icons.refresh,size:18)),
        IconButton(tooltip:'Remove from queue',onPressed:s.isUploading?null:()=>_run(()=>s.removeJob('${job['key']}')),icon:const Icon(Icons.close,size:18)),
      ]),
    );}),
  );
  Widget _fileCard(FileManagementService s,ManagedFile f){
    final cache=s.cached(f);final upToDate=cache!=null&&cache['sha256']==f.checksum;
    final progress=s.downloadProgress[f.id];
    final busy=progress!=null;
    return Container(key:ValueKey(f.id),margin:const EdgeInsets.only(bottom:6),padding:const EdgeInsets.all(10),decoration:BoxDecoration(color:Colors.white,border:Border.all(color:_line),borderRadius:BorderRadius.circular(12)),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
      Row(crossAxisAlignment:CrossAxisAlignment.start,children:[
        Container(padding:const EdgeInsets.all(10),decoration:BoxDecoration(color:_green.withOpacity(.06),borderRadius:BorderRadius.circular(8)),child:const Icon(Icons.description_outlined,color:_green)),
        const SizedBox(width:12),Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
          Text(f.title,maxLines:2,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_ink,fontSize:14,fontWeight:FontWeight.w700)),const SizedBox(height:4),
          Text('${f.owner} · ${f.filename}',maxLines:1,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_muted,fontSize:11)),const SizedBox(height:3),
          Text('${formatFileBytes(f.size)} · Version ${f.version} · ${f.canEdit?'Can edit':'Read only'}',style:const TextStyle(color:_muted,fontSize:11)),
        ])),
        PopupMenuButton<String>(onSelected:(action)async{
          if(action=='details')await _showDetails(s,f);
          if(action=='replace')await _upload(replacing:f);
          if(action=='saved')await _run(()=>s.openFile(f,savedOnly:true));
          if(action=='access'&&mounted)await showDialog<void>(context:context,builder:(c)=>AlertDialog(title:const Text('Who can access this file'),content:Text(_audienceText(s,f)),actions:[TextButton(onPressed:()=>Navigator.pop(c),child:const Text('Close'))]));
          if(action=='delete'&&await _confirm('Delete this file?','This removes the file from everyone’s accessible list.'))await _run(()=>s.deleteFile(f));
        },itemBuilder:(_)=>[
          const PopupMenuItem(value:'details',child:Text('File details')),
          const PopupMenuItem(value:'access',child:Text('Who can access')),
          if(cache!=null&&!upToDate)PopupMenuItem(value:'saved',child:Text('Open saved version ${cache['version']}')),
          if(f.canEdit)const PopupMenuItem(value:'replace',child:Text('Upload new version')),
          if(f.canEdit)const PopupMenuItem(value:'delete',child:Text('Delete file')),
        ]),
      ]),const SizedBox(height:12),
      Wrap(spacing:10,runSpacing:8,crossAxisAlignment:WrapCrossAlignment.center,children:[
        TextButton.icon(onPressed:()=>_showDetails(s,f),icon:const Icon(Icons.info_outline,size:16),label:const Text('Details')),
        _statusChip(upToDate?'Saved offline':cache!=null?'New version available':'Not downloaded',upToDate?Icons.offline_pin_outlined:Icons.cloud_download_outlined,upToDate?_green:_muted),
        OutlinedButton.icon(onPressed:busy?null:()=>_run(()=>s.openFile(f)),icon:Icon(upToDate?Icons.open_in_new:Icons.download_outlined,size:16),label:Text(busy?'Downloading…':upToDate?'Open':cache!=null?'Update & open':'Download & open')),
      ]),
      if(progress!=null)...[const SizedBox(height:10),LinearProgressIndicator(value:progress,color:_green),const SizedBox(height:3),Text('${(progress*100).round()}%',style:const TextStyle(fontSize:10,color:_muted))],
    ]));
  }
  // Build extended metadata on demand instead of expanding every list row.
  Future<void> _showDetails(FileManagementService s, ManagedFile f) async {
    final cache = s.cached(f);
    final current = cache != null && cache['sha256'] == f.checksum;
    final dot = f.filename.lastIndexOf('.');
    final type = dot < 0 ? 'Unknown' : f.filename.substring(dot + 1).toUpperCase();
    final details = <String, String>{
      'Title': f.title,
      'Filename': f.filename,
      'File type': type,
      'Owner': f.owner,
      'Campus': f.campus.isEmpty ? 'Not assigned' : f.campus,
      'Size': formatFileBytes(f.size),
      'Version': '${f.version}',
      'Your access': f.canEdit ? 'Can edit' : 'Read only',
      'Audience': _audienceText(s,f),
      'Offline copy': current ? 'Current version saved' : cache == null
          ? 'Not downloaded' : 'Saved version ${cache['version']} — update available',
    };
    await showDialog<void>(context: context, builder: (dialogContext) => AlertDialog(
      title: const Text('File details'),
      content: SizedBox(width: 440, child: SingleChildScrollView(
        child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start,
          children: details.entries.map((entry) => Padding(
            padding: const EdgeInsets.only(bottom: 14),
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(entry.key, style: const TextStyle(color: _muted, fontSize: 12)),
              const SizedBox(height: 3),
              SelectableText(entry.value.isEmpty ? 'Not provided' : entry.value,
                style: const TextStyle(color: _ink, fontSize: 14)),
            ]),
          )).toList(),
        ),
      )),
      actions: [TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('Close'))],
    ));
  }

  String _audienceText(FileManagementService s, ManagedFile f) {
    if (s.fileFolderIds.containsKey(f.id)) {
      return 'Access is inherited from the folder. Open Folders to see its members and visibility. Executives and the folder campus registrars have automatic access.';
    }
    return 'Uploader; DVC1, DVC2, CEO, CFO, COO and CAO across all campuses; the registrar of the uploading campus. Additional existing office access: ${f.audience}';
  }

  Widget _folderCard(Map<String,dynamic> folder) => Card(
    elevation:0,color:Colors.white,
    shape:RoundedRectangleBorder(borderRadius:BorderRadius.circular(10),side:const BorderSide(color:_line)),
    child:ListTile(
      contentPadding:const EdgeInsets.symmetric(horizontal:14,vertical:8),
      leading:const Icon(Icons.folder_rounded,color:Color(0xFFF4C044),size:48),
      title:Text('${folder['name']}',maxLines:2,overflow:TextOverflow.ellipsis,
        style:const TextStyle(color:_ink,fontWeight:FontWeight.w800,fontSize:15)),
      subtitle:Text('${folder['owner_name']} · ${folder['campus'] ?? ''}\n'
        '${folder['visibility']=='public'?'Public to all staff':'Members and oversight offices'}',
        maxLines:3,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_muted,fontSize:12)),
      trailing:const Icon(Icons.chevron_right,color:_muted),
      onTap:()=>_openFolder((folder['id'] as num).toInt()),
    ),
  );

  Future<void> _openFolder(int id) async {
    _searchTimer?.cancel();_search.clear();
    setState((){_tab=4;_folderId=id;_query='';_campus='All campuses';_folderDetails=null;_folderError=null;});
    await _loadFolderDetails(id);
  }
  Future<void> _loadFolderDetails(int id) async {
    if(!mounted||_folderId!=id)return;
    setState((){_folderLoading=true;_folderError=null;});
    try {
      final details=await _service!.folderDetails(id);
      if(mounted&&_folderId==id)setState(()=>_folderDetails=details);
    } catch(e) {
      if(mounted&&_folderId==id)setState((){_folderDetails=null;_folderError=e.toString();});
    } finally { if(mounted&&_folderId==id)setState(()=>_folderLoading=false); }
  }
  Widget _folderInterior(FileManagementService s,Map<String,dynamic> folder) {
    final members=(_folderDetails?['members'] as List? ?? []).whereType<Map>().toList();
    final pending=(_folderDetails?['pending'] as List? ?? []).whereType<Map>().toList();
    final id=(folder['id'] as num).toInt();
    return Container(
      margin:const EdgeInsets.only(bottom:14),padding:const EdgeInsets.all(16),
      decoration:BoxDecoration(color:const Color(0xFFFFFCF1),border:Border.all(color:const Color(0xFFEADBAB)),borderRadius:BorderRadius.circular(12)),
      child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
        Row(children:[const Icon(Icons.folder_open_rounded,color:Color(0xFFE5AC25),size:34),const SizedBox(width:10),
          Expanded(child:Text('${folder['name']}',style:const TextStyle(fontWeight:FontWeight.w800,fontSize:19,color:_ink)))]),
        const SizedBox(height:10),
        SelectableText('${folder['description'] ?? ''}'.trim().isEmpty?'No description provided.':'${folder['description']}',
          style:const TextStyle(color:_ink,fontSize:13)),
        const SizedBox(height:8),
        Text('Owner: ${folder['owner_name']} · ${folder['campus'] ?? ''}',style:const TextStyle(color:_muted,fontSize:12)),
        const SizedBox(height:8),
        Text(folder['visibility']=='public'?'Public folder · All staff have read access.'
          :'Invited staff must accept before gaining access. Executives and campus registrars have automatic read access.',
          style:const TextStyle(color:_muted,fontSize:12)),
        Wrap(spacing:8,children:[
          if(folder['can_invite']==true)TextButton.icon(onPressed:()=>_inviteMember(s,id),icon:const Icon(Icons.person_add_alt_1,size:18),label:const Text('Invite people')),
          if(folder['can_delete']==true)TextButton.icon(onPressed:()=>_deleteFolder(s,id),icon:const Icon(Icons.delete_outline,color:Colors.red,size:18),label:const Text('Delete folder',style:TextStyle(color:Colors.red))),
        ]),
        if(_folderLoading)const LinearProgressIndicator(minHeight:2),
        if(_folderError!=null)Row(children:[Expanded(child:Text(_folderError!,style:const TextStyle(color:_muted,fontSize:12))),TextButton(onPressed:()=>_loadFolderDetails(id),child:const Text('Retry'))]),
        if(_folderDetails!=null)...[
          InkWell(onTap:()=>setState(()=>_membersExpanded=!_membersExpanded),child:Padding(
            padding:const EdgeInsets.symmetric(vertical:10),child:Row(children:[
              Expanded(child:Text('People with access (${members.length})',style:const TextStyle(fontWeight:FontWeight.w700))),
              Icon(_membersExpanded?Icons.expand_less:Icons.expand_more),
            ]))),
          if(_membersExpanded)SizedBox(height:(members.length*62.0).clamp(0.0,248.0).toDouble(),
            child:ListView.builder(primary:false,itemCount:members.length,itemBuilder:(context,index){
              final member=members[index];
              return ListTile(dense:true,contentPadding:EdgeInsets.zero,
                leading:const Icon(Icons.person_outline,color:_green),
                title:Text('${member['name']}',maxLines:1,overflow:TextOverflow.ellipsis),
                subtitle:Text('${member['email']} · ${member['role']}\n${member['access_reason']}',maxLines:2,overflow:TextOverflow.ellipsis));
            })),
          if(pending.isNotEmpty)...[
            const SizedBox(height:12),Text('Pending invitations (${pending.length}) — not accepted',style:const TextStyle(fontWeight:FontWeight.w600,fontSize:12)),
            SizedBox(height:(pending.length*48.0).clamp(0.0,144.0).toDouble(),child:ListView.builder(primary:false,itemCount:pending.length,itemBuilder:(c,i)=>ListTile(
              dense:true,contentPadding:EdgeInsets.zero,leading:const Icon(Icons.hourglass_empty,size:18),
              title:Text('${pending[i]['name']} · ${pending[i]['email']}',maxLines:1,overflow:TextOverflow.ellipsis)))),
          ],
        ],
        const SizedBox(height:12),const Text('Documents in this folder',style:TextStyle(fontWeight:FontWeight.w700,color:_green)),
      ]),
    );
  }
  Future<void> _inviteMember(FileManagementService s,int id) async {
    final sent=await showDialog<bool>(context:context,builder:(_)=>_FolderInviteDialog(service:s,folderId:id));
    if(sent==true&&mounted){_message('Invitation sent. The member must accept it in Invitations.');await _loadFolderDetails(id);}
  }
  Future<void> _deleteFolder(FileManagementService s,int id) async {
    if(!await _confirm('Delete this folder?','The folder and all documents inside it will disappear for everyone. Only the owner can delete a folder.'))return;
    await _run(()async{
      await s.deleteFolder(id);
      if(mounted)setState((){_folderId=null;_folderDetails=null;});
    });
  }
  Widget _invitationCard(FileManagementService s,Map<String,dynamic> invitation) {
    final id=(invitation['folder_id'] as num).toInt();final busy=_respondingInvites.contains(id);
    return Card(elevation:0,child:Padding(padding:const EdgeInsets.all(14),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
      Row(children:[const Icon(Icons.folder_rounded,color:Color(0xFFF4C044),size:36),const SizedBox(width:10),
        Expanded(child:Text('${invitation['name']}',style:const TextStyle(fontWeight:FontWeight.w800)))]),
      Text('Invited by ${invitation['owner_name']} · ${invitation['campus']}',style:const TextStyle(color:_muted,fontSize:12)),
      const SizedBox(height:8),
      Wrap(spacing:10,children:[
        FilledButton(onPressed:busy?null:()=>_respondInvite(s,id,true),child:const Text('Accept')),
        TextButton(onPressed:busy?null:()=>_respondInvite(s,id,false),child:const Text('Decline')),
      ]),
    ])));
  }
  Future<void> _respondInvite(FileManagementService s,int id,bool accept) async {
    setState(()=>_respondingInvites.add(id));
    try{await s.respondToFolderInvitation(id,accept);if(mounted)_message(accept?'Invitation accepted. Open Folders to view the documents.':'Invitation declined.');}
    catch(e){_message(e.toString());}
    finally{if(mounted)setState(()=>_respondingInvites.remove(id));}
  }

  Future<void> _createFolder(FileManagementService s) async {
    if (_creatingFolder) return;
    setState(()=>_creatingFolder=true);
    final name=TextEditingController();
    final description=TextEditingController();
    Map<String,String>? input;
    bool public=false;
    try {
      input=await showDialog<Map<String,String>>(context:context,builder:(c)=>StatefulBuilder(builder:(c,setDialogState)=>AlertDialog(
        title:const Text('Create official folder'),
        content:SizedBox(width:420,child:SingleChildScrollView(child:Column(
          mainAxisSize:MainAxisSize.min,crossAxisAlignment:CrossAxisAlignment.start,children:[
          const Text('Invite staff after creating the folder. Executives and registrars of your campus have automatic access. You control invitations, uploads and deletion.'),
          if(s.canCreatePublicFolder)SwitchListTile(contentPadding:EdgeInsets.zero,title:const Text('Public to all staff'),value:public,onChanged:(v)=>setDialogState(()=>public=v)),
          const SizedBox(height:16),
          TextField(controller:name,maxLength:100,decoration:const InputDecoration(labelText:'Folder name',hintText:'e.g. Official Circulars',border:OutlineInputBorder())),
          const SizedBox(height:12),
          TextField(controller:description,maxLength:300,maxLines:3,decoration:const InputDecoration(labelText:'Description (optional)',border:OutlineInputBorder())),
        ]))),
        actions:[
          TextButton(onPressed:()=>Navigator.pop(c),child:const Text('Cancel')),
          FilledButton(onPressed:(){if(name.text.trim().isNotEmpty)Navigator.pop(c,{'name':name.text.trim(),'description':description.text.trim(),'public':public?'true':'false'});},child:const Text('Create folder')),
        ],
      )));
    } finally {
      name.dispose(); description.dispose();
      if(mounted)setState(()=>_creatingFolder=false);
    }
    if (input==null||!mounted) return;
    setState(()=>_creatingFolder=true);
    try {
      await s.createFolder(input['name']!,input['description']!,public:input['public']=='true');
      if (!mounted) return;
      _searchTimer?.cancel(); _search.clear();
      setState((){_tab=4;_folderId=null;_query='';_campus='All campuses';});
      _message('Folder created. Open it to add documents and invite people.');
    } catch(e) { _message(e.toString()); }
    finally { if(mounted)setState(()=>_creatingFolder=false); }
  }

}

// Search is requested only while the invitation dialog is open.
class _FolderInviteDialog extends StatefulWidget {
  final FileManagementService service;
  final int folderId;
  const _FolderInviteDialog({required this.service,required this.folderId});
  @override State<_FolderInviteDialog> createState()=>_FolderInviteDialogState();
}
class _FolderInviteDialogState extends State<_FolderInviteDialog> {
  final _controller=TextEditingController();
  Timer? _debounce;
  int _sequence=0;
  bool _loading=false;
  bool _sending=false;
  String? _error;
  List<Map<String,dynamic>> _people=[];
  Map<String,dynamic>? _selected;
  void _search(String value) {
    _debounce?.cancel();final sequence=++_sequence;
    setState((){_selected=null;_people=[];_error=null;_loading=value.trim().length>=2;});
    if(value.trim().length<2)return;
    _debounce=Timer(const Duration(milliseconds:300),()async{
      try{
        final people=await widget.service.findFolderCandidates(widget.folderId,value.trim());
        if(mounted&&sequence==_sequence)setState(()=>_people=people);
      }catch(e){if(mounted&&sequence==_sequence)setState(()=>_error=e.toString());}
      finally{if(mounted&&sequence==_sequence)setState(()=>_loading=false);}
    });
  }
  Future<void> _send() async {
    final selected=_selected;if(selected==null||_sending)return;
    setState((){_sending=true;_error=null;});
    try{
      await widget.service.inviteToFolder(widget.folderId,(selected['id'] as num).toInt());
      if(mounted)Navigator.pop(context,true);
    }catch(e){if(mounted)setState(()=>_error=e.toString());}
    finally{if(mounted)setState(()=>_sending=false);}
  }
  @override void dispose(){_debounce?.cancel();_controller.dispose();super.dispose();}
  @override Widget build(BuildContext context)=>AlertDialog(
    title:const Text('Invite a staff member'),
    content:SizedBox(width:480,child:SingleChildScrollView(child:Column(mainAxisSize:MainAxisSize.min,crossAxisAlignment:CrossAxisAlignment.start,children:[
      const Text('Search by name or email, then verify the person and campus. Access is granted after acceptance. Automatic oversight and public access remain in place.'),
      const SizedBox(height:12),
      TextField(controller:_controller,enabled:!_sending,onChanged:_search,
        decoration:const InputDecoration(labelText:'Staff name or email',prefixIcon:Icon(Icons.search),border:OutlineInputBorder())),
      if(_loading)const LinearProgressIndicator(minHeight:2),
      if(_error!=null)Padding(padding:const EdgeInsets.only(top:8),child:Text(_error!,style:const TextStyle(color:Colors.red))),
      if(!_loading&&_people.isEmpty&&_controller.text.trim().length>=2&&_error==null)
        const Padding(padding:EdgeInsets.only(top:12),child:Text('No eligible matches. Try another name or email.')),
      SizedBox(height:220,child:ListView.builder(itemCount:_people.length,itemBuilder:(context,index){
        final person=_people[index];
        return ListTile(
          selected:_selected?['id']==person['id'],
          leading:Icon(_selected?['id']==person['id']?Icons.check_circle:Icons.person_outline,color:_green),
          title:Text('${person['name']}',style:const TextStyle(fontWeight:FontWeight.w600)),
          subtitle:Text('${person['email']}\n${person['campus']} · ${person['role']}'),
          isThreeLine:true,onTap:_sending?null:()=>setState(()=>_selected=person),
        );
      })),
      if(_selected!=null)Text('Invite: ${_selected!['name']} (${_selected!['email']})',style:const TextStyle(fontWeight:FontWeight.w600)),
    ]))),
    actions:[
      TextButton(onPressed:_sending?null:()=>Navigator.pop(context,false),child:const Text('Cancel')),
      FilledButton(onPressed:_selected==null||_sending?null:_send,child:Text(_sending?'Sending…':'Send invitation')),
    ],
  );
}
