/*// lib/features/admin/tabs/admin_about_campuses_tab.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../core/constants/app_colors.dart';
import '../../../core/networks/api_client.dart'; 

class AdminAboutCampusesTab extends StatefulWidget {
  const AdminAboutCampusesTab({super.key});

  @override
  State<AdminAboutCampusesTab> createState() => _AdminAboutCampusesTabState();
}

class _AdminAboutCampusesTabState extends State<AdminAboutCampusesTab> {
  // Form Controllers for Create Tab
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _contactController = TextEditingController();
  final _registrarController = TextEditingController();
  final _descriptionController = TextEditingController();
  
  // Image Picker State (Using XFile instead of Base64)
  XFile? _selectedImage;
  final ImagePicker _picker = ImagePicker();
  
  bool _isMainCampus = false;
  bool _isSubmitting = false;
  
  // API State
  bool _isLoadingData = true;
  List<dynamic> campuses = [];
  final ApiClient _apiClient = ApiClient(); 

  @override
  void initState() {
    super.initState();
    _loadCampuses();
  }

  // --- API Methods ---
  Future<void> _loadCampuses() async {
    setState(() => _isLoadingData = true);
    try {
      final fetchedCampuses = await ApiClient.getCampuses();
      setState(() {
        campuses = fetchedCampuses;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load campuses: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoadingData = false);
      }
    }
  }

  Future<void> _pickImage() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 70, // Compresses image to save DB space
      );
      
      if (pickedFile != null) {
        setState(() {
          _selectedImage = pickedFile;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error picking image: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isSubmitting = true);

      final newCampusData = {
        "name": _nameController.text,
        "address": _addressController.text,
        "contact_number": _contactController.text,
        "registrar": _registrarController.text,
        "description": _descriptionController.text,
        "is_main_campus": _isMainCampus,
      };

      try {
        // Pass the file directly to the API Client
        await ApiClient.createCampus(
          newCampusData, 
          imageFile: _selectedImage != null ? File(_selectedImage!.path) : null
        );
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Campus successfully added!'), backgroundColor: AppColors.brandGreen),
          );
        }
        
        // Clear form
        _nameController.clear();
        _addressController.clear();
        _contactController.clear();
        _registrarController.clear();
        _descriptionController.clear();
        setState(() {
          _isMainCampus = false;
          _selectedImage = null;
        });

        _loadCampuses();
        
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Error saving campus: $e'), backgroundColor: Colors.red),
          );
        }
      } finally {
        if (mounted) setState(() => _isSubmitting = false);
      }
    }
  }

  // --- EDIT DIALOG METHOD ---
  Future<void> _showEditDialog(dynamic campus) async {
    final editNameCtrl = TextEditingController(text: campus['name']);
    final editAddressCtrl = TextEditingController(text: campus['address']);
    final editContactCtrl = TextEditingController(text: campus['contact_number']);
    final editRegistrarCtrl = TextEditingController(text: campus['registrar']);
    final editDescCtrl = TextEditingController(text: campus['description']);
    
    bool editIsMain = campus['is_main_campus'] ?? false;
    String? existingBannerUrl = campus['banner_url']; 
    XFile? newEditImage;
    final editFormKey = GlobalKey<FormState>();
    bool isUpdating = false;

    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setStateDialog) {
            return AlertDialog(
              title: const Text('Edit Campus Details', style: TextStyle(fontWeight: FontWeight.bold)),
              content: SizedBox(
                width: 600,
                child: SingleChildScrollView(
                  child: Form(
                    key: editFormKey,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        TextFormField(
                          controller: editNameCtrl,
                          decoration: const InputDecoration(labelText: 'Campus Name', border: OutlineInputBorder()),
                          validator: (v) => v!.isEmpty ? 'Required' : null,
                        ),
                        const SizedBox(height: 16),
                        
                        // Image Picker for Edit Mode
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade400),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Column(
                            children: [
                              // Show Newly Selected File OR Existing Server Image
                              if (newEditImage != null)
                                Padding(
                                  padding: const EdgeInsets.only(bottom: 16),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child: Image.file(File(newEditImage!.path), height: 120, width: double.infinity, fit: BoxFit.cover),
                                  ),
                                )
                              else if (existingBannerUrl != null && existingBannerUrl.isNotEmpty)
                                Padding(
                                  padding: const EdgeInsets.only(bottom: 16),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child: _buildImageWidget(existingBannerUrl, height: 120),
                                  ),
                                ),
                              OutlinedButton.icon(
                                onPressed: () async {
                                  final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 70);
                                  if (pickedFile != null) {
                                    setStateDialog(() {
                                      newEditImage = pickedFile;
                                    });
                                  }
                                },
                                icon: const Icon(Icons.image),
                                label: const Text('Upload New Banner Image'),
                              ),
                            ],
                          ),
                        ),
                        
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                controller: editRegistrarCtrl,
                                decoration: const InputDecoration(labelText: 'Registrar Name', border: OutlineInputBorder()),
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: TextFormField(
                                controller: editContactCtrl,
                                decoration: const InputDecoration(labelText: 'Contact Number', border: OutlineInputBorder()),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          controller: editAddressCtrl,
                          decoration: const InputDecoration(labelText: 'Physical Address', border: OutlineInputBorder()),
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          controller: editDescCtrl,
                          maxLines: 3,
                          decoration: const InputDecoration(labelText: 'Campus Description', border: OutlineInputBorder()),
                        ),
                        const SizedBox(height: 16),
                        SwitchListTile(
                          title: const Text('Set as Main Campus'),
                          value: editIsMain,
                          activeThumbColor: AppColors.brandGreen,
                          onChanged: (val) => setStateDialog(() => editIsMain = val),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              actions: [
                TextButton(
                  onPressed: isUpdating ? null : () => Navigator.pop(context),
                  child: const Text('Cancel', style: TextStyle(color: Colors.grey)),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: AppColors.brandBlue, foregroundColor: Colors.white),
                  onPressed: isUpdating
                      ? null
                      : () async {
                          if (editFormKey.currentState!.validate()) {
                            setStateDialog(() => isUpdating = true);
                            try {
                              final updateData = {
                                "name": editNameCtrl.text,
                                "address": editAddressCtrl.text,
                                "contact_number": editContactCtrl.text,
                                "registrar": editRegistrarCtrl.text,
                                "description": editDescCtrl.text,
                                "is_main_campus": editIsMain,
                              };
                              
                              await ApiClient.updateCampus(
                                campus['id'], 
                                updateData,
                                imageFile: newEditImage != null ? File(newEditImage!.path) : null
                              );
                              
                              if (mounted) {
                                Navigator.pop(context);
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(content: Text('Campus updated!'), backgroundColor: AppColors.brandGreen),
                                );
                                _loadCampuses();
                              }
                            } catch (e) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(content: Text('Update failed: $e'), backgroundColor: Colors.red),
                              );
                              setStateDialog(() => isUpdating = false);
                            }
                          }
                        },
                  child: isUpdating 
                      ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                      : const Text('Save Changes'),
                ),
              ],
            );
          }
        );
      }
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _addressController.dispose();
    _contactController.dispose();
    _registrarController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: Colors.grey.shade50,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          toolbarHeight: 0, 
          bottom: const TabBar(
            labelColor: AppColors.brandBlue,
            unselectedLabelColor: Colors.grey,
            indicatorColor: AppColors.brandBlue,
            indicatorWeight: 3,
            tabs: [
              Tab(icon: Icon(Icons.business), text: 'Manage Campuses'),
              Tab(icon: Icon(Icons.add_location_alt), text: 'Add New Campus'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            _buildCampusesList(),
            _buildCreateCampusForm(),
          ],
        ),
      ),
    );
  }

  // --- HELPER TO DISPLAY NETWORK URL SAFELY ---
  Widget _buildImageWidget(String imageString, {double? height}) {
    // If backend returns relative path like "/static/campuses/file.jpg", prepend base URL
    String fullUrl = imageString;
    if (imageString.startsWith('/')) {
      fullUrl = '${ApiClient.baseUrl}$imageString';
    }

    return Image.network(
      fullUrl,
      height: height,
      width: double.infinity,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) => Container(
        height: height ?? 120,
        width: double.infinity,
        color: Colors.grey.shade200,
        child: const Icon(Icons.broken_image, color: Colors.grey, size: 50),
      ),
    );
  }

  // --- VIEW & EDIT TAB ---
  Widget _buildCampusesList() {
    if (_isLoadingData) {
      return const Center(child: CircularProgressIndicator(color: AppColors.brandBlue));
    }

    if (campuses.isEmpty) {
      return const Center(
        child: Text('No campuses found. Add one to get started!', style: TextStyle(color: Colors.grey, fontSize: 16)),
      );
    }

    return Center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 1000),
        child: ListView.builder(
          padding: const EdgeInsets.all(24),
          itemCount: campuses.length,
          itemBuilder: (context, index) {
            final campus = campuses[index];
            final bool isMain = campus['is_main_campus'] ?? false;
            final String? bannerUrl = campus['banner_url'];

            return Card(
              elevation: 3,
              margin: const EdgeInsets.only(bottom: 24),
              clipBehavior: Clip.antiAlias,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
                side: isMain ? const BorderSide(color: AppColors.brandGreen, width: 2) : BorderSide.none,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // --- CAMPUS BANNER ---
                  if (bannerUrl != null && bannerUrl.isNotEmpty)
                    _buildImageWidget(bannerUrl, height: 200)
                  else
                    Container(
                      height: 120,
                      width: double.infinity,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [AppColors.brandBlue.withOpacity(0.7), AppColors.brandBlue],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                      ),
                      child: const Center(child: Icon(Icons.account_balance, color: Colors.white54, size: 60)),
                    ),
                  
                  // --- CAMPUS DETAILS ---
                  Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Text(
                                campus['name'] ?? 'Unnamed Campus',
                                style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 22, letterSpacing: 0.5),
                              ),
                            ),
                            if (isMain)
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                    color: AppColors.brandGreen.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(20)),
                                child: const Text('MAIN CAMPUS',
                                    style: TextStyle(color: AppColors.brandGreen, fontWeight: FontWeight.bold, fontSize: 12)),
                              )
                          ],
                        ),
                        const SizedBox(height: 16),
                        
                        if (campus['description'] != null && campus['description'].toString().isNotEmpty) ...[
                          Text(
                            campus['description'],
                            style: TextStyle(color: Colors.grey.shade800, fontSize: 15, height: 1.5),
                          ),
                          const SizedBox(height: 24),
                        ],

                        Wrap(
                          spacing: 32,
                          runSpacing: 16,
                          children: [
                            _buildInfoRow(Icons.person, 'Registrar:', campus['registrar'] ?? 'Not Assigned'),
                            _buildInfoRow(Icons.phone, 'Contact:', campus['contact_number'] ?? 'No contact'),
                            _buildInfoRow(Icons.location_on, 'Address:', campus['address'] ?? 'No address'),
                          ],
                        ),
                        
                        const Padding(padding: EdgeInsets.symmetric(vertical: 16), child: Divider()),
                        
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            OutlinedButton.icon(
                              onPressed: () => _showEditDialog(campus),
                              icon: const Icon(Icons.edit, size: 18),
                              label: const Text('Edit Details'),
                              style: OutlinedButton.styleFrom(foregroundColor: AppColors.brandBlue),
                            ),
                            const SizedBox(width: 12),
                            if (!isMain)
                              ElevatedButton.icon(
                                onPressed: () async {
                                  try {
                                    await ApiClient.deleteCampus(campus['id']);
                                    _loadCampuses(); 
                                  } catch (e) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red),
                                    );
                                  }
                                },
                                icon: const Icon(Icons.delete, size: 18),
                                label: const Text('Remove'),
                                style: ElevatedButton.styleFrom(backgroundColor: Colors.red.shade600, foregroundColor: Colors.white),
                              ),
                          ],
                        )
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, color: Colors.grey, size: 20),
        const SizedBox(width: 8),
        Text(label, style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.grey)),
        const SizedBox(width: 4),
        Flexible(child: Text(value, style: const TextStyle(fontSize: 15))),
      ],
    );
  }

  // --- CREATE TAB ---
  Widget _buildCreateCampusForm() {
    return Center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 800),
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24.0),
          child: Card(
            elevation: 2,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
            child: Padding(
              padding: const EdgeInsets.all(32.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('Register New Campus', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    const Text('Enter the details below to add a new campus to the university network.', style: TextStyle(color: Colors.grey)),
                    const SizedBox(height: 32),
                    
                    Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: TextFormField(
                            controller: _nameController,
                            validator: (value) => value!.isEmpty ? 'Required' : null,
                            decoration: const InputDecoration(labelText: 'Campus Name', border: OutlineInputBorder(), prefixIcon: Icon(Icons.business)),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          flex: 1,
                          child: TextFormField(
                            controller: _contactController,
                            decoration: const InputDecoration(labelText: 'Contact Number', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone)),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),

                    TextFormField(
                      controller: _registrarController,
                      decoration: const InputDecoration(labelText: 'Campus Registrar Name', border: OutlineInputBorder(), prefixIcon: Icon(Icons.person)),
                    ),
                    const SizedBox(height: 24),

                    // --- NEW IMAGE PICKER SECTION ---
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey.shade400),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text('Campus Banner Image', style: TextStyle(color: Colors.grey, fontSize: 16)),
                          const SizedBox(height: 12),
                          if (_selectedImage != null) 
                            Padding(
                              padding: const EdgeInsets.only(bottom: 16),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: Image.file(File(_selectedImage!.path), height: 150, width: double.infinity, fit: BoxFit.cover),
                              ),
                            ),
                          Center(
                            child: OutlinedButton.icon(
                              onPressed: _pickImage,
                              icon: const Icon(Icons.upload_file),
                              label: Text(_selectedImage == null ? 'Select Image from Gallery' : 'Choose a Different Image'),
                            ),
                          )
                        ],
                      ),
                    ),
                    const SizedBox(height: 24),
                    // -------------------------------

                    TextFormField(
                      controller: _addressController,
                      maxLines: 2,
                      decoration: const InputDecoration(labelText: 'Physical Address', border: OutlineInputBorder(), prefixIcon: Icon(Icons.location_on)),
                    ),
                    const SizedBox(height: 24),

                    TextFormField(
                      controller: _descriptionController,
                      maxLines: 4,
                      decoration: const InputDecoration(
                        labelText: 'Campus Description / Info', 
                        alignLabelWithHint: true,
                        border: OutlineInputBorder(), 
                      ),
                    ),
                    const SizedBox(height: 24),

                    SwitchListTile(
                      title: const Text('Set as Main Campus', style: TextStyle(fontWeight: FontWeight.bold)),
                      subtitle: const Text('This will identify this location as the primary headquarters.'),
                      value: _isMainCampus,
                      onChanged: (bool value) => setState(() => _isMainCampus = value),
                      activeThumbColor: AppColors.brandGreen,
                      contentPadding: EdgeInsets.zero,
                    ),
                    const SizedBox(height: 32),

                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColors.brandBlue,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                        ),
                        onPressed: _isSubmitting ? null : _submitForm,
                        child: _isSubmitting 
                            ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                            : const Text('Save Campus', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}*/