import 'package:flutter/material.dart';

import '../../../../../core/services/api_service.dart';
import '../../../../layouts/appheader.dart';
import '../model/dropdown_option.dart';
import '../model/enquiry_model.dart';
import '../screens/enquiry_form.dart';
import '../screens/enquiry_group.dart';

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

  @override
  State<EnquiryScreen> createState() => _EnquiryScreenState();
}

class _EnquiryScreenState extends State<EnquiryScreen> {
  List<EnquiryModel> _enquiries = [];
  List<DropdownOption> _partners = [];
  List<DropdownOption> _insurers = [];
  List<DropdownOption> _assignees = [];
  bool _isLoading = true;
  String _searchQuery = '';

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

  Future<void> _loadData() async {
    setState(() => _isLoading = true);
    try {
      final results = await Future.wait([
        ApiService.fetchEnquiries(),
        ApiService.fetchDropdownOptions('partners'),
        ApiService.fetchDropdownOptions('insurers'),
        ApiService.fetchDropdownOptions('assignees'),
      ]);

      setState(() {
        _enquiries = results[0] as List<EnquiryModel>;
        _partners = results[1] as List<DropdownOption>;
        _insurers = results[2] as List<DropdownOption>;
        _assignees = results[3] as List<DropdownOption>;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Error loading data: $e')));
    }
  }

  Future<void> _createEnquiry(EnquiryModel enquiry) async {
    try {
      final created = await ApiService.createEnquiry(enquiry);
      setState(() {
        _enquiries.insert(0, created);
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Enquiry created successfully')),
      );
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Error creating enquiry: $e')));
    }
  }

  Future<void> _updateEnquiry(EnquiryModel enquiry) async {
    try {
      final updated = await ApiService.updateEnquiry(enquiry.id!, enquiry);
      setState(() {
        final index = _enquiries.indexWhere((e) => e.id == enquiry.id);
        if (index != -1) {
          _enquiries[index] = updated;
        }
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Enquiry updated successfully')),
      );
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Error updating enquiry: $e')));
    }
  }

  Map<String, List<EnquiryModel>> _groupEnquiries() {
    final filtered = _enquiries.where((e) {
      if (_searchQuery.isEmpty) return true;
      final query = _searchQuery.toLowerCase();
      return e.partner.toLowerCase().contains(query) ||
          e.insuredName.toLowerCase().contains(query) ||
          e.vehicleNo.toLowerCase().contains(query) ||
          e.email.toLowerCase().contains(query) ||
          e.mobile.contains(query);
    }).toList();

    return {
      'awaiting': filtered.where((e) => e.status == 'awaiting').toList(),
      'created': filtered.where((e) => e.status == 'created').toList(),
      'accepted': filtered.where((e) => e.status == 'accepted').toList(),
      'rejected': filtered.where((e) => e.status == 'rejected').toList(),
      'policy': filtered.where((e) => e.status == 'policy').toList(),
    };
  }

  @override
  Widget build(BuildContext context) {
    final groupedEnquiries = _groupEnquiries();

    return Scaffold(
      appBar: const AppHeader(),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                EnquiryForm(
                  onSubmit: _createEnquiry,
                  partners: _partners,
                  insurers: _insurers,
                  assignees: _assignees,
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '📋 Enquiries',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      SizedBox(
                        width: 250,
                        child: TextField(
                          decoration: const InputDecoration(
                            hintText: 'Search...',
                            border: OutlineInputBorder(),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          ),
                          onChanged: (value) {
                            setState(() => _searchQuery = value);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 15),
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 20),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 4,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          // Table Header
                          Container(
                            color: const Color(0xFFf8f9fa),
                            child: const Row(
                              children: [
                                SizedBox(
                                  width: 120,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Received Date',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Partner',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Assigned To',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Broker',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Insurer',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 150,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Insured Name',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 120,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Vehicle No',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 120,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Vehicle Type',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 150,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Email',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Mobile',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 150,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Remarks',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 80,
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Text(
                                      'Actions',
                                      style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: Color(0xFF555555),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          // Grouped Enquiries
                          EnquiryGroup(
                            title: 'Awaiting Proposal',
                            icon: '🕐',
                            groupKey: 'awaiting',
                            enquiries: groupedEnquiries['awaiting']!,
                            onUpdate: _updateEnquiry,
                            partners: _partners,
                            insurers: _insurers,
                            assignees: _assignees,
                          ),
                          EnquiryGroup(
                            title: 'Proposal Created',
                            icon: '📝',
                            groupKey: 'created',
                            enquiries: groupedEnquiries['created']!,
                            onUpdate: _updateEnquiry,
                            partners: _partners,
                            insurers: _insurers,
                            assignees: _assignees,
                          ),
                          EnquiryGroup(
                            title: 'Proposal Accepted',
                            icon: '✅',
                            groupKey: 'accepted',
                            enquiries: groupedEnquiries['accepted']!,
                            onUpdate: _updateEnquiry,
                            partners: _partners,
                            insurers: _insurers,
                            assignees: _assignees,
                          ),
                          EnquiryGroup(
                            title: 'Proposal Rejected',
                            icon: '❌',
                            groupKey: 'rejected',
                            enquiries: groupedEnquiries['rejected']!,
                            onUpdate: _updateEnquiry,
                            partners: _partners,
                            insurers: _insurers,
                            assignees: _assignees,
                          ),
                          EnquiryGroup(
                            title: 'Policy Created',
                            icon: '📋',
                            groupKey: 'policy',
                            enquiries: groupedEnquiries['policy']!,
                            onUpdate: _updateEnquiry,
                            partners: _partners,
                            insurers: _insurers,
                            assignees: _assignees,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
              ],
            ),
    );
  }
}
