import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:marquee/marquee.dart';

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

  @override
  State<RiwayatPage> createState() =>
      _RiwayatPageState();
}



class _RiwayatPageState
    extends State<RiwayatPage> {

final ScrollController bulanController =
    ScrollController();

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

  WidgetsBinding.instance.addPostFrameCallback((_) {
    final bulanSekarang = DateTime.now().month;

    if (bulanController.hasClients) {
      bulanController.jumpTo(
        (((bulanSekarang - 3) * 70).toDouble()).clamp(
          0.0,
          bulanController.position.maxScrollExtent,
        ),
      );
    }
  });
}


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),

      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(height: 10),

            // 🔶 HEADER
            Container(
              margin: const EdgeInsets.all(16),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFFFE082),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: Colors.orange,
                  width: 1,
                ),
              ),
              child: Column(
                crossAxisAlignment:
                    CrossAxisAlignment.start,
                children: [
                  const Text(
                    "Riwayat Jadwal Pemberian Pakan",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),

                  const SizedBox(height: 12),

                  // =====================================================
// BULAN + TAHUN
// =====================================================

// =====================================================
// TAHUN + BULAN
// =====================================================

Builder(
  builder: (context) {

    final now = DateTime.now();

    final bulanSekarang = now.month;
    final tahunSekarang = now.year;

    final List<String> bulan = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "Mei",
      "Jun",
      "Jul",
      "Agu",
      "Sep",
      "Okt",
      "Nov",
      "Des",
    ];

    return SizedBox(
      width: double.infinity,

      child: Row(
        children: [

          // =====================================
          // DROPDOWN TAHUN
          // =====================================
          Container(
            padding:
                const EdgeInsets.symmetric(
              horizontal: 10,
            ),

            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.circular(10),
            ),

            child: DropdownButton<int>(
              value: tahunSekarang,

              underline: const SizedBox(),

              items: List.generate(5, (index) {

                int tahun =
                    tahunSekarang - 2 + index;

                return DropdownMenuItem(
                  value: tahun,
                  child: Text("$tahun"),
                );
              }),

              onChanged: (value) {},
            ),
          ),

          const SizedBox(width: 10),

          // =====================================
          // BULAN SCROLL
 Expanded(
  child: SizedBox(
  height: 40,
  child: ListView.builder(
    controller: bulanController,
    scrollDirection: Axis.horizontal,
    itemCount: bulan.length,
    itemBuilder: (context, index) {

      final isActive =
          (index + 1) == bulanSekarang;

      return Padding(
        padding:
            const EdgeInsets.only(
          right: 8,
        ),

        child: monthChip(
          bulan[index],
          isActive,
        ),
      );
    },
  ),
),
 ),
        ],
      ),
    );
  },
),
                ],
              ),
            ),

            // 🔻 LIST RIWAYAT FIRESTORE
            Expanded(
              child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection("riwayat")
                    .snapshots(),
                builder: (context, snapshot) {

                  // loading
                  if (snapshot.connectionState ==
                      ConnectionState.waiting) {
                    return const Center(
                      child:
                          CircularProgressIndicator(),
                    );
                  }

                  // kosong
                  if (!snapshot.hasData ||
                      snapshot.data!.docs.isEmpty) {
                    return const Center(
                      child:
                          Text("Belum ada riwayat"),
                    );
                  }

                  final docs = snapshot.data!.docs;

                  return ListView.builder(
                    padding:
                        const EdgeInsets.symmetric(
                            horizontal: 16),
                    itemCount: docs.length,
                    itemBuilder: (context, index) {

                      final data =
                          docs[index].data()
                              as Map<String, dynamic>;

                      return RiwayatItem(
  tanggal: data["tanggal"] ?? "-",
  jam: data["jam"] ?? "-",
  jenis: data["waktu"] ?? "-",
  status: data["status"] ?? "-",
  beratKanan:
      (data["beratKanan"] ?? 0).toDouble(),
  beratKiri:
      (data["beratKiri"] ?? 0).toDouble(),
);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 🔘 CHIP BULAN
  static Widget monthChip(
      String text,
      bool active,
      ) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 14,
        vertical: 6,
      ),
      decoration: BoxDecoration(
        color: active
            ? const Color(0xFFD4AF37)
            : const Color(0xFFFFB74D),
        borderRadius:
            BorderRadius.circular(20),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
    );
  }
}

// ======================================================
// ITEM RIWAYAT
// ======================================================

class RiwayatItem extends StatelessWidget {
final String tanggal;
final String jam;
final String jenis;
final String status;

final double beratKanan;
final double beratKiri;

const RiwayatItem({
  super.key,
  required this.tanggal,
  required this.jam,
  required this.jenis,
  required this.status,
  required this.beratKanan,
  required this.beratKiri,
});

  Color getStatusColor() {

    if (status == "done") {
      return Colors.green;
    }

    if (status == "running") {
      return Colors.orange;
    }

    return Colors.red;
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      margin: const EdgeInsets.only(bottom: 10),

      padding: const EdgeInsets.symmetric(
        horizontal: 10,
        vertical: 10,
      ),

      decoration: BoxDecoration(
        color: const Color(0xFFE8B4B4),
        borderRadius: BorderRadius.circular(10),
      ),

child: Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [

Text(
  jenis,
  style: const TextStyle(
    fontWeight: FontWeight.bold,
    fontSize: 15,
  ),
),

    const SizedBox(height: 4),

    Text("Jam : $jam"),

    Text("Tanggal : $tanggal"),

    Text(
      "Berat Kanan : ${beratKanan.toStringAsFixed(1)} kg",
    ),

    Text(
      "Berat Kiri : ${beratKiri.toStringAsFixed(1)} kg",
    ),

    const SizedBox(height: 12),

    Container(
      width: double.infinity,
      height: 40,
      decoration: BoxDecoration(
        color: getStatusColor(),
        borderRadius: BorderRadius.circular(8),
      ),

      child: Center(
        child: status.length > 30
            ? Marquee(
                text: status,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
                blankSpace: 40,
                velocity: 25,
              )
            : Text(
                status,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                  fontWeight: FontWeight.bold,
                ),
              ),
      ),
    ),
  ],
),
    );
  }
}