import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; // Import screenutil
import '../services/auth_service.dart';
import 'main_screen.dart';
import 'terms_agreement_screen.dart'; // Import TermsAgreementScreen

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool _isLoading = false;

  Future<void> _handleGoogleLogin() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final authService = AuthService();
      final result = await authService.signInWithGoogle();

      if (!mounted) return;

      if (result != null) {
        final isNewUser = result['isNewUser'] as bool;

        if (isNewUser) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) =>
                  TermsAgreementScreen(idToken: result['idToken']),
            ),
          );
        } else {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const MainScreen()),
          );
        }
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('로그인이 취소되었습니다.')));
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('로그인 실패: $e')));
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
                size: 16.w, // Responsive size
              ),
              onPressed: () => Navigator.pop(context),
            ),
            title: Text(
              '간편 로그인',
              style: TextStyle(
                fontSize: 15.sp, // Responsive font size
                fontFamily: 'SCDream',
                fontWeight: FontWeight.w500,
                color: Colors.black,
              ),
            ),
            centerTitle: true,
          ),
          body: Padding(
            padding: EdgeInsets.fromLTRB(
              20.w,
              0,
              20.w,
              240.h,
            ), // Responsive padding
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.h), // Responsive height
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Image.asset(
                      'assets/img/foot.png',
                      width: 30.w,
                    ), // Responsive width
                    SizedBox(width: 10.w), // Responsive width
                    Text(
                      '간편 로그인',
                      style: TextStyle(
                        fontSize: 24.sp, // Responsive font size
                        fontFamily: 'SCDream',
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10.h),
                Text(
                  '똑똑한 반려생활을 위한 첫걸음,\nRUP에 오신것을 환영해요!',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontFamily: 'SCDream',
                    fontWeight: FontWeight.w500,
                    color: Colors.black,
                  ),
                  textAlign: TextAlign.start,
                ),
                const Spacer(),
                Align(
                  alignment: Alignment.centerRight,
                  child: Image.asset('assets/img/cat.png', height: 150.h),
                ),
                SizedBox(height: 10.h),
              ],
            ),
          ),
          bottomSheet: Container(
            color: Colors.white,
            padding: EdgeInsets.fromLTRB(20.w, 20.h, 20.w, 40.h),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Naver Login Button
                _SocialLoginButton(
                  text: '네이버 로그인',
                  textColor: Colors.white,
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp,
                  backgroundColor: const Color(0xFF00D03F),
                  onPressed: () {},
                  iconPath: 'assets/icons/naver_icon.svg',
                ),
                SizedBox(height: 15.h),
                // Kakao Login Button
                _SocialLoginButton(
                  text: '카카오 로그인',
                  textColor: const Color(0xFF212121),
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp,
                  backgroundColor: const Color(0xFFFAE100),
                  onPressed: () {},
                  iconPath: 'assets/icons/kakao_icon.svg',
                ),
                SizedBox(height: 15.h),
                // Google Login Button
                _SocialLoginButton(
                  text: '구글 로그인',
                  textColor: const Color(0xFF17191A),
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp,
                  backgroundColor: Colors.white,
                  onPressed: _handleGoogleLogin,
                  iconPath: 'assets/icons/google_icon.svg',
                  isBordered: true,
                ),
              ],
            ),
          ),
        ),
        if (_isLoading)
          Container(
            color: Colors.black.withValues(alpha: 0.5),
            child: const Center(child: CircularProgressIndicator()),
          ),
      ],
    );
  }
}

class _SocialLoginButton extends StatelessWidget {
  final String text;
  final Color textColor;
  final Color backgroundColor;
  final VoidCallback onPressed;
  final String iconPath;
  final bool isBordered;
  final String fontFamily;
  final double fontSize;
  final FontWeight fontWeight;

  const _SocialLoginButton({
    required this.text,
    required this.textColor,
    required this.backgroundColor,
    required this.onPressed,
    required this.iconPath,
    this.isBordered = false,
    this.fontFamily = 'SCDream',
    this.fontWeight = FontWeight.w500,
    required this.fontSize, // Make required to ensure passed value is used
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50.h,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: backgroundColor,
          foregroundColor: textColor,
          elevation: 0,
          shape: StadiumBorder(
            side: isBordered
                ? BorderSide(color: Colors.grey[300]!)
                : BorderSide.none,
          ),
          padding: EdgeInsets.symmetric(horizontal: 20.w),
        ),
        child: Row(
          children: [
            SvgPicture.asset(
              iconPath,
              width: 24.w,
              height: 24.h,
              fit: BoxFit.contain,
            ),
            Expanded(
              child: Text(
                text,
                style: TextStyle(
                  fontFamily: fontFamily,
                  fontWeight: fontWeight,
                  fontSize: fontSize,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            SizedBox(width: 24.w),
          ],
        ),
      ),
    );
  }
}
