import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:medora/data/services/patient_registration_service.dart';
import 'package:medora/route/route_names.dart';
import 'package:medora/data/models/patient.dart';

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

  @override
  State<PatientProfileScreen> createState() => _PatientProfileScreenState();
}

class _PatientProfileScreenState extends State<PatientProfileScreen> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  PatientModel? _patientProfile;

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

  Future<void> _fetchPatientProfile() async {
    final patientProfile = await PatientProfileService.getPatientProfile();
    if (mounted) {
      setState(() {
        _patientProfile = patientProfile;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            _buildProfileHeader(),
            _buildProfileOptions(),
          ],
        ),
      ),
    );
  }

  Widget _buildProfileHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Color(0xFF00BCD4),
            Color(0xFF2196F3),
          ],
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
              image: _patientProfile?.profileImageUrl != null
                  ? DecorationImage(
                      image: NetworkImage(_patientProfile!.profileImageUrl!),
                      fit: BoxFit.cover,
                    )
                  : null,
            ),
            child: _patientProfile?.profileImageUrl == null
                ? Center(
                    child: Text(
                      _patientProfile != null && _patientProfile!.name != null
                          ? _patientProfile!.name![0].toUpperCase()
                          : '',
                      style: const TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue,
                      ),
                    ),
                  )
                : null,
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _patientProfile != null && _patientProfile!.name != null
                      ? _patientProfile!.name!
                      : 'Create your profile',
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
          const Icon(
            Icons.chevron_right,
            color: Colors.white,
            size: 30,
          ),
        ],
      ),
    );
  }

  Widget _buildProfileOptions() {
    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
          ),
        ],
      ),
      child: Column(
        children: [
          _buildOptionTile(
            'Medical Profile',
            Icons.medical_information_outlined,
            onTap: () {
              // Add navigation or action
            },
          ),
          const Divider(height: 1),
          _buildOptionTile(
            'Sign Out',
            Icons.logout,
            onTap: () {
              _signOut();
            },
            iconColor: Colors.blue,
          ),
        ],
      ),
    );
  }

  Widget _buildOptionTile(String title, IconData icon,
      {required VoidCallback onTap, Color? iconColor}) {
    return ListTile(
      leading: Icon(
        icon,
        color: iconColor ?? Colors.grey,
        size: 24,
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
      trailing: const Icon(
        Icons.chevron_right,
        color: Colors.grey,
      ),
      onTap: onTap,
    );
  }

  Future<void> _signOut() async {
    try {
      await _auth.signOut();
      if (mounted) {
        Navigator.of(context).pushReplacementNamed(RouteNames.launch);
      }
    } catch (e) {
      print("Error signing out: $e");
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Failed to log out. Please try again.')),
        );
      }
    }
  }
}
