import 'package:flutter/material.dart';

import '../../../../../../core/services/cv_service.dart';
import 'my_cv_tab.dart';

/// Admin CV browser. Selecting a person changes only this panel's content;
/// it never opens a route, full-screen page, or modal window.
class EmployeeCvTab extends StatefulWidget {
  const EmployeeCvTab({super.key});
  @override
  State<EmployeeCvTab> createState() => _EmployeeCvTabState();
}

class _EmployeeCvTabState extends State<EmployeeCvTab> {
  bool _loading = true;
  String? _error;
  String _search = '';
  List<Map<String, dynamic>> _people = [];
  Map<String, dynamic>? _selected;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() { super.initState(); CvService.offlineRevision.addListener(_onOfflineRevision); _load(); }
  @override
  void dispose() { CvService.offlineRevision.removeListener(_onOfflineRevision); _searchController.dispose(); super.dispose(); }

  void _onOfflineRevision() {
    if (!mounted) return;
    final selected = _selected;
    if (selected != null) {
      _openEmployee({'user_id': selected['user_id']});
    } else {
      _load(search: _search);
    }
  }

  Future<void> _load({String? search, bool refresh = false}) async {
    if (search != null) _search = search;
    setState(() { _loading = _people.isEmpty; _error = null; });
    try {
      final rows = await CvService.directory(search: _search, refresh: refresh);
      if (!mounted) return;
      setState(() { _people = rows; _loading = false; });
    } catch (e) {
      if (!mounted) return;
      setState(() { _error = CvService.cleanError(e); _loading = false; });
    }
  }

  Future<void> _searchDirectory(String value) async {
    _search = value;
    try {
      final rows = await CvService.directory(search: value);
      if (!mounted) return;
      setState(() { _people = rows; _error = null; });
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = CvService.cleanError(e));
    }
  }

  Future<void> _openEmployee(Map<String, dynamic> row, {bool refresh = false}) async {
    final id = int.tryParse('${row['user_id'] ?? 0}') ?? 0;
    if (id <= 0) return;
    setState(() { _loading = _selected == null; _error = null; });
    try {
      final cv = await CvService.getCv(id, refresh: refresh);
      if (!mounted) return;
      setState(() { _selected = cv; _loading = false; });
    } catch (e) {
      if (!mounted) return;
      setState(() { _loading = false; if (_selected == null) _error = CvService.cleanError(e); });
    }
  }

  void _backToDirectory() => setState(() { _selected = null; _error = null; });

  @override
  Widget build(BuildContext context) {
    final selected = _selected;
    return Column(children: [
      _EmployeeHeader(
        detail: selected != null,
        subtitle: selected == null
            ? 'Browse professional profiles for staff and administrators'
            : '${selected['campus'] ?? 'Campus not specified'}  •  ${selected['role'] ?? 'Staff'}',
        onBack: _backToDirectory,
        onRefresh: () => selected == null ? _load(refresh: true) : _openEmployee({'user_id': selected['user_id']}, refresh: true),
      ),
      Expanded(child: _loading
          ? const Center(child: CircularProgressIndicator(color: cvGreen))
          : _error != null
              ? _EmployeeError(message: _error!, onRetry: () => selected == null ? _load() : _openEmployee({'user_id': selected['user_id']}))
              : selected != null
                  ? _employeeDocument(selected)
                  : _directory()),
    ]);
  }

  Widget _employeeDocument(Map<String, dynamic> cv) => LayoutBuilder(builder: (context, box) => SingleChildScrollView(padding: EdgeInsets.all(box.maxWidth < 500 ? 10 : 20), child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 820), child: Column(children: [if (cv['_offline_cached'] == true) _OfflineEmployeeBanner(), if (cv['_offline_cached'] == true) const SizedBox(height: 12), StaffCvDocument(cv: cv), const SizedBox(height: 10), _CvChangeHistory(history: cv['change_history'])])))));

  Widget _directory() => Column(children: [
    Padding(padding: const EdgeInsets.fromLTRB(18, 18, 18, 12), child: LayoutBuilder(builder: (context, box) {
      final intro = Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        const Text('EMPLOYEE CV DIRECTORY', style: TextStyle(color: cvGreen, fontSize: 21, fontWeight: FontWeight.w900, letterSpacing: .4)),
        const SizedBox(height: 4),
        Text('${_people.length} staff and administrator profiles', style: const TextStyle(color: cvMuted)),
      ]);
      final search = TextField(
        controller: _searchController,
        onChanged: _searchDirectory,
        decoration: InputDecoration(
          hintText: 'Search name, email, campus or staff ID',
          prefixIcon: const Icon(Icons.search_rounded, color: cvGreen),
          filled: true, fillColor: Colors.white,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(9), borderSide: const BorderSide(color: cvLine)),
          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(9), borderSide: const BorderSide(color: cvLine)),
        ),
      );
      if (box.maxWidth < 720) return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [intro, const SizedBox(height: 12), search]);
      return Row(children: [Expanded(child: intro), const SizedBox(width: 18), SizedBox(width: 370, child: search)]);
    })),
    Expanded(child: _people.isEmpty
        ? const Center(child: Text('No staff CVs were found.', style: TextStyle(color: cvMuted)))
        : LayoutBuilder(builder: (context, box) {
            final columns = box.maxWidth > 1100 ? 3 : box.maxWidth > 680 ? 2 : 1;
            return GridView.builder(
              padding: const EdgeInsets.fromLTRB(18, 2, 18, 22),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: columns, crossAxisSpacing: 14, mainAxisSpacing: 14, mainAxisExtent: (270 * MediaQuery.textScalerOf(context).scale(1)).clamp(270.0, 380.0).toDouble()),
              itemCount: _people.length,
              itemBuilder: (context, index) => _EmployeeCard(row: _people[index], onTap: () => _openEmployee(_people[index])),
            );
          })),
  ]);
}

