import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../services/api_service.dart';
import '../widgets/common.dart';

class AccountScreen extends StatefulWidget {
  final VoidCallback? onProfileChanged;

  const AccountScreen({super.key, this.onProfileChanged});

  @override
  State<AccountScreen> createState() => _AccountScreenState();
}

class _AccountScreenState extends State<AccountScreen> {
  bool loading = true;
  bool registering = false;
  bool saving = false;
  bool uploadingPhoto = false;
  Uint8List? profilePreviewBytes;
  bool donorSaving = false;
  Map<String, dynamic>? user;
  Map<String, dynamic>? donorApplication;

  List<Map<String, dynamic>> donorDistricts = [];
  List<Map<String, dynamic>> donorBloodGroups = [];

  final identity = TextEditingController();
  final loginPassword = TextEditingController();
  final name = TextEditingController();
  final phone = TextEditingController();
  final email = TextEditingController();
  final registerPassword = TextEditingController();
  final confirmPassword = TextEditingController();
  final district = TextEditingController();
  String bloodGroup = '';

  final donorName = TextEditingController();
  final donorPhone = TextEditingController();
  final donorAddress = TextEditingController();
  final donorLastDonation = TextEditingController();
  String donorDistrictId = '';
  String donorThanaId = '';
  String donorBloodGroupId = '';
  bool donorAvailable = true;

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

  @override
  void dispose() {
    for (final c in [
      identity,
      loginPassword,
      name,
      phone,
      email,
      registerPassword,
      confirmPassword,
      district,
      donorName,
      donorPhone,
      donorAddress,
      donorLastDonation,
    ]) {
      c.dispose();
    }
    super.dispose();
  }

  Map<String, dynamic> _map(dynamic value) {
    if (value is Map<String, dynamic>) return value;
    if (value is Map) {
      return value.map((k, v) => MapEntry(k.toString(), v));
    }
    return <String, dynamic>{};
  }

  List<Map<String, dynamic>> _list(dynamic value) {
    if (value is! List) return <Map<String, dynamic>>[];
    return value
        .whereType<Map>()
        .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
        .toList();
  }

  String _s(dynamic value) => value == null ? '' : value.toString();

  Future<void> _load() async {
    if (mounted) setState(() => loading = true);
    final has = await ApiService.hasToken();
    if (!has) {
      if (mounted) setState(() => loading = false);
      return;
    }
    try {
      final u = await ApiService.me();
      if (!mounted) return;
      _setUser(u);
      await _loadDonorApplication();
    } on ApiException catch (e) {
      if (e.statusCode == 401 || e.statusCode == 403) {
        await ApiService.clearSession();
        if (mounted) setState(() => user = null);
      } else {
        _message(e.message, error: true);
      }
    } catch (_) {}
    if (mounted) setState(() => loading = false);
  }

  void _setUser(Map<String, dynamic> u) {
    user = u;
    if (_s(u['photo_url']).trim().isEmpty) profilePreviewBytes = null;
    name.text = _s(u['name']);
    phone.text = _s(u['phone']);
    email.text = _s(u['email']);
    district.text = _s(u['district']);
    bloodGroup = _s(u['blood_group']);
    if (donorApplication == null) {
      donorName.text = name.text;
      donorPhone.text = phone.text;
    }
  }

  Future<void> _loadDonorApplication() async {
    final data = await ApiService.getJson('/auth/donor-application');
    final filters = _map(data['filters']);
    final app = _map(data['application']);
    if (!mounted) return;
    setState(() {
      donorDistricts = _list(filters['districts']);
      donorBloodGroups = _list(filters['blood_groups']);
      donorApplication = app.isEmpty ? null : app;
      _fillDonorForm(app.isEmpty ? null : app);
    });
  }

