// lib/features/admin/widgets/user_card.dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import '../../../../core/constants/app_colors.dart';

class UserCard extends StatefulWidget {
  final dynamic user;

  const UserCard({super.key, required this.user});

  @override
  State<UserCard> createState() => _UserCardState();
}

class _UserCardState extends State<UserCard> {
  bool _isLoadingProfile = false;

  ImageProvider _getImageProvider(String? imageString) {
    if (imageString == null || imageString.trim().isEmpty) {
      return const AssetImage('assets/images/default_avatar.png'); 
    }
    if (imageString.startsWith('http://') || imageString.startsWith('https://')) {
      return NetworkImage(imageString);
    } else if (imageString.startsWith('/data') || imageString.startsWith('C:\\') || imageString.startsWith('storage')) {
      final file = File(imageString);
      if (file.existsSync()) return FileImage(file);
    } else {
      try {
        String cleanBase64 = imageString;
        if (cleanBase64.contains(',')) cleanBase64 = cleanBase64.split(',').last;
        cleanBase64 = cleanBase64.replaceAll(RegExp(r'\s+'), '');
        return MemoryImage(base64Decode(cleanBase64));
      } catch (_) {}
    }
    return const AssetImage('assets/images/default_avatar.png');
  }

  Future<void> _handleViewProfile(
    String name, String role, String program, String campus, 
    String studentId, String admissionYear, String email, String phone, 
    ImageProvider avatarImage
  ) async {
    setState(() => _isLoadingProfile = true);
    await Future.delayed(const Duration(milliseconds: 400));
    
    if (!mounted) return;
    setState(() => _isLoadingProfile = false);

    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: 'Close Profile',
      barrierColor: (const Color.fromARGB(255, 78, 170, 98)).withOpacity(0.85),
      transitionDuration: const Duration(milliseconds: 350),
      pageBuilder: (context, animation, secondaryAnimation) {
        return Center(
          child: Material(
            color: Colors.transparent,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24.0),
              child: _buildBackCard(
                name, role, program, campus, studentId, admissionYear, email, phone, avatarImage, context
              ),
            ),
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return FadeTransition(
          opacity: animation,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.9, end: 1.0).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeOutCubic)
            ),
            child: child,
          ),
        );
      },
    );
  }

  Widget _buildQuickInfo(IconData icon, String text) {
    return Row(
      children: [
        Icon(icon, size: 16, color: Colors.grey.shade500),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              fontSize: 13,
              color: Colors.grey.shade700,
              fontWeight: FontWeight.w500,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  Widget _buildDetailRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 20, color: Colors.grey.shade500),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey.shade500,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBackCard(
    String name, String role, String program, String campus, 
    String studentId, String admissionYear, String email, String phone, 
    ImageProvider avatarImage, BuildContext dialogContext
  ) {
    return Container(
      constraints: const BoxConstraints(maxWidth: 450, maxHeight: 550), 
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.zero, // SHARP CORNERS
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            blurRadius: 30,
            offset: const Offset(0, 10),
          )
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.zero, // SHARP CORNERS
        child: Stack(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.fromLTRB(20, 40, 20, 24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Center(
                    child: Container(
                      width: 84,
                      height: 84,
                      decoration: BoxDecoration(
                        color: AppColors.brandBlue.withOpacity(0.1) ?? Colors.blue.withOpacity(0.1),
                        shape: BoxShape.rectangle, // SHARP CORNERS
                        image: DecorationImage(
                          image: avatarImage,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    name,
                    style: const TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.w900,
                      color: Color(0xFF1A1F36),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 6),
                  Text(
                    role.toUpperCase(),
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w700,
                      color: AppColors.brandGreen ?? Colors.green,
                      letterSpacing: 0.8,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  
                  const SizedBox(height: 28),
                  
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.grey.shade50,
                      borderRadius: BorderRadius.zero, // SHARP CORNERS
                      border: Border.all(color: Colors.grey.shade200),
                    ),
                    child: Column(
                      children: [
                        _buildDetailRow(Icons.badge_outlined, 'Student ID', studentId),
                        const Divider(height: 1, indent: 16, endIndent: 16),
                        _buildDetailRow(Icons.school_outlined, 'Program', program),
                        const Divider(height: 1, indent: 16, endIndent: 16),
                        _buildDetailRow(Icons.account_balance_outlined, 'Campus', campus),
                        const Divider(height: 1, indent: 16, endIndent: 16),
                        _buildDetailRow(Icons.calendar_month_outlined, 'Enrollment', admissionYear),
                        const Divider(height: 1, indent: 16, endIndent: 16),
                        _buildDetailRow(Icons.email_outlined, 'Email', email),
                        const Divider(height: 1, indent: 16, endIndent: 16),
                        _buildDetailRow(Icons.phone_outlined, 'Phone', phone),
                      ],
                    ),
                  ),
                  const SizedBox(height: 24),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () {},
                          icon: const Icon(Icons.chat_bubble_rounded, size: 18),
                          label: const Text('Message', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.brandBlue ?? Colors.blue,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 14),
                            elevation: 0,
                            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // SHARP CORNERS
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () {},
                          icon: const Icon(Icons.phone_rounded, size: 18),
                          label: const Text('Call', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.brandGreen ?? Colors.green,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 14),
                            elevation: 0,
                            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // SHARP CORNERS
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Positioned(
              top: 12,
              right: 12,
              child: Material(
                color: Colors.grey.shade100,
                shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // SHARP CORNERS
                child: IconButton(
                  icon: const Icon(Icons.close_rounded, size: 22),
                  color: Colors.grey.shade700,
                  onPressed: () => Navigator.of(dialogContext).pop(),
                  tooltip: 'Close Profile',
                  constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
                  padding: EdgeInsets.zero,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final String name = widget.user['name'] ?? widget.user['full_name'] ?? 'Unknown User';
    final String role = widget.user['role'] ?? 'Student';
    final String program = widget.user['program'] ?? 'Computer Science & Information Technology';
    final String campus = widget.user['campus'] ?? 'Rockview University, Ndola Campus';
    final String email = widget.user['email'] ?? 'No academic email on file';
    final String phone = widget.user['phone'] ?? 'Contact restricted';
    final String studentId = widget.user['student_id'] ?? widget.user['id']?.toString() ?? 'N/A';
    final String admissionYear = widget.user['admission_year'] ?? 'Ongoing';
    final ImageProvider avatarImage = _getImageProvider(widget.user['profile_picture'] ?? widget.user['image']);

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.zero, // SHARP CORNERS
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 10,
            offset: const Offset(0, 4),
          )
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 56,
                height: 56,
                decoration: BoxDecoration(
                  color: AppColors.brandBlue.withOpacity(0.1) ?? Colors.blue.withOpacity(0.1),
                  shape: BoxShape.rectangle, // SHARP CORNERS
                  image: DecorationImage(
                    image: avatarImage,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name,
                      style: const TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.w800,
                        color: Color(0xFF1A1F36),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      role.toUpperCase(),
                      style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w700,
                        color: AppColors.brandGreen ?? Colors.green,
                        letterSpacing: 0.5,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: BorderRadius.zero, // SHARP CORNERS
              border: Border.all(color: Colors.grey.shade100),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildQuickInfo(Icons.school_outlined, program),
                const SizedBox(height: 8),
                _buildQuickInfo(Icons.account_balance_outlined, campus),
              ],
            ),
          ),
          
          const SizedBox(height: 16),
          
          Row(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  shape: BoxShape.rectangle, // SHARP CORNERS
                ),
                child: IconButton(
                  icon: const Icon(Icons.chat_bubble_outline_rounded, size: 20),
                  color: AppColors.brandBlue ?? Colors.blue,
                  onPressed: () {},
                ),
              ),
              const SizedBox(width: 12),
              Container(
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  shape: BoxShape.rectangle, // SHARP CORNERS
                ),
                child: IconButton(
                  icon: const Icon(Icons.phone_outlined, size: 20),
                  color: AppColors.brandGreen ?? Colors.green,
                  onPressed: () {},
                ),
              ),
              const Spacer(),
              ElevatedButton(
                onPressed: _isLoadingProfile 
                    ? null 
                    : () => _handleViewProfile(name, role, program, campus, studentId, admissionYear, email, phone, avatarImage),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.brandBlue ?? Colors.blue,
                  foregroundColor: Colors.white,
                  disabledBackgroundColor: (AppColors.brandBlue ?? Colors.blue).withOpacity(0.7),
                  elevation: 0,
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero, // SHARP CORNERS
                  ),
                ),
                child: _isLoadingProfile 
                  ? const SizedBox(
                      width: 16, 
                      height: 16, 
                      child: CircularProgressIndicator(
                        color: Colors.white, 
                        strokeWidth: 2.5
                      )
                    )
                  : const Text(
                      'View Profile',
                      style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700),
                    ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}