/// Admin-only change history returned with the employee CV detail response.
class _CvChangeHistory extends StatelessWidget {
  final dynamic history;
  const _CvChangeHistory({required this.history});

  @override
  Widget build(BuildContext context) {
    final rows = history is List ? history.whereType<Map>().map((row) => row.map((key, value) => MapEntry(key.toString(), value))).toList() : <Map<String, dynamic>>[];
    return Container(width: double.infinity, padding: const EdgeInsets.all(18), decoration: BoxDecoration(color: Colors.white, border: Border.all(color: cvLine), borderRadius: BorderRadius.circular(13)), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Row(children: [Icon(Icons.history_rounded, color: cvGreen), SizedBox(width: 9), Expanded(child: Text('CV CHANGE HISTORY', style: TextStyle(color: cvInk, fontWeight: FontWeight.w900, letterSpacing: .4)))]),
      const SizedBox(height: 12),
      if (rows.isEmpty) const Text('No CV changes have been recorded yet.', style: TextStyle(color: cvMuted)),
      for (final row in rows) Padding(padding: const EdgeInsets.only(bottom: 11), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        const Padding(padding: EdgeInsets.only(top: 4), child: Icon(Icons.circle, size: 8, color: cvGold)),
        const SizedBox(width: 10),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('${row['changed_by_name'] ?? 'Employee'} updated the CV', style: const TextStyle(color: cvInk, fontWeight: FontWeight.w700)),
          const SizedBox(height: 3),
          Text('${row['changed_sections'] ?? 'CV details'}', style: const TextStyle(color: cvMuted)),
          const SizedBox(height: 3),
          Text('${row['changed_at'] ?? ''}', style: const TextStyle(color: cvMuted, fontSize: 11)),
        ])),
      ])),
    ]));
  }
}

class _EmployeeHeader extends StatelessWidget {
  final bool detail;
  final String subtitle;
  final VoidCallback onBack, onRefresh;
  const _EmployeeHeader({required this.detail, required this.subtitle, required this.onBack, required this.onRefresh});
  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.fromLTRB(20, 16, 16, 16),
    decoration: const BoxDecoration(color: cvGreen, border: Border(bottom: BorderSide(color: cvGold, width: 3))),
    child: Row(children: [
      if (detail) IconButton(onPressed: onBack, tooltip: 'Back to employee CVs', icon: const Icon(Icons.arrow_back_rounded, color: Colors.white)),
      Container(width: 42, height: 42, decoration: BoxDecoration(color: Colors.white.withOpacity(.14), borderRadius: BorderRadius.circular(10)), child: Icon(detail ? Icons.description_outlined : Icons.groups_rounded, color: Colors.white)),
      const SizedBox(width: 12),
      Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(detail ? 'EMPLOYEE CURRICULUM VITAE' : 'EMPLOYEE CVs', style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w900, letterSpacing: .45)),
        const SizedBox(height: 3), Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFFD9EEE1), fontSize: 12)),
      ])),
      IconButton(onPressed: onRefresh, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: Colors.white)),
    ]),
  );
}