  void _fillDonorForm(Map<String, dynamic>? app) {
    donorName.text = _s(app?['name']).isNotEmpty ? _s(app?['name']) : name.text;
    donorPhone.text = _s(app?['phone']).isNotEmpty ? _s(app?['phone']) : phone.text;
    donorAddress.text = _s(app?['address']);
    donorLastDonation.text = _s(app?['last_donation_date']);
    donorDistrictId = _s(app?['district_id']);
    donorThanaId = _s(app?['thana_id']);
    donorAvailable = app == null || app['available'] == 1 || app['available'] == '1' || app['available'] == true;

    final appGroup = _s(app?['blood_group']);
    donorBloodGroupId = _s(app?['blood_group_id']);
    if (donorBloodGroupId.isEmpty && appGroup.isNotEmpty) {
      final match = donorBloodGroups.where((g) => _s(g['name']) == appGroup);
      if (match.isNotEmpty) donorBloodGroupId = _s(match.first['id']);
    }
    if (donorBloodGroupId.isEmpty && bloodGroup.isNotEmpty) {
      final match = donorBloodGroups.where((g) => _s(g['name']) == bloodGroup);
      if (match.isNotEmpty) donorBloodGroupId = _s(match.first['id']);
    }
    if (donorDistrictId.isEmpty && district.text.trim().isNotEmpty) {
      final match = donorDistricts.where((d) => _s(d['name']) == district.text.trim());
      if (match.isNotEmpty) donorDistrictId = _s(match.first['id']);
    }
  }

  List<Map<String, dynamic>> get _selectedDistrictThanas {
    if (donorDistrictId.isEmpty) return [];
    final match = donorDistricts.where((d) => _s(d['id']) == donorDistrictId);
    if (match.isEmpty) return [];
    return _list(match.first['thanas']);
  }

