import 'dart:convert';
import 'dart:io';

import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

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

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

class _RegisterScreenState extends State<RegisterScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _businessNameController = TextEditingController();

  DateTime? _selectedDate;
  String? _selectedBusinessType;
  String? _selectedGender;
  InviteBy? _selectedInviteBy;

  List<String> _businessTypes = [];
  List<InviteBy> _inviteByList = [];

  bool _isLoadingDropdowns = false;
  bool _isSubmitting = false;

  static const String _baseUrl = 'https://rmbferodeunited.in/api';

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

  Future<void> _fetchDropdownData() async {
    setState(() {
      _isLoadingDropdowns = true;
    });

    try {
      await Future.wait([
        _fetchBusinessTypes(),
        _fetchInviteByList(),
      ]);
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingDropdowns = false;
        });
      }
    }
  }

  Future<void> _fetchBusinessTypes() async {
    try {
      final uri = Uri.parse('$_baseUrl/get_business_types.php');
      final response = await http.get(uri);

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);

        if (json['success'] == true && json['data'] is List) {
          final List data = json['data'];
          setState(() {
            _businessTypes = data
                .map((e) => (e['business_type'] ?? '').toString())
                .where((e) => e.isNotEmpty)
                .toList();
          });
        }
      }
    } catch (e) {
      _showSnackBar('Failed to load business types');
    }
  }

  Future<void> _fetchInviteByList() async {
    try {
      final uri = Uri.parse('$_baseUrl/get_invite_by.php');
      final response = await http.get(uri);

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);

        if (json['success'] == true && json['data'] is List) {
          final List data = json['data'];
          setState(() {
            _inviteByList = data
                .map((e) => InviteBy.fromJson(e as Map<String, dynamic>))
                .toList();
          });
        }
      }
    } catch (e) {
      _showSnackBar('Failed to load invite by list');
    }
  }

  String _formatDate(DateTime date) {
    // PHP usually expects yyyy-MM-dd
    return DateFormat('yyyy-MM-dd').format(date);
  }

  Future<void> _pickDate() async {
    final now = DateTime.now();
    final picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? now,
      firstDate: DateTime(now.year - 1),
      lastDate: DateTime(now.year + 1),
    );

    if (picked != null) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) {
      _showSnackBar('Please fill all required fields');
      return;
    }

    if (_selectedDate == null) {
      _showSnackBar('Please select date');
      return;
    }

    if (_selectedBusinessType == null || _selectedBusinessType!.isEmpty) {
      _showSnackBar('Please select business type');
      return;
    }

    if (_selectedGender == null || _selectedGender!.isEmpty) {
      _showSnackBar('Please select gender');
      return;
    }

    if (_selectedInviteBy == null) {
      _showSnackBar('Please select invite by');
      return;
    }

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

    final body = {
      'date': _formatDate(_selectedDate!),
      'name': _nameController.text.trim(),
      'phone': _phoneController.text.trim(),
      'business_name': _businessNameController.text.trim(),
      'business_type': _selectedBusinessType!,
      'gender': _selectedGender!.toLowerCase(), // "male" or "female"
      // sending rid_no as invite_by (backend can store invited_by as rid_no)
      'invite_by': _selectedInviteBy!.id,
    };

    try {
      final uri = Uri.parse('$_baseUrl/visitors_meeting_save.php');
      final response = await http.post(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(body),
      );

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);

        if (json['success'] == true) {
          _showSnackBar('Visitor meeting saved successfully');

          // Clear form
          _formKey.currentState!.reset();
          setState(() {
            _selectedDate = null;
            _selectedBusinessType = null;
            _selectedGender = null;
            _selectedInviteBy = null;
          });
        } else {
          _showSnackBar(json['message']?.toString() ?? 'Failed to save');
        }
      } else {
        _showSnackBar('Server error: ${response.statusCode}');
      }
    } catch (e) {
      _showSnackBar('Error while saving visitor meeting');
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      body: Container(
        height: size.height,
        width: size.width,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/auth/bg.png"),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            heightSpace,
            height5Space,
            backbutton(context),
            Expanded(
              child: ListView(
                physics: const BouncingScrollPhysics(),
                padding: const EdgeInsets.symmetric(
                  horizontal: fixPadding * 2.0,
                ),
                children: [
                  registerText(),
                  heightSpace,
                  pleaseText(),
                  heightSpace,
                  heightSpace,
                  Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        dateField(),
                        heightSpace,
                        height5Space,
                        userNameField(),
                        heightSpace,
                        height5Space,
                        phoneField(),
                        heightSpace,
                        height5Space,
                        businessNameField(),
                        heightSpace,
                        height5Space,
                        businessTypeDropdown(),
                        heightSpace,
                        height5Space,
                        genderDropdown(),
                        heightSpace,
                        height5Space,
                        inviteByDropdown(),
                        heightSpace,
                        heightSpace,
                        registerButton(),
                        heightSpace,
                        heightSpace,
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ---------------- TEXTS ----------------

  Widget pleaseText() {
    return Text(
      getTranslate(context, 'register.please_text'),
      textAlign: TextAlign.center,
      style: medium14Grey77,
    );
  }

  Widget registerText() {
    return Text(
      getTranslate(context, 'register.REGISTER'),
      style: semibold21Primary,
      textAlign: TextAlign.center,
    );
  }

  // ---------------- FIELDS ----------------

  Widget dateField() {
    final dateText = _selectedDate == null
        ? getTranslate(context, 'register.date') // add in localization
        : _formatDate(_selectedDate!);

    return GestureDetector(
      onTap: _pickDate,
      child: Container(
        width: double.maxFinite,
        padding: const EdgeInsets.symmetric(
          horizontal: fixPadding * 1.5,
          vertical: fixPadding * 1.3,
        ),
        decoration: BoxDecoration(
          color: whiteColor,
          borderRadius: BorderRadius.circular(10.0),
          boxShadow: [
            BoxShadow(
              color: blackColor.withOpacity(0.1),
              blurRadius: 12.0,
              offset: const Offset(0, 6),
            ),
          ],
        ),
        child: Row(
          children: [
            const Icon(CupertinoIcons.calendar, size: 20),
            const SizedBox(width: 10),
            Expanded(
              child: Text(
                dateText,
                style: _selectedDate == null ? medium16Grey : semibold16Black33,
              ),
            ),
            const Icon(Icons.keyboard_arrow_down_rounded, size: 20),
          ],
        ),
      ),
    );
  }

  Widget userNameField() {
    return Container(
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: TextFormField(
        controller: _nameController,
        cursorColor: primaryColor,
        style: semibold16Black33,
        keyboardType: TextInputType.name,
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            return 'Name is required';
          }
          return null;
        },
        decoration: InputDecoration(
          border: InputBorder.none,
          prefixIconConstraints: const BoxConstraints(maxWidth: 60),
          prefixIconColor: WidgetStateColor.resolveWith(
                (states) =>
            states.contains(WidgetState.focused) ? primaryColor : greyColor,
          ),
          prefixIcon: Container(
            width: 60.0,
            margin: languageValue == 4
                ? const EdgeInsets.only(left: 15.0)
                : const EdgeInsets.only(right: 15.0),
            decoration: BoxDecoration(
              border: languageValue == 4
                  ? const Border(
                left: BorderSide(color: greyColor, width: 1.5),
              )
                  : const Border(
                right: BorderSide(color: greyColor, width: 1.5),
              ),
            ),
            alignment: Alignment.center,
            child: const Icon(
              CupertinoIcons.person,
              size: 20,
            ),
          ),
          hintText: getTranslate(context, 'register.user_name'),
          hintStyle: medium16Grey,
        ),
      ),
    );
  }

  Widget phoneField() {
    return Container(
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: TextFormField(
        controller: _phoneController,
        cursorColor: primaryColor,
        style: semibold16Black33,
        keyboardType: TextInputType.phone,
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            return 'Phone is required';
          }
          if (value.trim().length < 8) {
            return 'Enter valid phone number';
          }
          return null;
        },
        decoration: InputDecoration(
          border: InputBorder.none,
          prefixIconConstraints: const BoxConstraints(maxWidth: 60),
          prefixIconColor: WidgetStateColor.resolveWith(
                (states) =>
            states.contains(WidgetState.focused) ? primaryColor : greyColor,
          ),
          prefixIcon: Container(
            width: 60.0,
            margin: languageValue == 4
                ? const EdgeInsets.only(left: 15.0)
                : const EdgeInsets.only(right: 15.0),
            decoration: BoxDecoration(
              border: languageValue == 4
                  ? const Border(
                left: BorderSide(color: greyColor, width: 1.5),
              )
                  : const Border(
                right: BorderSide(color: greyColor, width: 1.5),
              ),
            ),
            alignment: Alignment.center,
            child: const Icon(
              Icons.phone_android,
              size: 20,
            ),
          ),
          hintText: getTranslate(context, 'register.mobile_number'),
          hintStyle: medium16Grey,
        ),
      ),
    );
  }

  Widget businessNameField() {
    return Container(
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: TextFormField(
        controller: _businessNameController,
        cursorColor: primaryColor,
        style: semibold16Black33,
        keyboardType: TextInputType.text,
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            return 'Business name is required';
          }
          return null;
        },
        decoration: InputDecoration(
          border: InputBorder.none,
          prefixIconConstraints: const BoxConstraints(maxWidth: 60),
          prefixIconColor: WidgetStateColor.resolveWith(
                (states) =>
            states.contains(WidgetState.focused) ? primaryColor : greyColor,
          ),
          prefixIcon: Container(
            width: 60.0,
            margin: languageValue == 4
                ? const EdgeInsets.only(left: 15.0)
                : const EdgeInsets.only(right: 15.0),
            decoration: BoxDecoration(
              border: languageValue == 4
                  ? const Border(
                left: BorderSide(color: greyColor, width: 1.5),
              )
                  : const Border(
                right: BorderSide(color: greyColor, width: 1.5),
              ),
            ),
            alignment: Alignment.center,
            child: const Icon(
              Icons.business_center_outlined,
              size: 20,
            ),
          ),
          hintText: 'Business Name',
          hintStyle: medium16Grey,
        ),
      ),
    );
  }

  Widget businessTypeDropdown() {
    return Container(
      width: double.maxFinite,
      padding: const EdgeInsets.symmetric(horizontal: fixPadding),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: DropdownButtonFormField<String>(
        value: _selectedBusinessType,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
        isExpanded: true,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Business type is required';
          }
          return null;
        },
        hint: Text(
          _isLoadingDropdowns
              ? 'Loading business types...'
              : 'Select Business Type',
          style: medium16Grey,
        ),
        items: _businessTypes
            .map(
              (type) => DropdownMenuItem<String>(
            value: type,
            child: Text(
              type,
              style: semibold16Black33,
            ),
          ),
        )
            .toList(),
        onChanged: (value) {
          setState(() {
            _selectedBusinessType = value;
          });
        },
      ),
    );
  }

  Widget genderDropdown() {
    return Container(
      width: double.maxFinite,
      padding: const EdgeInsets.symmetric(horizontal: fixPadding),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: DropdownButtonFormField<String>(
        value: _selectedGender,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
        isExpanded: true,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Gender is required';
          }
          return null;
        },
        hint: Text(
          'Select Gender',
          style: medium16Grey,
        ),
        items: const [
          DropdownMenuItem(
            value: 'Male',
            child: Text('Male'),
          ),
          DropdownMenuItem(
            value: 'Female',
            child: Text('Female'),
          ),
        ],
        onChanged: (value) {
          setState(() {
            _selectedGender = value;
          });
        },
      ),
    );
  }

  Widget inviteByDropdown() {
    return Container(
      width: double.maxFinite,
      padding: const EdgeInsets.symmetric(horizontal: fixPadding),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.1),
            blurRadius: 12.0,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: DropdownButtonFormField<InviteBy>(
        value: _selectedInviteBy,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
        isExpanded: true,
        validator: (value) {
          if (value == null) {
            return 'Invite by is required';
          }
          return null;
        },
        hint: Text(
          _isLoadingDropdowns ? 'Loading invite list...' : 'Invite By',
          style: medium16Grey,
        ),
        items: _inviteByList
            .map(
              (item) => DropdownMenuItem<InviteBy>(
            value: item,
            child: Text(
              '${item.name} (${item.id})',
              style: semibold16Black33,
            ),
          ),
        )
            .toList(),
        onChanged: (value) {
          setState(() {
            _selectedInviteBy = value;
          });
        },
      ),
    );
  }

  // ---------------- BUTTON & BACK ----------------

  Widget registerButton() {
    return GestureDetector(
      onTap: _isSubmitting ? null : _submitForm,
      child: Opacity(
        opacity: _isSubmitting ? 0.7 : 1,
        child: Container(
          width: double.maxFinite,
          padding: const EdgeInsets.symmetric(
            horizontal: fixPadding * 2.0,
            vertical: fixPadding * 1.4,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            color: primaryColor,
            boxShadow: [
              BoxShadow(
                color: primaryColor.withOpacity(0.1),
                blurRadius: 12.0,
                offset: const Offset(0, 6),
              ),
            ],
          ),
          alignment: Alignment.center,
          child: _isSubmitting
              ? const SizedBox(
            height: 20,
            width: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          )
              : Text(
            getTranslate(context, 'register.register'),
            style: semibold18White,
          ),
        ),
      ),
    );
  }

  Widget backbutton(BuildContext context) {
    return IconButton(
      onPressed: () {
        Navigator.pop(context);
      },
      padding: (Platform.isIOS)
          ? const EdgeInsets.fromLTRB(
        fixPadding * 2.0,
        fixPadding * 4.0,
        fixPadding * 2.0,
        fixPadding * 2.0,
      )
          : const EdgeInsets.all(fixPadding * 2.0),
      icon: const Icon(
        Icons.arrow_back,
        color: black33Color,
      ),
    );
  }
}

// ---------------- MODELS ----------------

class InviteBy {
  final String id; // rid_no
  final String name; // full_name

  InviteBy({
    required this.id,
    required this.name,
  });

  factory InviteBy.fromJson(Map<String, dynamic> json) {
    return InviteBy(
      id: (json['rid_no'] ?? '').toString(),
      name: (json['full_name'] ?? '').toString(),
    );
  }
}
