import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../views/widgets/snackbar.dart';
import '../../controller/functions/crud.dart';

class _C {
  static const bg = Color(0xFF0A0D14);
  static const card = Color(0xFF161D2E);
  static const accent = Color(0xFF00E5FF);
  static const textPrimary = Color(0xFFE8F0FE);
  static const textSec = Color(0xFF7A8BAA);
  static const inputBg = Color(0xFF0C1120);
}

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

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;

  Future<void> _register() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);

    try {
      final fingerprint = box.read(BoxName.fingerPrint);
      final response = await CRUD().post(
        link: '${AppLink.server}/Admin/auth/register.php',
        payload: {
          'name': _nameController.text.trim(),
          'phone': _phoneController.text.trim(),
          'password': _passwordController.text.trim(),
          'fingerprint': fingerprint,
        },
      );

      if (response != 'failure') {
        mySnackbarSuccess(response['message'] ?? 'تم تقديم طلبك بنجاح');
        Get.back(); // العودة لصفحة الدخول
      }
    } catch (e) {
      mySnackeBarError('حدث خطأ أثناء التسجيل: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _C.bg,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new_rounded, color: _C.accent),
          onPressed: () => Get.back(),
        ),
      ),
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 28),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                const Icon(Icons.person_add_rounded, color: _C.accent, size: 64),
                const SizedBox(height: 24),
                const Text(
                  'طلب انضمام جديد',
                  style: TextStyle(
                    color: _C.textPrimary,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                const Text(
                  'سيتم مراجعة طلبك من قبل الإدارة',
                  style: TextStyle(color: _C.textSec, fontSize: 14),
                ),
                const SizedBox(height: 40),
                _buildCard(),
                const SizedBox(height: 32),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCard() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: _C.card,
        borderRadius: BorderRadius.circular(24),
        border: Border.all(color: _C.accent.withAlpha(25)), // 0.1 * 255 ≈ 25
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          _buildField('الاسم الكامل', _nameController, Icons.person_outline),
          const SizedBox(height: 20),
          _buildField('رقم الهاتف', _phoneController, Icons.phone_android, isPhone: true),
          const SizedBox(height: 20),
          _buildField('كلمة المرور', _passwordController, Icons.lock_outline, isPass: true),
          const SizedBox(height: 32),
          _isLoading
              ? const Center(child: CircularProgressIndicator(color: _C.accent))
              : ElevatedButton(
                  onPressed: _register,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _C.accent,
                    foregroundColor: Colors.black,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(14),
                    ),
                  ),
                  child: const Text('إرسال الطلب', style: TextStyle(fontWeight: FontWeight.bold)),
                ),
        ],
      ),
    );
  }

  Widget _buildField(String label, TextEditingController ctrl, IconData icon,
      {bool isPhone = false, bool isPass = false}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, color: _C.accent, size: 16),
            const SizedBox(width: 8),
            Text(label, style: const TextStyle(color: _C.textSec, fontSize: 13)),
          ],
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: ctrl,
          obscureText: isPass,
          keyboardType: isPhone ? TextInputType.phone : TextInputType.text,
          style: const TextStyle(color: _C.textPrimary),
          decoration: InputDecoration(
            filled: true,
            fillColor: _C.inputBg,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          ),
          validator: (val) => val == null || val.isEmpty ? 'هذا الحقل مطلوب' : null,
        ),
      ],
    );
  }
}
