import 'package:digiplug/bat_theme/bat_theme.dart';
import 'package:digiplug/core/navigation/navigator.dart';
import 'package:digiplug/data/models/device.dart';
import 'package:digiplug/data/models/room.dart';
import 'package:digiplug/data/models/weather.dart';
import 'package:digiplug/features/home/presentation/widgets/device_card.dart';
import 'package:digiplug/features/home/presentation/widgets/room_card.dart';
import 'package:digiplug/features/home/presentation/widgets/summary_header.dart';
import 'package:digiplug/main.dart';
import 'package:digiplug/providers/home_data_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // Fungsi untuk mendapatkan salam berdasarkan waktu
  String getGreeting() {
    final hour = DateTime.now().hour;
    if (hour < 4) return 'Selamat Malam,';
    if (hour < 11) return 'Selamat Pagi,';
    if (hour < 15) return 'Selamat Siang,';
    if (hour < 19) return 'Selamat Sore,';
    return 'Selamat Malam,';
  }

  // Data cuaca statis
  final Weather weatherData = Weather(
    location: "Jember, ID",
    condition: "Cerah Berawan",
    temperature: 29.5,
    icon: Icons.wb_cloudy_outlined,
  );

  @override
  Widget build(BuildContext context) {
    var theme = BatThemeData.of(context);
    var themeProvider = context.read<ThemeProvider>();

    // Mengambil data dari HomeDataProvider
    var homeData = context.watch<HomeDataProvider>();
    var allDevices = homeData.devices;
    var allRooms = homeData.rooms;

    // Filter perangkat favorit
    var favoriteDevices = allDevices.where((d) => d.isFavorite).toList();

    return Scaffold(
      backgroundColor: theme.colors.background,
      body: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 16.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header: Salam dan Ikon
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(getGreeting(),
                          style: theme.typography.headline4.copyWith(
                              fontSize: 20.sp,
                              fontWeight: FontWeight.w400,
                              color: theme.colors.tertiary.withOpacity(0.7))),
                      Text("Hensen", style: theme.typography.headline3),
                    ],
                  ),
                ),
                Row(
                  children: [
                    IconButton(
                        onPressed: () => themeProvider.changeMode(),
                        icon: Icon(
                            themeProvider.isDark
                                ? Icons.light_mode_outlined
                                : Icons.dark_mode_outlined,
                            color: theme.colors.tertiary)),
                    SizedBox(width: 4.w),
                    GestureDetector(
                      onTap: () => AppNavigator.pushNamed(profileRoute),
                      child: const CircleAvatar(
                          radius: 22,
                          backgroundImage:
                              AssetImage('assets/images/profile.png')),
                    ),
                  ],
                ),
              ],
            ),
            SizedBox(height: 24.h),

            // Header Ringkasan Cuaca dan Energi
            SummaryHeader(
              weather: weatherData,
              energyUsed: 5.7, // Data energi statis
            ),
            SizedBox(height: 24.h),

            // Bagian Perangkat Favorit
            _buildFavoritesSection(theme, favoriteDevices),
            SizedBox(height: 24.h),

            // Bagian Daftar Ruangan
            _buildRoomsView(theme, allRooms),
          ],
        ),
      ),
    );
  }

  // Widget untuk membangun bagian favorit
  Widget _buildFavoritesSection(
      BatThemeData theme, List<Device> favoriteDevices) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Akses Cepat', style: theme.typography.bodyCopyMedium),
        SizedBox(height: 16.h),
        SizedBox(
          height: 170.w,
          child: favoriteDevices.isEmpty
              ? Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                      color: theme.colors.tertiary.withOpacity(0.05),
                      borderRadius: BorderRadius.circular(20.r)),
                  child:
                      const Center(child: Text('Belum ada perangkat favorit.')),
                )
              : ListView.separated(
                  scrollDirection: Axis.horizontal,
                  itemCount: favoriteDevices.length,
                  separatorBuilder: (context, index) => SizedBox(width: 16.w),
                  itemBuilder: (context, index) {
                    return SizedBox(
                      width: 170.w,
                      child: DeviceCard(
                        device: favoriteDevices[index],
                      ),
                    );
                  }),
        ),
      ],
    );
  }

  // Widget untuk membangun daftar ruangan
  Widget _buildRoomsView(BatThemeData theme, List<Room> rooms) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Daftar Ruangan',
            style: theme.typography.headline4
                .copyWith(color: theme.colors.primary)),
        SizedBox(height: 16.h),
        rooms.isEmpty
            ? const Center(child: Text('Belum ada ruangan.'))
            : GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 16,
                  mainAxisSpacing: 16,
                  childAspectRatio: 1,
                ),
                itemCount: rooms.length,
                itemBuilder: (context, index) {
                  final room = rooms[index];
                  return RoomCard(
                    roomName: room.name,
                    deviceCount: room.deviceCount,
                    onTap: () {
                      // Aksi saat ruangan di-tap (bisa dikembangkan nanti)
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        content: Text("Masuk ke ${room.name}"),
                        duration: const Duration(seconds: 1),
                      ));
                    },
                  );
                },
              ),
      ],
    );
  }
}
