// lib/screens/forms/lead_form.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<LeadFormScreen> createState() => _LeadFormScreenState();
}

class _LeadFormScreenState extends State<LeadFormScreen> {
  static const String membersApi = 'https://rmbferodeunited.in/api/get_members.php';
  static const String submitApi = 'https://rmbferodeunited.in/api/lead_form.php';

  final _formKey = GlobalKey<FormState>();

  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _placeController = TextEditingController();
  final _commentController = TextEditingController();

  bool _isSubmitting = false;
  bool _isLoadingMembers = true;
  bool _hasMembersError = false;

  String? _myRidNo;
  List<Map<String, dynamic>> _members = [];
  Map<String, dynamic>? _selectedMember;

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

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

  Future<void> _initialize() async {
    await _checkRID();
    await _fetchMembers();
  }

  Future<void> _checkRID() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final rid = prefs.getString('rid_no')?.trim();

      debugPrint('Loaded RID: $rid');

      if (rid == null || rid.isEmpty) {
        if (mounted) {
          Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
        }
        return;
      }

      if (mounted) {
        setState(() => _myRidNo = rid);
      }
    } catch (e) {
      debugPrint('RID check error: $e');
      if (mounted) {
        Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
      }
    }
  }

  Future<void> _fetchMembers() async {
    if (!mounted) return;

    setState(() {
      _isLoadingMembers = true;
      _hasMembersError = false;
    });

    try {
      final response = await http.get(
        Uri.parse(membersApi),
        headers: {'Content-Type': 'application/json'},
      ).timeout(const Duration(seconds: 10));

      debugPrint('Members API Status: ${response.statusCode}');
      debugPrint('Members API Response: ${response.body}');

      if (!mounted) return;

      if (response.statusCode != 200) {
        throw Exception('Server error: ${response.statusCode}');
      }

      final Map<String, dynamic> decoded = jsonDecode(response.body);

      if (decoded['success'] == true) {
        final List<dynamic> data = decoded['data'] ?? [];
        final members = <Map<String, dynamic>>[];

        for (final item in data) {
          if (item is Map<String, dynamic>) {
            members.add({
              ...item,
              'display_name': _buildMemberDisplayName(item),
              'rid_no': item['rid_no']?.toString().trim() ?? '',
            });
          }
        }

        if (mounted) {
          setState(() {
            _members = members;
            _isLoadingMembers = false;
          });
        }
      } else {
        throw Exception(decoded['message'] ?? 'Failed to load members');
      }
    } catch (e) {
      debugPrint('Fetch members error: $e');
      if (mounted) {
        setState(() {
          _hasMembersError = true;
          _isLoadingMembers = false;
        });
      }
    }
  }

  String _buildMemberDisplayName(Map<String, dynamic> member) {
    final name = (member['full_name'] ?? member['name'] ?? '').toString().trim();
    final company = (member['company_name'] ?? '').toString().trim();

    if (company.isNotEmpty) {
      return '$name ($company)';
    }
    return name.isNotEmpty ? name : 'Unnamed Member';
  }

  Future<void> _submitLead() async {
    if (!_formKey.currentState!.validate() ||
        _myRidNo == null ||
        _myRidNo!.isEmpty ||
        _selectedMember == null) {
      return;
    }

    setState(() => _isSubmitting = true);

    try {
      final response = await http.post(
        Uri.parse(submitApi),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: {
          'rid_no': _myRidNo!,
          'grid_no': _selectedMember!['rid_no'].toString().trim(),
          'lead_name': _nameController.text.trim(),
          'phone': _phoneController.text.trim(),
          'place': _placeController.text.trim(),
          'comments': _commentController.text.trim(),
        },
      ).timeout(const Duration(seconds: 15));

      debugPrint('Submit Status: ${response.statusCode}');
      debugPrint('Submit Response: ${response.body}');

      if (!mounted) return;

      final Map<String, dynamic> data = jsonDecode(response.body);

      if (response.statusCode == 200 && data['success'] == true) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: const Row(
                children: [
                  Icon(Icons.check_circle, color: Colors.white),
                  SizedBox(width: 12),
                  Text('Lead submitted successfully!'),
                ],
              ),
              backgroundColor: Colors.green,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            ),
          );

          _clearForm();
          Navigator.pop(context, true);
        }
      } else {
        throw Exception(data['message'] ?? 'Submission failed');
      }
    } catch (e) {
      debugPrint('Submit error: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error_outline, color: Colors.white),
                const SizedBox(width: 12),
                Text(e.toString().split('\n').first),
              ],
            ),
            backgroundColor: Colors.red.shade600,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isSubmitting = false);
      }
    }
  }

  void _clearForm() {
    _nameController.clear();
    _phoneController.clear();
    _placeController.clear();
    _commentController.clear();
    setState(() => _selectedMember = null);
  }

  String? _validatePhone(String? value) {
    if (value == null || value.trim().isEmpty) return 'Phone number is required';
    final cleanPhone = value.trim().replaceAll(RegExp(r'[^\d]'), '');
    if (cleanPhone.length < 7 || cleanPhone.length > 15) {
      return 'Enter valid phone number (7-15 digits)';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final primaryColor = Theme.of(context).colorScheme.primary;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'New Business Prospect',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        actions: [
          if (_isSubmitting)
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: SizedBox(
                height: 20,
                width: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: const AlwaysStoppedAnimation(Colors.white),
                ),
              ),
            ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Header Card
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(24),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [primaryColor, primaryColor.withOpacity(0.8)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: primaryColor.withOpacity(0.3),
                      blurRadius: 20,
                      offset: const Offset(0, 8),
                    ),
                  ],
                ),
                child: Column(
                  children: [
                    Icon(
                      Icons.business_outlined,
                      size: 48,
                      color: Colors.white,
                    ),
                    const SizedBox(height: 12),
                    const Text(
                      'Share New Prospect',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Select member and fill details',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.white.withOpacity(0.9),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 32),

              // To Member Field
              _buildInputField(
                context,
                label: 'To Member *',
                child: _isLoadingMembers
                    ? const LinearProgressIndicator(
                  backgroundColor: Colors.grey,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                )
                    : _hasMembersError
                    ? ElevatedButton.icon(
                  onPressed: _fetchMembers,
                  icon: const Icon(Icons.refresh),
                  label: const Text('Retry Loading Members'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange.shade100,
                    foregroundColor: Colors.orange.shade700,
                  ),
                )
                    : DropdownButtonFormField<Map<String, dynamic>>(
                  value: _selectedMember,
                  decoration: _inputDecoration('Select member', Icons.group),
                  isExpanded: true,
                  items: _members.map((member) {
                    return DropdownMenuItem(
                      value: member,
                      key: ValueKey(member['rid_no']),
                      child: Text(
                        member['display_name'] as String,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontSize: 16),
                      ),
                    );
                  }).toList(),
                  onChanged: (value) => setState(() => _selectedMember = value),
                  validator: (value) => value == null ? 'Please select a member' : null,
                ),
              ),
              const SizedBox(height: 20),

              // Name Field
              _buildInputField(
                context,
                label: 'Prospect Name *',
                controller: _nameController,
                validator: (v) => v?.trim().isEmpty == true ? 'Name is required' : null,
                icon: Icons.person_outline,
                textCapitalization: TextCapitalization.words,
              ),
              const SizedBox(height: 20),

              // Phone Field
              _buildInputField(
                context,
                label: 'Phone Number *',
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                validator: _validatePhone,
                icon: Icons.phone_outlined,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                ],
              ),
              const SizedBox(height: 20),

              // Place Field (Optional)
              _buildInputField(
                context,
                label: 'Place / Location',
                controller: _placeController,
                icon: Icons.location_on_outlined,
                textCapitalization: TextCapitalization.words,
              ),
              const SizedBox(height: 20),

              // Comments Field
              _buildInputField(
                context,
                label: 'Comments (Optional)',
                controller: _commentController,
                maxLines: 4,
                icon: Icons.comment_outlined,
              ),
              const SizedBox(height: 40),

              // Submit Button
              SizedBox(
                height: 60,
                child: ElevatedButton(
                  onPressed: _isSubmitting ? null : _submitLead,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: primaryColor,
                    foregroundColor: Colors.white,
                    elevation: 8,
                    shadowColor: primaryColor.withOpacity(0.4),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: _isSubmitting
                      ? const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation(Colors.white),
                        ),
                      ),
                      SizedBox(width: 16),
                      Text('Submitting...'),
                    ],
                  )
                      : const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.send, size: 24),
                      SizedBox(width: 12),
                      Text(
                        'Submit Prospect',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInputField(
      BuildContext context, {
        required String label,
        TextEditingController? controller,
        String? Function(String?)? validator,
        int maxLines = 1,
        Widget? child,
        IconData? icon,
        TextInputType? keyboardType,
        TextCapitalization textCapitalization = TextCapitalization.none,
        List<TextInputFormatter>? inputFormatters,
      }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: child ?? TextFormField(
        controller: controller,
        maxLines: maxLines,
        keyboardType: keyboardType,
        textCapitalization: textCapitalization,
        inputFormatters: inputFormatters,
        validator: validator,
        decoration: _inputDecoration(label, icon),
      ),
    );
  }

  InputDecoration _inputDecoration(String label, IconData? icon) {
    return InputDecoration(
      labelText: label,
      labelStyle: TextStyle(color: Colors.grey.shade600),
      prefixIcon: icon != null
          ? Icon(icon, color: Colors.grey.shade600)
          : null,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(16),
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(16),
        borderSide: BorderSide(color: Colors.grey.shade200),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(16),
        borderSide: const BorderSide(color: Colors.blue, width: 2),
      ),
      filled: true,
      fillColor: Colors.transparent,
      contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      isDense: true,
    );
  }
}
