import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'pet_form_screen.dart';
import '../models/pet_model.dart';
import '../theme/app_colors.dart';
import '../widgets/home/pet_profile_card.dart';
import '../widgets/common/pet_selection_header.dart';
import '../providers/pet_provider.dart';

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

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

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = context.read<PetProvider>();
      if (provider.userId == null) {
        provider.loadUserAndPets();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final petProvider = context.watch<PetProvider>();
    final pets = petProvider.pets;
    final displayPet = petProvider.selectedPet;
    final isLoading = petProvider.isLoading;

    if (isLoading) {
      return const Scaffold(
        backgroundColor: Colors.white,
        body: Center(child: CircularProgressIndicator()),
      );
    }

    // Check login
    if (petProvider.userId == null && !isLoading) {
      return const Scaffold(body: Center(child: Text('로그인이 필요합니다.')));
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Builder(
          builder: (context) {
            if (pets.isEmpty) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      left: 20.w,
                      right: 20.w,
                      top: 6.h,
                      bottom: 20.h,
                    ),
                    child: PetSelectionHeader(
                      pets: [],
                      selectedPet: null,
                      onPetSelected: (_) {},
                      onAddPetPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const PetFormScreen(),
                          ),
                        ).then((value) {
                          if (value == true) {
                            context.read<PetProvider>().refreshPets();
                          }
                        });
                      },
                    ),
                  ),
                  Expanded(
                    child: Center(
                      child: Text(
                        '등록된 반려동물이 없습니다.\n새로운 가족을 등록해주세요!',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'SCDream',
                          fontSize: 16.sp,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }

            // 등록된 반려동물이 있을 때
            // displayPet derived from provider (already defined above)
            final currentPet = displayPet ?? pets.first;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(
                    left: 10.w,
                    right: 20.w,
                    top: 6.h,
                    bottom: 0,
                  ),
                  child: PetSelectionHeader(
                    pets: pets,
                    selectedPet: displayPet, // displayPet comes from provider
                    onPetSelected: (value) {
                      context.read<PetProvider>().selectPet(value);
                    },
                    onAddPetPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const PetFormScreen(),
                        ),
                      ).then((value) {
                        if (value == true) {
                          context.read<PetProvider>().refreshPets();
                        }
                      });
                    },
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        PetProfileCard(
                          pet: currentPet, // Use safe currentPet
                          onPetUpdated: () {
                            context.read<PetProvider>().refreshPets();
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
