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

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:fl_sevengen_society_user_app/theme/theme.dart';

class ReferralToReferralScreen extends StatefulWidget {
  const ReferralToReferralScreen({Key? key}) : super(key: key);

  @override
  State<ReferralToReferralScreen> createState() =>
      _ReferralToReferralScreenState();
}

class _ReferralToReferralScreenState extends State<ReferralToReferralScreen> {
  final _formKey = GlobalKey<FormState>();

  final String _meetingUrl =
      'https://rmbferodeunited.in/api/rtor_meeting.php';
  final String _inviteByUrl =
      'https://rmbferodeunited.in/api/get_invite_by.php';

  List<Map<String, dynamic>> _members = [];
  String? _memberTo;
  String? _memberFrom;

  DateTime? _selectedDate;
  TimeOfDay? _selectedTime;

  final _locationController = TextEditingController();
  final _descriptionController = TextEditingController();

  File? _selectedImage;
  final ImagePicker _picker = ImagePicker();

  bool _isLoadingMembers = false;
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _checkRID();
    _fetchMembers();
  }

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

    print('RID NO: $ridNo');

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

  Future<void> _fetchMembers() async {
    setState(() => _isLoadingMembers = true);

    try {
      print('FETCH MEMBERS URL: $_inviteByUrl');

      final res = await http.get(Uri.parse(_inviteByUrl));

      print('FETCH MEMBERS STATUS: ${res.statusCode}');
      print('FETCH MEMBERS RESPONSE: ${res.body}');

      if (res.statusCode == 200) {
        final data = json.decode(res.body);
        if (data['success'] == true) {
          _members = List<Map<String, dynamic>>.from(data['data']);
        }
      }
    } catch (e) {
      print('FETCH MEMBERS ERROR: $e');
    } finally {
      setState(() => _isLoadingMembers = false);
    }
  }

  Future<void> _pickDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.now().subtract(const Duration(days: 365)),
      lastDate: DateTime.now().add(const Duration(days: 730)),
    );

    if (picked != null) {
      print('SELECTED DATE: $picked');
      setState(() => _selectedDate = picked);
    }
  }

  Future<void> _pickTime() async {
    final picked =
    await showTimePicker(context: context, initialTime: TimeOfDay.now());

    if (picked != null) {
      print('SELECTED TIME: ${picked.format(context)}');
      setState(() => _selectedTime = picked);
    }
  }

  Future<void> _pickImage() async {
    final img = await _picker.pickImage(
      source: ImageSource.gallery,
      imageQuality: 80,
    );

    if (img != null) {
      print('SELECTED IMAGE: ${img.path}');
      setState(() => _selectedImage = File(img.path));
    }
  }

  String _fmtDate(DateTime d) =>
      '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';

  String _fmtTime(TimeOfDay t) =>
      '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}:00';

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;
    if (_selectedDate == null || _selectedTime == null) return;

    setState(() => _isSubmitting = true);

    try {
      final req =
      http.MultipartRequest('POST', Uri.parse(_meetingUrl));

      final fields = {
        'member_to': _memberTo!,
        'member_from': _memberFrom!,
        'meeting_date': _fmtDate(_selectedDate!),
        'meeting_time': _fmtTime(_selectedTime!),
        'location': _locationController.text.trim(),
        'description': _descriptionController.text.trim(),
      };

      req.fields.addAll(fields);

      print('SUBMIT URL: $_meetingUrl');
      print('REQUEST FIELDS: $fields');

      if (_selectedImage != null) {
        print('UPLOADING IMAGE: ${_selectedImage!.path}');
        req.files.add(
          await http.MultipartFile.fromPath(
            'g_tage_photo',
            _selectedImage!.path,
          ),
        );
      }

      final streamedResponse = await req.send();
      final response =
      await http.Response.fromStream(streamedResponse);

      print('SUBMIT STATUS: ${response.statusCode}');
      print('SUBMIT RESPONSE: ${response.body}');

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

        if (data['success'] == true) {
          if (!mounted) return;

          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Referral meeting submitted successfully'),
              backgroundColor: Colors.green,
              duration: Duration(seconds: 2),
            ),
          );

          await Future.delayed(const Duration(seconds: 2));

          if (!mounted) return;

          Navigator.pushNamedAndRemoveUntil(
            context,
            '/bottomBar',
                (route) => false,
          );
        } else {
          print('SUBMIT FAILED: ${data['message']}');
        }
      }
    } catch (e) {
      print('SUBMIT ERROR: $e');
    } finally {
      if (mounted) {
        setState(() => _isSubmitting = false);
      }
    }
  }

  DropdownButtonFormField<String> _memberDropdown({
    required String label,
    required String? value,
    required ValueChanged<String?> onChanged,
  }) {
    return DropdownButtonFormField<String>(
      isExpanded: true,
      value: value,
      decoration: InputDecoration(
        labelText: label,
        border: const OutlineInputBorder(),
      ),
      items: _members.map((m) {
        final text =
            '${m['full_name']} (${m['company_name'] ?? 'N/A'})';
        return DropdownMenuItem(
          value: m['rid_no'].toString(),
          child: Text(
            text,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        );
      }).toList(),
      onChanged: onChanged,
      validator: (v) => v == null ? 'Required' : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        automaticallyImplyLeading: true,
        title: Text(
          'Rotarian to Rotarian',
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: _isLoadingMembers
          ? const Center(child: CircularProgressIndicator())
          : Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              _memberDropdown(
                label: 'Member To (Invitee)',
                value: _memberTo,
                onChanged: (v) => setState(() => _memberTo = v),
              ),
              const SizedBox(height: 16),
              _memberDropdown(
                label: 'Member From (Invited By)',
                value: _memberFrom,
                onChanged: (v) => setState(() => _memberFrom = v),
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: _pickDate,
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: 'Meeting Date',
                    border: OutlineInputBorder(),
                  ),
                  child: Text(
                    _selectedDate == null
                        ? 'Tap to select date'
                        : _fmtDate(_selectedDate!),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: _pickTime,
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: 'Meeting Time',
                    border: OutlineInputBorder(),
                  ),
                  child: Text(
                    _selectedTime == null
                        ? 'Tap to select time'
                        : _selectedTime!.format(context),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _locationController,
                decoration: const InputDecoration(
                  labelText: 'Location',
                  border: OutlineInputBorder(),
                ),
                validator: (v) =>
                v == null || v.isEmpty ? 'Required' : null,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _descriptionController,
                maxLines: 3,
                decoration: const InputDecoration(
                  labelText: 'Description / Notes',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  ElevatedButton.icon(
                    onPressed: _pickImage,
                    icon: const Icon(Icons.photo),
                    label: const Text('Pick G-Tag Photo'),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      _selectedImage == null
                          ? 'No image selected'
                          : _selectedImage!.path.split('/').last,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed:
                  _isSubmitting ? null : _submitForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: primaryColor,
                    foregroundColor: Colors.white,
                    padding:
                    const EdgeInsets.symmetric(vertical: 14),
                  ),
                  child: _isSubmitting
                      ? const CircularProgressIndicator(
                    strokeWidth: 2.5,
                    valueColor:
                    AlwaysStoppedAnimation<Color>(
                        Colors.white),
                  )
                      : const Text(
                    'Submit Referral Meeting',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
