import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'pet_form_screen.dart';
import '../services/firestore_service.dart';
import '../models/pet_model.dart';
import '../theme/app_colors.dart';
import '../widgets/home/pet_profile_card.dart';

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

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

class _HomeScreenState extends State<HomeScreen> {
  final FirestoreService _firestoreService = FirestoreService();
  String? _userId;
  Pet? _selectedPet;

  @override
  void initState() {
    super.initState();
    _userId = _firestoreService.getCurrentUserId();
  }

  @override
  Widget build(BuildContext context) {
    if (_userId == null) {
      return const Scaffold(body: Center(child: Text('로그인이 필요합니다.')));
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: StreamBuilder<List<Pet>>(
          stream: _firestoreService.getPets(_userId!),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }

            if (snapshot.hasError) {
              return Center(child: Text('오류가 발생했습니다: ${snapshot.error}'));
            }

            final pets = snapshot.data ?? [];

            // 등록된 반려동물이 없을 때: 기존 UI 유지 (등록 버튼 강조)
            if (pets.isEmpty) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 20.w,
                      vertical: 20.h,
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        borderRadius: BorderRadius.circular(8.r),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const PetFormScreen(),
                            ),
                          );
                        },
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 4.h),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(
                                'assets/img/profile.png',
                                width: 40.w,
                                height: 40.h,
                              ),
                              SizedBox(width: 10.w),
                              Text(
                                '반려동물 등록 +',
                                style: TextStyle(
                                  fontFamily: 'SCDream',
                                  fontWeight: FontWeight.w500,
                                  fontSize: 15.sp,
                                  letterSpacing: 0.45.sp,
                                  color: const Color(0xFF1f1f1f),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: Center(
                      child: Text(
                        '등록된 반려동물이 없습니다.\n새로운 가족을 등록해주세요!',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'SCDream',
                          fontSize: 16.sp,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }

            // 등록된 반려동물이 있을 때
            // 선택된 펫이 없거나 리스트에 없으면 첫 번째 펫 선택
            // 등록된 반려동물이 있을 때
            Pet displayPet;

            // 선택된 펫이 없거나 리스트에 없으면 첫 번째 펫 선택 (State 변경 없이 화면 표시만 처리)
            if (_selectedPet != null &&
                pets.any((p) => p.id == _selectedPet!.id)) {
              displayPet = pets.firstWhere((p) => p.id == _selectedPet!.id);
            } else {
              displayPet = pets.first;
            }

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 20.w,
                    vertical: 20.h,
                  ),
                  child: PopupMenuButton<dynamic>(
                    offset: Offset(0, 50.h), // 헤더 바로 아래에 위치하도록 조정
                    elevation: 3,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    color: Colors.white,
                    surfaceTintColor: Colors.white,
                    onSelected: (value) {
                      if (value is Pet) {
                        setState(() {
                          _selectedPet = value;
                        });
                      } else if (value == 'add_pet') {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const PetFormScreen(),
                          ),
                        );
                      }
                    },
                    itemBuilder: (context) {
                      return [
                        ...pets.map(
                          (pet) => PopupMenuItem<Pet>(
                            value: pet,
                            child: Row(
                              children: [
                                CircleAvatar(
                                  radius: 16.r,
                                  backgroundColor: Colors.grey[200],
                                  backgroundImage: pet.profileImageUrl != null
                                      ? NetworkImage(pet.profileImageUrl!)
                                      : null,
                                  child: pet.profileImageUrl == null
                                      ? SvgPicture.asset(
                                          'assets/icons/profile_icon.svg',
                                          width: 16.w,
                                          colorFilter: ColorFilter.mode(
                                            Colors.grey[400]!,
                                            BlendMode.srcIn,
                                          ),
                                        )
                                      : null,
                                ),
                                SizedBox(width: 10.w),
                                Text(
                                  pet.name,
                                  style: TextStyle(
                                    fontFamily: 'SCDream',
                                    fontSize: 14.sp,
                                    fontWeight: pet.id == displayPet.id
                                        ? FontWeight.bold
                                        : FontWeight.normal,
                                    color: pet.id == displayPet.id
                                        ? AppColors.highlight
                                        : Colors.black,
                                  ),
                                ),
                                if (pet.id == displayPet.id) ...[
                                  const Spacer(),
                                  const Icon(
                                    Icons.check,
                                    color: AppColors.highlight,
                                    size: 16,
                                  ),
                                ],
                              ],
                            ),
                          ),
                        ),
                        const PopupMenuDivider(),
                        PopupMenuItem<String>(
                          value: 'add_pet',
                          child: Row(
                            children: [
                              Container(
                                padding: EdgeInsets.all(4.w),
                                decoration: BoxDecoration(
                                  color: Colors.grey[100],
                                  shape: BoxShape.circle,
                                ),
                                child: Icon(
                                  Icons.add,
                                  size: 16.w,
                                  color: Colors.black54,
                                ),
                              ),
                              SizedBox(width: 10.w),
                              Text(
                                '반려동물 추가하기',
                                style: TextStyle(
                                  fontFamily: 'SCDream',
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ];
                    },
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 프로필 이미지
                        CircleAvatar(
                          radius: 20.r,
                          backgroundColor: Colors.grey[200],
                          backgroundImage: displayPet.profileImageUrl != null
                              ? NetworkImage(displayPet.profileImageUrl!)
                              : null,
                          child: displayPet.profileImageUrl == null
                              ? SvgPicture.asset(
                                  'assets/icons/profile_icon.svg',
                                  width: 20.w,
                                  colorFilter: ColorFilter.mode(
                                    Colors.grey[400]!,
                                    BlendMode.srcIn,
                                  ),
                                )
                              : null,
                        ),
                        SizedBox(width: 10.w),
                        // 이름
                        Text(
                          displayPet.name,
                          style: TextStyle(
                            fontFamily: 'SCDream',
                            fontWeight: FontWeight.bold,
                            fontSize: 18.sp,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        // 드롭다운 화살표
                        Icon(
                          Icons.keyboard_arrow_down,
                          size: 24.w,
                          color: Colors.black,
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(children: [PetProfileCard(pet: displayPet)]),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
