import 'package:flutter/material.dart';
import 'loker_tab.dart';
import 'riwayat_tab.dart';
import 'package:intl/intl.dart';
import 'package:ui_loker/Service/api_service.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late TabController _tabController;
  DateTime selectedDate = DateTime.now();
  int penghasilan = 0;
  final ApiService apiService = ApiService();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    selectedDate = DateTime.now();
    fetchPenghasilan();
  }

  Future<void> selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
      });

      fetchPenghasilan();
    }
  }

  Future<void> fetchPenghasilan() async {
    final String formattedDate = DateFormat('yyyy-MM-dd').format(selectedDate);
    try {
      final total = await apiService.getPenghasilanByTanggal(formattedDate);
      setState(() {
        penghasilan = total;
      });
    } catch (e) {
      print("Error: $e");
      setState(() {
        penghasilan = 0;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final String tanggalLabel = DateFormat('dd MMMM yyyy').format(selectedDate);

    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: Column(
        children: [
          // Penghasilan dan tombol pilih tanggal
          Container(
            height: 180,
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
            decoration: BoxDecoration(
              color: Colors.deepPurple,
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(30),
                bottomRight: Radius.circular(30),
              ),
            ),
            width: double.infinity,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Penghasilan Tanggal",
                  style: TextStyle(color: Colors.white70),
                ),
                SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      tanggalLabel,
                      style: TextStyle(color: Colors.white, fontSize: 16),
                    ),
                    IconButton(
                      onPressed: () => selectDate(context),
                      icon: Icon(Icons.calendar_today, color: Colors.white),
                    )
                  ],
                ),
                SizedBox(height: 8),
                Text(
                  "Rp $penghasilan",
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),

          // TabBar
          Container(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(25),
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 5)],
            ),
            child: TabBar(
              controller: _tabController,
              indicator: BoxDecoration(
                color: Colors.pinkAccent,
                borderRadius: BorderRadius.circular(25),
              ),
              indicatorPadding: EdgeInsets.all(4),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor: Colors.white,
              unselectedLabelColor: Colors.black54,
              tabs: [
                Tab(text: "Loker"),
                Tab(text: "Riwayat"),
              ],
            ),
          ),

          // Isi dari TabBar
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [LokerTab(activeTabIndex: 0), RiwayatTab()],
            ),
          ),
        ],
      ),
    );
  }
}
