import 'package:flutter/material.dart';
import 'package:adminduk_puger/widget/bottom_nav.dart';
import 'package:adminduk_puger/widget/card_item.dart';
import 'package:adminduk_puger/theme.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:adminduk_puger/cubit/submission_cubit.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

String kontak =
    '<p><b>Langkah langkah mengirim data perekaman :</b></p><ol><li><b>PIlih jenis dokumen yang ingin dibuat (KTP,KK,Akta,dll)</b></li><li><b>Perhatikan jenis formulir yang diperlukan</b></li><li><b>Unduh formulir yang dibutuhkan di fitur "Daftar Formulir"<br></b><img src="data:image/png;base64, " data-filename="image.png" style="width: 260.5px; height: 142.785px;"></li><li><b>Cetak Formulir di tempat foto copy terdekat</b></li><li><b>Mengisi data formulir&nbsp;</b></li><li><b>Mengisi kelengkapan kebutuhan data pada pembuatan dokumen</b></li><li><b>Apabila masih bingung atau ada yang perlu ditanyakan <a href="http://127.0.0.1:8000" target="_blank">bisa menghubungi admin dengan cara menekan text ini, lalu tekan bagian "Contact"</a></b></li></ol>';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;

  final List<String> _routes = ['/home', '/submission', '/setting'];

  @override
  void initState() {
    super.initState();
    context.read<SubmissionCubit>().fetchSubmissions();
  }

  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
    });

    Navigator.pushReplacementNamed(context, _routes[index]);
  }

  @override
  Widget build(BuildContext context) {
    final submissionState = context.watch<SubmissionCubit>().state;

    return Scaffold(
      backgroundColor: Colors.grey[100],
      bottomNavigationBar: BottomNav(
        currentIndex: _currentIndex,
        onTap: _onTap,
      ),
      body: SafeArea(
        child: Column(
          children: [
            // AppBar
            SizedBox(
              width: double.infinity,
              child: Container(
                height: 150,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topRight,
                    end: Alignment.bottomCenter,
                    colors: [putih, biru],
                  ),
                  borderRadius: const BorderRadius.only(
                    bottomLeft: Radius.circular(34),
                    bottomRight: Radius.circular(34),
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.only(left: 20, top: 30),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Adminduk\nPuger",
                        style: GoogleFonts.poppins(
                          fontSize: 25,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.left,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // Body
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildServiceButtons(),
                    SizedBox(height: 10),
                    _buildDocumentGrid(
                      submissionState,
                      submissionState.keys.toList(),
                      context,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildServiceButtons() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      padding: EdgeInsets.symmetric(vertical: 15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 2,
            offset: Offset(0, 1),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildCategoryItem(
            assetPath: 'assets/images/icons/documents.png',
            label: "Daftar\nFormulir",
            onTap: () {
              Navigator.pushNamed(context, '/document');
            },
          ),
          _buildCategoryItem(
            assetPath: 'assets/images/icons/riwayat.png',
            label: "Riwayat\nPengajuan",
            onTap: () {
              Navigator.pushNamed(context, '/submission');
            },
          ),
          _buildCategoryItem(
            icon: Icons.help_outline,
            label: "Bantuan &\nPanduan",
            onTap: () {
              showModalBottomSheet(
                context: context,
                isScrollControlled: true,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                ),
                builder: (context) {
                  return DraggableScrollableSheet(
                    expand: false,
                    initialChildSize: 0.7,
                    minChildSize: 0.3,
                    maxChildSize: 0.95,
                    builder: (context, scrollController) {
                      return Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          children: [
                            const Text(
                              "Kontak Bantuan",
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                            const SizedBox(height: 12),
                            Expanded(
                              child: SingleChildScrollView(
                                controller: scrollController,
                                child: HtmlWidget(
                                  kontak,
                                  onTapUrl: (url) async {
                                    if (await canLaunchUrl(Uri.parse(url))) {
                                      await launchUrl(
                                        Uri.parse(url),
                                        mode: LaunchMode.externalApplication,
                                      );
                                    } else {
                                      print("Gagal membuka URL: $url");
                                    }
                                    return true;
                                  },
                                ),
                              ),
                            ),
                            const SizedBox(height: 12),
                            TextButton(
                              onPressed: () => Navigator.pop(context),
                              child: const Text("Tutup"),
                            ),
                          ],
                        ),
                      );
                    },
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryItem({
    IconData? icon,
    String? assetPath,
    VoidCallback? onTap,
    required String label,
  }) {
    return Column(
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.blue.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child:
                icon != null
                    ? Icon(icon, color: Colors.blue, size: 24)
                    : Image.asset(assetPath!, width: 24, height: 24),
          ),
        ),
        SizedBox(height: 8),
        Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 12),
        ),
      ],
    );
  }

  Widget _buildDocumentGrid(
    Map<String, dynamic> data,
    List<String> submittedTypes,
    BuildContext context,
  ) {
    // Helper untuk ngecek status 'Diproses'
    bool hasPending(List<dynamic>? items) {
      if (items == null) return false;
      return items.any((item) => item['status'] == 'Diproses');
    }

    // Helper buat munculin snackbar
    void showPendingSnackBar() {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            "Anda masih memiliki pengajuan yang berstatus 'Diproses'",
          ),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: GridView.count(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        childAspectRatio: 1.3,
        children: [
          if (submittedTypes.contains('ektp'))
            CardItem(
              title: "Kartu Tanda\nPenduduk (KTP)",
              iconPath: "ktp.png",
              onPress:
                  hasPending(data['ektp'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/ktp_option'),
            ),
          if (submittedTypes.contains('kia'))
            CardItem(
              title: "Kartu Identitas Anak (KIA)",
              iconPath: "kids.png",
              onPress:
                  hasPending(data['kia'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/kia_option'),
            ),
          if (submittedTypes.contains('kk'))
            CardItem(
              title: "Kartu Keluarga\n(KK)",
              iconPath: "kk.png",
              onPress:
                  hasPending(data['kk'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/kkform'),
            ),
          if (submittedTypes.contains('birth_certif'))
            CardItem(
              title: "Akta Kelahiran",
              iconPath: "aktehidup.png",
              onPress:
                  hasPending(data['birth_certif'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/birthcertif'),
            ),
          if (submittedTypes.contains('die_certif'))
            CardItem(
              title: "Akta Kematian",
              iconPath: "aktemati.png",
              onPress:
                  hasPending(data['die_certif'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/diecertif'),
            ),
          if (submittedTypes.contains('moving_letter'))
            CardItem(
              title: "Surat Pindah",
              iconPath: "suratpindah.png",
              onPress:
                  hasPending(data['moving_letter'])
                      ? showPendingSnackBar
                      : () => Navigator.pushNamed(context, '/moving_letter'),
            ),
        ],
      ),
    );
  }
}
