import 'dart:convert';

import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

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

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _dobController = TextEditingController();
  final TextEditingController _officeAddressController =
  TextEditingController();

  List<String> _verticalList = [];
  List<String> _kulamList = [];

  String? _selectedVertical;
  String? _selectedKulam;

  bool _isLoading = false;
  bool _isMetaLoading = false;

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

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _dobController.dispose();
    _officeAddressController.dispose();
    super.dispose();
  }

  Future<void> _fetchVerticalAndKulam() async {
    setState(() {
      _isMetaLoading = true;
    });

    try {
      final uri = Uri.parse('https://gelite.asia/api/members_meta.php');

      // ==== LOG REQUEST ====
      print('========= MEMBERS META API REQUEST =========');
      print('METHOD : GET');
      print('URL    : $uri');
      print('HEADERS: {} (default)');
      print('BODY   : (no body for GET)');
      print('===========================================');

      final response = await http.get(uri);

      // ==== LOG RESPONSE ====
      print('========= MEMBERS META API RESPONSE =========');
      print('STATUS CODE : ${response.statusCode}');
      print('BODY        : ${response.body}');
      print('=============================================');

      if (response.statusCode == 200) {
        final Map<String, dynamic> decoded = jsonDecode(response.body);
        print('DECODED JSON: $decoded');

        if (decoded['success'] == true) {
          final List<dynamic> vList = decoded['vertical'] ?? [];
          final List<dynamic> kList = decoded['kulam'] ?? [];

          setState(() {
            _verticalList = vList.map((e) => e.toString()).toList();
            _kulamList = kList.map((e) => e.toString()).toList();

            if (_verticalList.isNotEmpty) {
              _selectedVertical ??= _verticalList.first;
            }
            if (_kulamList.isNotEmpty) {
              _selectedKulam ??= _kulamList.first;
            }
          });
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(decoded['message'] ?? 'Failed to load meta')),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
            Text('Failed to load meta data (${response.statusCode})'),
          ),
        );
      }
    } catch (e) {
      print('ERROR MEMBERS META: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error loading meta data: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isMetaLoading = false;
        });
      }
    }
  }

  Future<void> _selectDob(BuildContext context) async {
    final now = DateTime.now();
    final initial = DateTime(now.year - 18, now.month, now.day);

    final picked = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: DateTime(1900),
      lastDate: now,
    );

    if (picked != null) {
      final formatted =
          '${picked.year.toString().padLeft(4, '0')}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}';
      setState(() {
        _dobController.text = formatted;
      });
    }
  }

  Future<void> _registerMember() async {
    final String phone = _phoneController.text.trim();
    final String name = _nameController.text.trim();
    final String vertical = _selectedVertical ?? '';
    final String kulam = _selectedKulam ?? '';
    final String dob = _dobController.text.trim();
    final String officeAddress = _officeAddressController.text.trim();
    final String email = _emailController.text.trim(); // optional

    if (phone.isEmpty || name.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Phone number and name are required')),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final uri = Uri.parse('https://gelite.asia/api/register.php');

      final Map<String, dynamic> body = {
        'phone_no': phone,
        'name': name,
        'vertical': vertical,
        'kulam': kulam,
        'dob': dob,
        'office_address': officeAddress,
        'email': email,
      };

      final String jsonBody = jsonEncode(body);

      // ==== LOG REQUEST ====
      print('============= REGISTER API REQUEST =============');
      print('METHOD  : POST');
      print('URL     : $uri');
      print('HEADERS : {Content-Type: application/json}');
      print('BODY    : $jsonBody');
      print('================================================');

      final response = await http.post(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonBody,
      );

      // ==== LOG RAW RESPONSE ====
      print('============= REGISTER API RESPONSE ============');
      print('STATUS CODE : ${response.statusCode}');
      print('BODY        : ${response.body}');
      print('================================================');

      final Map<String, dynamic> decoded = jsonDecode(response.body);
      print('DECODED JSON: $decoded');

      if (response.statusCode == 200 && decoded['success'] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(decoded['message'] ?? 'Registered')),
        );

        if (mounted) {
          Navigator.pushNamed(
            context,
            '/otp',
            arguments: {
              'phone_no': phone,
              'name': name,
              'member_id': decoded['member_id'],
            },
          );
        }
      } else {
        final msg = decoded['message'] ?? 'Registration failed';
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(msg)),
        );
      }
    } catch (e) {
      print('ERROR REGISTER: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Scaffold(
      // This helps avoid overflow when keyboard appears
      resizeToAvoidBottomInset: true,
      body: Container(
        height: size.height,
        width: size.width,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/auth/bg-image.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              stops: const [0.37, 1.0],
              colors: [
                whiteColor,
                primaryColor.withOpacity(0.5),
              ],
            ),
          ),
          child: Column(
            children: [
              backArrow(context),
              Expanded(
                child: ListView(
                  physics: const BouncingScrollPhysics(),
                  padding: const EdgeInsets.symmetric(
                    horizontal: fixPadding * 2.0,
                    vertical: fixPadding * 2.0,
                  ),
                  children: [
                    registerContent(),
                    heightSpace,
                    heightSpace,
                    userNameField(),
                    heightSpace,
                    mobileNumberField(),
                    heightSpace,
                    emailAddressField(),
                    heightSpace,
                    verticalField(),
                    heightSpace,
                    kulamField(),
                    heightSpace,
                    dobField(context),
                    heightSpace,
                    officeAddressField(),
                    heightSpace,
                    heightSpace,
                    registerButton(context),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // ============ FIELDS ============

  Widget registerButton(BuildContext context) {
    return GestureDetector(
      onTap: _isLoading ? null : _registerMember,
      child: Container(
        height: 50,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: _isLoading ? primaryColor.withOpacity(0.6) : primaryColor,
          borderRadius: BorderRadius.circular(10.0),
          boxShadow: buttonShadow,
        ),
        child: _isLoading
            ? const SizedBox(
          height: 20,
          width: 20,
          child: CircularProgressIndicator(strokeWidth: 2),
        )
            : Text(
          tr(context, 'register_text.submit_btn'),
          style: medium20White,
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Widget _commonFieldContainer({required Widget child}) {
    return Container(
      height: 52,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: boxShadow,
      ),
      alignment: Alignment.center,
      child: child,
    );
  }

  Widget emailAddressField() {
    return _commonFieldContainer(
      child: TextField(
        controller: _emailController,
        cursorColor: primaryColor,
        keyboardType: TextInputType.emailAddress,
        style: regular16Black,
        decoration: InputDecoration(
          icon: const Icon(Icons.mail_outline_outlined, size: 22.0),
          border: InputBorder.none,
          isDense: true,
          hintText: tr(context, 'register_text.email_address'),
          hintStyle: regular16Grey.copyWith(height: 1.4),
        ),
      ),
    );
  }

  Widget mobileNumberField() {
    return _commonFieldContainer(
      child: TextField(
        controller: _phoneController,
        cursorColor: primaryColor,
        keyboardType: TextInputType.phone,
        style: regular16Black,
        decoration: InputDecoration(
          icon: const Icon(Icons.phone_android_outlined, size: 22.0),
          border: InputBorder.none,
          isDense: true,
          hintText: tr(context, 'register_text.mobile_number'),
          hintStyle: regular16Grey.copyWith(height: 1.4),
        ),
      ),
    );
  }

  Widget userNameField() {
    return _commonFieldContainer(
      child: TextField(
        controller: _nameController,
        cursorColor: primaryColor,
        keyboardType: TextInputType.name,
        style: regular16Black,
        decoration: InputDecoration(
          icon: const Icon(Icons.person_outline, size: 24.0),
          border: InputBorder.none,
          isDense: true,
          hintText: tr(context, 'register_text.user_name'),
          hintStyle: regular16Grey.copyWith(height: 1.4),
        ),
      ),
    );
  }

  Widget verticalField() {
    if (_isMetaLoading) {
      return _commonFieldContainer(
        child: Row(
          children: const [
            SizedBox(
              height: 18,
              width: 18,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            SizedBox(width: 10),
            Expanded(
              child: Text(
                'Loading Vertical...',
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      );
    }

    return _commonFieldContainer(
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          isExpanded: true,
          value: _selectedVertical,
          icon: const Icon(Icons.arrow_drop_down),
          hint: Text(
            'Select Vertical',
            style: regular16Grey.copyWith(height: 1.4),
          ),
          items: _verticalList
              .map(
                (v) => DropdownMenuItem<String>(
              value: v,
              child: Text(
                v,
                style: regular16Black,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          )
              .toList(),
          onChanged: (value) {
            setState(() {
              _selectedVertical = value;
            });
          },
        ),
      ),
    );
  }

  Widget kulamField() {
    if (_isMetaLoading) {
      return _commonFieldContainer(
        child: Row(
          children: const [
            SizedBox(
              height: 18,
              width: 18,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            SizedBox(width: 10),
            Expanded(
              child: Text(
                'Loading Kulam...',
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      );
    }

    return _commonFieldContainer(
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          isExpanded: true,
          value: _selectedKulam,
          icon: const Icon(Icons.arrow_drop_down),
          hint: Text(
            'Select Kulam',
            style: regular16Grey.copyWith(height: 1.4),
          ),
          items: _kulamList
              .map(
                (v) => DropdownMenuItem<String>(
              value: v,
              child: Text(
                v,
                style: regular16Black,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          )
              .toList(),
          onChanged: (value) {
            setState(() {
              _selectedKulam = value;
            });
          },
        ),
      ),
    );
  }

  Widget dobField(BuildContext context) {
    return _commonFieldContainer(
      child: TextField(
        controller: _dobController,
        readOnly: true,
        onTap: () => _selectDob(context),
        cursorColor: primaryColor,
        style: regular16Black,
        decoration: InputDecoration(
          icon: const Icon(Icons.calendar_today_outlined, size: 22.0),
          border: InputBorder.none,
          isDense: true,
          hintText: 'DOB (YYYY-MM-DD)',
          hintStyle: regular16Grey.copyWith(height: 1.4),
        ),
      ),
    );
  }

  Widget officeAddressField() {
    return Container(
      // little taller for multiline
      height: 70,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: boxShadow,
      ),
      child: TextField(
        controller: _officeAddressController,
        cursorColor: primaryColor,
        keyboardType: TextInputType.streetAddress,
        style: regular16Black,
        maxLines: 3,
        decoration: InputDecoration(
          icon: const Icon(Icons.location_city_outlined, size: 22.0),
          border: InputBorder.none,
          isDense: true,
          hintText: 'Office Address',
          hintStyle: regular16Grey.copyWith(height: 1.4),
        ),
      ),
    );
  }

  // ============ APP BAR & HEADER ============

  Widget backArrow(BuildContext context) {
    return AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Colors.transparent,
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
      ),
      elevation: 0.0,
      shadowColor: Colors.transparent,
      centerTitle: false,
      leading: IconButton(
        onPressed: () {
          Navigator.pop(context);
        },
        icon: const Icon(
          Icons.arrow_back,
          color: blackColor,
        ),
      ),
    );
  }

  Widget registerContent() {
    return Column(
      children: [
        Text(
          tr(context, 'register_text.register'),
          style: medium20Primary,
          textAlign: TextAlign.center,
        ),
        height5Space,
        Text(
          tr(context, 'register_text.welcome_text'),
          style: regular16Grey,
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
}