  void _message(String text, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(text),
        backgroundColor: error ? kDeepRed : Colors.green.shade700,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F8FB),
      appBar: AppBar(
        title: const Text(
          'আমার একাউন্ট',
          style: TextStyle(color: kRed, fontWeight: FontWeight.w900),
        ),
      ),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : user == null
              ? _authView()
              : _profileView(),
    );
  }

  Widget _authView() {
    return ListView(
      padding: const EdgeInsets.all(20),
      children: [
        Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            gradient: const LinearGradient(
              colors: [Color(0xFFD52B38), Color(0xFF9B0B3B)],
            ),
            borderRadius: BorderRadius.circular(28),
          ),
          child: Column(
            children: [
              const CircleAvatar(
                radius: 34,
                backgroundColor: Colors.white24,
                child: Icon(Icons.person_rounded, color: Colors.white, size: 40),
              ),
              const SizedBox(height: 14),
              Text(
                registering ? 'নতুন একাউন্ট তৈরি করুন' : 'আপনার একাউন্টে লগইন করুন',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.w900,
                ),
              ),
              const SizedBox(height: 6),
              Text(
                registering
                    ? 'আপনার তথ্য দিয়ে লাইফড্রপ পরিবারের সদস্য হন।'
                    : 'ডোনার হতে আবেদন, রক্তের আবেদন পোস্ট ও নিজের তথ্য পরিচালনা করতে লগইন করুন।',
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.white70, height: 1.5),
              ),
            ],
          ),
        ),
        const SizedBox(height: 18),
        SoftCard(
          child: Column(
            children: [
              SegmentedButton<bool>(
                segments: const [
                  ButtonSegment(value: false, label: Text('লগইন'), icon: Icon(Icons.login)),
                  ButtonSegment(value: true, label: Text('রেজিস্টার'), icon: Icon(Icons.person_add_alt_1)),
                ],
                selected: {registering},
                onSelectionChanged: (s) => setState(() => registering = s.first),
              ),
              const SizedBox(height: 20),
              if (registering) ..._registerFields() else ..._loginFields(),
            ],
          ),
        ),
      ],
    );
  }

  List<Widget> _loginFields() => [
        TextField(
          controller: identity,
          keyboardType: TextInputType.emailAddress,
          decoration: _dec('মোবাইল নম্বর অথবা ইমেইল', Icons.alternate_email),
        ),
        const SizedBox(height: 14),
        TextField(
          controller: loginPassword,
          obscureText: true,
          decoration: _dec('পাসওয়ার্ড', Icons.lock_outline),
        ),
        const SizedBox(height: 20),
        SizedBox(
          width: double.infinity,
          height: 54,
          child: FilledButton(
            style: FilledButton.styleFrom(backgroundColor: kDeepRed),
            onPressed: saving ? null : _login,
            child: Text(saving ? 'লগইন হচ্ছে...' : 'লগইন করুন'),
          ),
        ),
      ];

  List<Widget> _registerFields() => [
        TextField(controller: name, decoration: _dec('পূর্ণ নাম *', Icons.person_outline)),
        const SizedBox(height: 12),
        TextField(
          controller: phone,
          keyboardType: TextInputType.phone,
          decoration: _dec('মোবাইল নম্বর *', Icons.phone_outlined),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: email,
          keyboardType: TextInputType.emailAddress,
          decoration: _dec('ইমেইল (ঐচ্ছিক)', Icons.email_outlined),
        ),
        const SizedBox(height: 12),
        DropdownButtonFormField<String>(
          value: bloodGroup.isEmpty ? null : bloodGroup,
          items: ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
              .map((e) => DropdownMenuItem(value: e, child: Text(e)))
              .toList(),
          onChanged: (v) => bloodGroup = v ?? '',
          decoration: _dec('রক্তের গ্রুপ (ঐচ্ছিক)', Icons.bloodtype_outlined),
        ),
        const SizedBox(height: 12),
        TextField(controller: district, decoration: _dec('জেলা (ঐচ্ছিক)', Icons.location_on_outlined)),
        const SizedBox(height: 12),
        TextField(
          controller: registerPassword,
          obscureText: true,
          decoration: _dec('পাসওয়ার্ড (কমপক্ষে ৬ অক্ষর) *', Icons.lock_outline),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: confirmPassword,
          obscureText: true,
          decoration: _dec('পাসওয়ার্ড আবার লিখুন *', Icons.lock_reset_outlined),
        ),
        const SizedBox(height: 20),
        SizedBox(
          width: double.infinity,
          height: 54,
          child: FilledButton(
            style: FilledButton.styleFrom(backgroundColor: kDeepRed),
            onPressed: saving ? null : _register,
            child: Text(saving ? 'একাউন্ট তৈরি হচ্ছে...' : 'রেজিস্টার করুন'),
          ),
        ),
      ];

  Widget _profileView() {
    final verified = user?['verified'] == 1 || user?['verified'] == '1';
    return RefreshIndicator(
      onRefresh: _load,
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(20),
        children: [
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Color(0xFFB51C2A), Color(0xFF741238)],
              ),
              borderRadius: BorderRadius.circular(28),
            ),
            child: Row(
              children: [
                _profilePhotoAvatar(),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Flexible(
                            child: Text(
                              _s(user?['name']),
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 20,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                          ),
                          if (verified) ...[
                            const SizedBox(width: 6),
                            const Icon(Icons.verified, color: Colors.lightBlueAccent, size: 19),
                          ],
                        ],
                      ),
                      const SizedBox(height: 5),
                      Text(_s(user?['phone']), style: const TextStyle(color: Colors.white70)),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
          Align(
            alignment: Alignment.centerLeft,
            child: OutlinedButton.icon(
              onPressed: uploadingPhoto ? null : _pickAndUploadPhoto,
              icon: uploadingPhoto
                  ? const SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Icon(Icons.photo_camera_outlined),
              label: Text(uploadingPhoto ? 'ছবি আপলোড হচ্ছে...' : 'প্রোফাইল ছবি পরিবর্তন করুন'),
            ),
          ),
          const SizedBox(height: 12),
          _donorStatusAndForm(),
          const SizedBox(height: 14),
          SoftCard(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('প্রোফাইল তথ্য', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
                const SizedBox(height: 16),
                TextField(controller: name, decoration: _dec('পূর্ণ নাম', Icons.person_outline)),
                const SizedBox(height: 12),
                TextField(controller: phone, keyboardType: TextInputType.phone, decoration: _dec('মোবাইল নম্বর', Icons.phone_outlined)),
                const SizedBox(height: 12),
                TextField(controller: email, keyboardType: TextInputType.emailAddress, decoration: _dec('ইমেইল', Icons.email_outlined)),
                const SizedBox(height: 12),
                DropdownButtonFormField<String>(
                  value: bloodGroup.isEmpty ? null : bloodGroup,
                  items: ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
                      .map((e) => DropdownMenuItem(value: e, child: Text(e)))
                      .toList(),
                  onChanged: (v) => bloodGroup = v ?? '',
                  decoration: _dec('রক্তের গ্রুপ', Icons.bloodtype_outlined),
                ),
                const SizedBox(height: 12),
                TextField(controller: district, decoration: _dec('জেলা', Icons.location_on_outlined)),
                const SizedBox(height: 18),
                SizedBox(
                  width: double.infinity,
                  child: FilledButton.icon(
                    onPressed: saving ? null : _saveProfile,
                    icon: const Icon(Icons.save_outlined),
                    label: Text(saving ? 'সেভ হচ্ছে...' : 'প্রোফাইল সেভ করুন'),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 14),
          SoftCard(
            child: Column(
              children: [
                ListTile(
                  contentPadding: EdgeInsets.zero,
                  leading: const Icon(Icons.password_rounded, color: kRed),
                  title: const Text('পাসওয়ার্ড পরিবর্তন', style: TextStyle(fontWeight: FontWeight.w800)),
                  trailing: const Icon(Icons.chevron_right),
                  onTap: _changePassword,
                ),
                const Divider(),
                ListTile(
                  contentPadding: EdgeInsets.zero,
                  leading: const Icon(Icons.logout, color: kRed),
                  title: const Text('লগআউট', style: TextStyle(fontWeight: FontWeight.w800, color: kRed)),
                  onTap: _logout,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _donorStatusAndForm() {
    final status = _s(donorApplication?['status']);
    Color statusColor;
    IconData statusIcon;
    String title;
    String message;
    switch (status) {
      case 'approved':
        statusColor = Colors.green.shade700;
        statusIcon = Icons.verified_rounded;
        title = 'ডোনার স্ট্যাটাস: অনুমোদিত';
        message = 'আপনি এখন ডোনার তালিকায় আছেন। নিচের তথ্য পরিবর্তন করলে তালিকাতেও সাথে সাথে আপডেট হবে।';
        break;
      case 'pending':
        statusColor = Colors.orange.shade800;
        statusIcon = Icons.hourglass_top_rounded;
        title = 'ডোনার স্ট্যাটাস: অনুমোদনের অপেক্ষায়';
        message = 'অ্যাডমিন আপনার আবেদন যাচাই করছেন। এই সময়েও নিচের তথ্য আপডেট করতে পারবেন।';
        break;
      case 'rejected':
        statusColor = Colors.red.shade700;
        statusIcon = Icons.cancel_rounded;
        title = 'ডোনার স্ট্যাটাস: আবেদন বাতিল হয়েছে';
        message = _s(donorApplication?['admin_note']).isNotEmpty
            ? 'অ্যাডমিন নোট: ${_s(donorApplication?['admin_note'])}'
            : 'তথ্য ঠিক করে আবার আবেদন করতে পারবেন।';
        break;
      default:
        statusColor = const Color(0xFFD71920);
        statusIcon = Icons.volunteer_activism_rounded;
        title = 'ডোনার হিসেবে যোগ করুন';
        message = 'ফর্মটি পূরণ করে আবেদন করুন। অ্যাডমিন অনুমোদন করার পর আপনার তথ্য ডোনার তালিকায় দেখাবে।';
    }

    final thanas = _selectedDistrictThanas;
    final validThana = thanas.any((t) => _s(t['id']) == donorThanaId);
    if (!validThana && donorThanaId.isNotEmpty) donorThanaId = '';

    return SoftCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: statusColor.withAlpha(20),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: statusColor.withAlpha(56)),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(statusIcon, color: statusColor, size: 30),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title, style: TextStyle(color: statusColor, fontSize: 17, fontWeight: FontWeight.w900)),
                      const SizedBox(height: 4),
                      Text(message, style: const TextStyle(height: 1.4, color: Colors.black54)),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 18),
          const Text('ডোনার তথ্য', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
          const SizedBox(height: 14),
          TextField(controller: donorName, decoration: _dec('ডোনারের নাম *', Icons.person_outline)),
          const SizedBox(height: 12),
          TextField(controller: donorPhone, keyboardType: TextInputType.phone, decoration: _dec('মোবাইল নম্বর *', Icons.phone_outlined)),
          const SizedBox(height: 12),
          DropdownButtonFormField<String>(
            value: donorBloodGroupId.isEmpty ? null : donorBloodGroupId,
            isExpanded: true,
            decoration: _dec('রক্তের গ্রুপ *', Icons.bloodtype_outlined),
            items: donorBloodGroups
                .map((g) => DropdownMenuItem(value: _s(g['id']), child: Text(_s(g['name']))))
                .toList(),
            onChanged: (v) => setState(() => donorBloodGroupId = v ?? ''),
          ),
          const SizedBox(height: 12),
          DropdownButtonFormField<String>(
            value: donorDistrictId.isEmpty ? null : donorDistrictId,
            isExpanded: true,
            decoration: _dec('জেলা *', Icons.location_city_outlined),
            items: donorDistricts
                .map((d) => DropdownMenuItem(value: _s(d['id']), child: Text(_s(d['name']))))
                .toList(),
            onChanged: (v) {
              setState(() {
                donorDistrictId = v ?? '';
                donorThanaId = '';
              });
            },
          ),
          const SizedBox(height: 12),
          DropdownButtonFormField<String>(
            value: donorThanaId.isEmpty ? null : donorThanaId,
            isExpanded: true,
            decoration: _dec('থানা / উপজেলা *', Icons.account_balance_outlined),
            items: thanas
                .map((t) => DropdownMenuItem(value: _s(t['id']), child: Text(_s(t['name']))))
                .toList(),
            onChanged: donorDistrictId.isEmpty ? null : (v) => setState(() => donorThanaId = v ?? ''),
          ),
          const SizedBox(height: 12),
          TextField(controller: donorAddress, maxLines: 2, decoration: _dec('ঠিকানা', Icons.home_outlined)),
          const SizedBox(height: 12),
          TextField(
            controller: donorLastDonation,
            readOnly: true,
            onTap: _pickLastDonationDate,
            decoration: _dec('শেষ রক্তদানের তারিখ (ঐচ্ছিক)', Icons.event_outlined).copyWith(
              suffixIcon: donorLastDonation.text.isEmpty
                  ? const Icon(Icons.calendar_month_outlined)
                  : IconButton(
                      onPressed: () => setState(() => donorLastDonation.clear()),
                      icon: const Icon(Icons.close),
                    ),
            ),
          ),
          const SizedBox(height: 8),
          SwitchListTile.adaptive(
            contentPadding: EdgeInsets.zero,
            value: donorAvailable,
            onChanged: (v) => setState(() => donorAvailable = v),
            activeColor: kRed,
            title: const Text('এখন রক্ত দিতে প্রস্তুত', style: TextStyle(fontWeight: FontWeight.w800)),
            subtitle: const Text('বন্ধ করলে ডোনার তালিকায় অনুপলব্ধ হিসেবে দেখাবে।'),
          ),
          const SizedBox(height: 10),
          SizedBox(
            width: double.infinity,
            height: 52,
            child: FilledButton.icon(
              style: FilledButton.styleFrom(backgroundColor: kRed),
              onPressed: donorSaving ? null : _saveDonorApplication,
              icon: donorSaving
                  ? const SizedBox(width: 19, height: 19, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                  : Icon(status == 'approved' ? Icons.save_rounded : Icons.volunteer_activism_rounded),
              label: Text(
                donorSaving
                    ? 'সেভ হচ্ছে...'
                    : status == 'approved'
                        ? 'ডোনার তথ্য আপডেট করুন'
                        : status == 'pending'
                            ? 'আবেদনের তথ্য আপডেট করুন'
                            : status == 'rejected'
                                ? 'আবার আবেদন করুন'
                                : 'ডোনার হিসেবে আবেদন করুন',
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _pickLastDonationDate() async {
    final now = DateTime.now();
    final initial = DateTime.tryParse(donorLastDonation.text) ?? now;
    final date = await showDatePicker(
      context: context,
      initialDate: initial.isAfter(now) ? now : initial,
      firstDate: DateTime(now.year - 30),
      lastDate: now,
    );
    if (date == null || !mounted) return;
    setState(() {
      donorLastDonation.text = '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    });
  }

  Future<void> _saveDonorApplication() async {
    if (donorName.text.trim().isEmpty || donorPhone.text.trim().isEmpty) {
      _message('ডোনারের নাম ও মোবাইল নম্বর দিন', error: true);
      return;
    }
    if (donorBloodGroupId.isEmpty || donorDistrictId.isEmpty || donorThanaId.isEmpty) {
      _message('রক্তের গ্রুপ, জেলা ও থানা নির্বাচন করুন', error: true);
      return;
    }
    setState(() => donorSaving = true);
    try {
      final data = await ApiService.postJson('/auth/donor-application', {
        'name': donorName.text.trim(),
        'phone': donorPhone.text.trim(),
        'blood_group_id': donorBloodGroupId,
        'district_id': donorDistrictId,
        'thana_id': donorThanaId,
        'address': donorAddress.text.trim(),
        'last_donation_date': donorLastDonation.text.trim(),
        'available': donorAvailable,
      });
      final app = _map(data['application']);
      if (!mounted) return;
      setState(() => donorApplication = app.isEmpty ? donorApplication : app);
      await _loadDonorApplication();
      final u = await ApiService.me();
      if (mounted) _setUser(u);
      widget.onProfileChanged?.call();
      _message(_s(data['message']).isEmpty ? 'ডোনার তথ্য সেভ হয়েছে' : _s(data['message']));
    } catch (e) {
      _message(e.toString(), error: true);
    } finally {
      if (mounted) setState(() => donorSaving = false);
    }
  }

  InputDecoration _dec(String label, IconData icon) => InputDecoration(
        labelText: label,
        prefixIcon: Icon(icon),
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)),
      );

  Future<void> _login() async {
    if (identity.text.trim().isEmpty || loginPassword.text.isEmpty) {
      _message('মোবাইল/ইমেইল ও পাসওয়ার্ড দিন', error: true);
      return;
    }
    setState(() => saving = true);
    try {
      final u = await ApiService.login(identity.text.trim(), loginPassword.text);
      _setUser(u);
      await _loadDonorApplication();
      _message('লগইন সফল হয়েছে');
    } catch (e) {
      _message(e.toString(), error: true);
    }
    if (mounted) setState(() => saving = false);
  }

  Future<void> _register() async {
    if (name.text.trim().isEmpty || phone.text.trim().isEmpty || registerPassword.text.isEmpty) {
      _message('নাম, মোবাইল ও পাসওয়ার্ড দিন', error: true);
      return;
    }
    if (registerPassword.text.length < 6) {
      _message('পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে', error: true);
      return;
    }
    if (registerPassword.text != confirmPassword.text) {
      _message('দুইটি পাসওয়ার্ড মিলছে না', error: true);
      return;
    }
    setState(() => saving = true);
    try {
      final u = await ApiService.register(
        name: name.text.trim(),
        phone: phone.text.trim(),
        email: email.text.trim(),
        password: registerPassword.text,
        bloodGroup: bloodGroup,
        district: district.text.trim(),
      );
      _setUser(u);
      registerPassword.clear();
      confirmPassword.clear();
      await _loadDonorApplication();
      _message('রেজিস্ট্রেশন সফল হয়েছে');
    } catch (e) {
      _message(e.toString(), error: true);
    }
    if (mounted) setState(() => saving = false);
  }

  Future<void> _saveProfile() async {
    setState(() => saving = true);
    try {
      final data = await ApiService.putJson('/auth/profile', {
        'name': name.text.trim(),
        'phone': phone.text.trim(),
        'email': email.text.trim(),
        'blood_group': bloodGroup,
        'district': district.text.trim(),
      });
      final u = _map(data['user']);
      _setUser(u);
      await ApiService.saveUser(u);
      if (donorApplication != null) {
        donorName.text = name.text;
        donorPhone.text = phone.text;
      }
      widget.onProfileChanged?.call();
      _message('প্রোফাইল আপডেট হয়েছে');
    } catch (e) {
      _message(e.toString(), error: true);
    }
    if (mounted) setState(() => saving = false);
  }

  Widget _profilePhotoAvatar() {
    final photo = _s(user?['photo_url']).trim();
    final ImageProvider<Object>? imageProvider = profilePreviewBytes != null
        ? MemoryImage(profilePreviewBytes!)
        : (photo.isNotEmpty ? CachedNetworkImageProvider(photo) : null);
    return Stack(
      clipBehavior: Clip.none,
      children: [
        CircleAvatar(
          radius: 36,
          backgroundColor: Colors.white24,
          backgroundImage: imageProvider,
          child: imageProvider == null
              ? const Icon(Icons.person, color: Colors.white, size: 40)
              : null,
        ),
        Positioned(
          right: -3,
          bottom: -3,
          child: Material(
            color: Colors.white,
            shape: const CircleBorder(),
            elevation: 2,
            child: InkWell(
              customBorder: const CircleBorder(),
              onTap: uploadingPhoto ? null : _pickAndUploadPhoto,
              child: const SizedBox(
                width: 30,
                height: 30,
                child: Icon(Icons.camera_alt_rounded, color: kRed, size: 17),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _pickAndUploadPhoto() async {
    try {
      final picker = ImagePicker();
      final picked = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 88,
        maxWidth: 1400,
        maxHeight: 1400,
      );
      if (picked == null) return;

      final bytes = await picked.readAsBytes();
      if (bytes.length > 5 * 1024 * 1024) {
        _message('ছবির সাইজ সর্বোচ্চ ৫ MB হতে পারবে', error: true);
        return;
      }

      if (mounted) setState(() => uploadingPhoto = true);
      final u = await ApiService.uploadProfilePhoto(
        filename: picked.name,
        bytes: bytes,
      );
      if (!mounted) return;
      setState(() {
        profilePreviewBytes = Uint8List.fromList(bytes);
        _setUser(u);
      });
      await ApiService.saveUser(u);
      widget.onProfileChanged?.call();
      _message('প্রোফাইল ছবি আপডেট হয়েছে');
    } catch (e) {
      _message(e.toString(), error: true);
    } finally {
      if (mounted) setState(() => uploadingPhoto = false);
    }
  }

  Future<void> _logout() async {
    await ApiService.logout();
    if (!mounted) return;
    setState(() {
      user = null;
      donorApplication = null;
      donorDistricts = [];
      donorBloodGroups = [];
      registering = false;
      identity.clear();
      loginPassword.clear();
    });
    _message('লগআউট হয়েছে');
  }

  Future<void> _changePassword() async {
    final current = TextEditingController();
    final next = TextEditingController();
    final confirm = TextEditingController();
    await showDialog<void>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('পাসওয়ার্ড পরিবর্তন'),
        content: SizedBox(
          width: 420,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(controller: current, obscureText: true, decoration: const InputDecoration(labelText: 'বর্তমান পাসওয়ার্ড')),
              const SizedBox(height: 12),
              TextField(controller: next, obscureText: true, decoration: const InputDecoration(labelText: 'নতুন পাসওয়ার্ড')),
              const SizedBox(height: 12),
              TextField(controller: confirm, obscureText: true, decoration: const InputDecoration(labelText: 'নতুন পাসওয়ার্ড আবার লিখুন')),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('বাতিল')),
          FilledButton(
            onPressed: () async {
              if (next.text.length < 6 || next.text != confirm.text) {
                _message('নতুন পাসওয়ার্ড ৬+ অক্ষর এবং দুইটি একই হতে হবে', error: true);
                return;
              }
              try {
                final data = await ApiService.putJson('/auth/password', {
                  'current_password': current.text,
                  'new_password': next.text,
                });
                await ApiService.clearSession();
                if (ctx.mounted) Navigator.pop(ctx);
                if (mounted) setState(() => user = null);
                _message(_s(data['message']).isEmpty ? 'পাসওয়ার্ড পরিবর্তন হয়েছে' : _s(data['message']));
              } catch (e) {
                _message(e.toString(), error: true);
              }
            },
            child: const Text('পরিবর্তন করুন'),
          ),
        ],
      ),
    );
    current.dispose();
    next.dispose();
    confirm.dispose();
  }
}
