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

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

  @override
  State<LeadDisplayScreen> createState() => _LeadDisplayScreenState();
}

class _LeadDisplayScreenState extends State<LeadDisplayScreen> {
  final String apiUrl = 'https://rmbferodeunited.in/api/lead_form.php';

  bool _loading = true;
  String? _error;
  bool _showReceived = true;

  String _myRidNo = '';

  List<Map<String, dynamic>> _receivedLeads = [];
  List<Map<String, dynamic>> _givenLeads = [];

  @override
  void initState() {
    super.initState();
    debugPrint('INIT LeadDisplayScreen');
    _init();
  }

  Future<void> _init() async {
    await _checkRID();
    await _loadLeads();
  }

  /* ---------------- RID CHECK ---------------- */
  Future<void> _checkRID() async {
    final prefs = await SharedPreferences.getInstance();
    final rid = prefs.getString('rid_no');

    debugPrint('RID => $rid');

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

  /* ---------------- LOAD LEADS ---------------- */
  Future<void> _loadLeads() async {
    debugPrint('LOAD LEADS');

    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final resp = await http.get(Uri.parse(apiUrl));
      debugPrint('STATUS => ${resp.statusCode}');
      debugPrint('BODY => ${resp.body}');

      if (resp.statusCode != 200) {
        setState(() {
          _error = 'Server error';
          _loading = false;
        });
        return;
      }

      final decoded = jsonDecode(resp.body);
      if (decoded is! Map || decoded['success'] != true) {
        setState(() {
          _error = 'Invalid API response';
          _loading = false;
        });
        return;
      }

      final List data = decoded['data'];

      final received = <Map<String, dynamic>>[];
      final given = <Map<String, dynamic>>[];

      for (final item in data) {
        if (item is Map) {
          final lead = Map<String, dynamic>.from(item);
          final gridNo = lead['grid_no']?.toString() ?? '';

          if (gridNo == _myRidNo) {
            received.add(lead);
          } else {
            given.add(lead);
          }
        }
      }

      debugPrint('RECEIVED => ${received.length}');
      debugPrint('GIVEN => ${given.length}');

      setState(() {
        _receivedLeads = received;
        _givenLeads = given;
        _loading = false;
      });
    } catch (e, st) {
      debugPrint('ERROR => $e\n$st');
      setState(() {
        _error = 'Failed to load leads';
        _loading = false;
      });
    }
  }

  /* ---------------- DATE FORMAT ---------------- */
  String _formatDate(String raw) {
    final dt = DateTime.tryParse(raw.replaceFirst(' ', 'T'));
    if (dt == null) return raw;
    final l = dt.toLocal();
    return '${l.year}-${l.month.toString().padLeft(2, '0')}-${l.day.toString().padLeft(2, '0')} '
        '${l.hour.toString().padLeft(2, '0')}:${l.minute.toString().padLeft(2, '0')}:${l.second.toString().padLeft(2, '0')}';
  }

  /* ---------------- CARD ---------------- */
  Widget _leadCard(Map<String, dynamic> lead) {
    final bool isReceived =
        (lead['grid_no']?.toString() ?? '') == _myRidNo;

    final String gridName =
    (lead['grid_name'] ?? lead['lead_name'] ?? '').toString();

    debugPrint(
        'CARD => ${lead['lead_name']} | isReceived=$isReceived | gridName=$gridName');

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        boxShadow: const [
          BoxShadow(color: Colors.black12, blurRadius: 6, offset: Offset(0, 3))
        ],
      ),
      child: Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // ONLY TEXT AREA
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      lead['lead_name'] ?? 'Unnamed',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text('Phone: ${lead['phone'] ?? ''}'),
                    const SizedBox(height: 4),
                    Text('Details: ${lead['comments'] ?? ''}'),
                    if (isReceived && gridName.isNotEmpty) ...[
                      const SizedBox(height: 8),
                      Text(
                        'Given by $gridName',
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0,
            top: 0,
            child: Container(
              padding:
              const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                color: const Color(0xFFe6f2f7),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                _formatDate(lead['created_at'] ?? ''),
                style: const TextStyle(fontSize: 11),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /* ---------------- UI ---------------- */
  @override
  Widget build(BuildContext context) {
    final list = _showReceived ? _receivedLeads : _givenLeads;
    final safeBottom = MediaQuery.of(context).padding.bottom;
    final primary = Theme.of(context).colorScheme.primary;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Business Prospect',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        backgroundColor: primary,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: Column(
        children: [
          const SizedBox(height: 16),

          // RECEIVED / GIVEN TABS
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                _tabButton(
                  title: 'Received',
                  active: _showReceived,
                  primary: primary,
                  onTap: () => setState(() => _showReceived = true),
                ),
                const SizedBox(width: 12),
                _tabButton(
                  title: 'Given',
                  active: !_showReceived,
                  primary: primary,
                  onTap: () => setState(() => _showReceived = false),
                ),
              ],
            ),
          ),

          const SizedBox(height: 16),

          Expanded(
            child: RefreshIndicator(
              onRefresh: _loadLeads,
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : list.isEmpty
                  ? const Center(child: Text('No records found'))
                  : ListView.builder(
                padding:
                EdgeInsets.only(bottom: 100 + safeBottom),
                itemCount: list.length,
                itemBuilder: (_, i) => _leadCard(list[i]),
              ),
            ),
          ),
        ],
      ),

      // PRIMARY BOTTOM BUTTON
      bottomNavigationBar: SafeArea(
        minimum: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: SizedBox(
          height: 56,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: primary,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            onPressed: () async {
              await Navigator.pushNamed(context, '/lead');
              await _loadLeads();
            },
            child: const Text(
              'New Business Prospect',
              style:
              TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ),
        ),
      ),
    );
  }

  Widget _tabButton({
    required String title,
    required bool active,
    required Color primary,
    required VoidCallback onTap,
  }) {
    return Expanded(
      child: InkWell(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 14),
          decoration: BoxDecoration(
            color: active ? primary : Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: primary),
          ),
          child: Center(
            child: Text(
              title,
              style: TextStyle(
                color: active ? Colors.white : primary,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