class _EmployeeCard extends StatelessWidget {
  final Map<String, dynamic> row;
  final VoidCallback onTap;
  const _EmployeeCard({required this.row, required this.onTap});
  @override
  Widget build(BuildContext context) {
    final name = '${row['full_name'] ?? 'Staff member'}';
    final image = '${row['account_photo'] ?? ''}';
    final role = '${row['role'] ?? 'Staff'}';
    final title = '${row['professional_title'] ?? ''}';
    final campus = '${row['campus'] ?? 'Campus not specified'}';
    final school = '${row['program'] ?? ''}';
    final hasCv = row['updated_at'] != null;
    return Material(color: Colors.white, child: InkWell(onTap: onTap, child: Container(
      decoration: BoxDecoration(border: Border.all(color: cvLine), boxShadow: const [BoxShadow(color: Color(0x0B000000), blurRadius: 8, offset: Offset(0, 3))]),
      child: Column(children: [
        Container(height: 5, color: cvGreen),
        Expanded(child: Padding(padding: const EdgeInsets.fromLTRB(16, 15, 16, 8), child: Column(children: [
          _EmployeePhoto(url: image, name: name),
          const SizedBox(height: 9),
          Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: const TextStyle(color: cvInk, fontSize: 16, fontWeight: FontWeight.w900)),
          const SizedBox(height: 5),
          Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), color: const Color(0xFFE8F3ED), child: Text(role.toUpperCase(), style: const TextStyle(color: cvGreen, fontSize: 10, fontWeight: FontWeight.w900, letterSpacing: .8))),
          const SizedBox(height: 9),
          Text(title.isEmpty ? (school.isEmpty ? campus : school) : title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: cvMuted, fontSize: 12)),
          const SizedBox(height: 4),
          Text(campus, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: cvMuted, fontSize: 11)),
        ]))),
        const Divider(height: 1, color: cvLine),
        SizedBox(height: 44, child: TextButton.icon(onPressed: onTap, icon: const Icon(Icons.visibility_outlined, size: 17), label: Text(hasCv ? 'VIEW EMPLOYEE CV' : 'VIEW PROFILE'), style: TextButton.styleFrom(foregroundColor: cvGreen, textStyle: const TextStyle(fontSize: 11, fontWeight: FontWeight.w900, letterSpacing: .4)))),
      ]),
    )));
  }
}

class _EmployeePhoto extends StatelessWidget {
  final String url, name;
  const _EmployeePhoto({required this.url, required this.name});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.all(3), decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: cvGold, width: 2)), child: CircleAvatar(radius: 32, backgroundColor: const Color(0xFFE8F3ED), backgroundImage: url.isEmpty ? null : NetworkImage(url), onBackgroundImageError: url.isEmpty ? null : (_, __) {}, child: url.isEmpty ? Text(name.isEmpty ? '?' : name[0].toUpperCase(), style: const TextStyle(color: cvGreen, fontSize: 22, fontWeight: FontWeight.w900)) : null));
}


class _OfflineEmployeeBanner extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Container(width: double.infinity, padding: const EdgeInsets.all(11), decoration: BoxDecoration(color: const Color(0xFFFFF5E6), border: Border.all(color: const Color(0xFFEBCB98)), borderRadius: BorderRadius.circular(9)), child: const Row(children: [Icon(Icons.cloud_off_rounded, color: cvGold, size: 18), SizedBox(width: 8), Expanded(child: Text('Showing the last CV copy saved on this device.', style: TextStyle(color: cvInk, fontSize: 12)))]));
}

class _EmployeeError extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _EmployeeError({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) => Center(child: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [const Icon(Icons.info_outline_rounded, color: cvGold, size: 36), const SizedBox(height: 10), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: cvInk)), const SizedBox(height: 12), OutlinedButton.icon(onPressed: onRetry, icon: const Icon(Icons.refresh_rounded), label: const Text('TRY AGAIN'))])));
}
