import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../services/auth_service.dart';
import 'home_screen.dart';

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

  @override
  State<SignupScreen> createState() => _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  bool _isLoading = false;

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

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

      if (!mounted) return;

      if (user != null) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const HomeScreen()),
        );
      } 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: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
                size: 20,
              ),
              onPressed: () => Navigator.pop(context),
            ),
            title: const Text(
              '회원가입',
              style: TextStyle(
                fontSize: 15,
                fontFamily: 'SCDream',
                fontWeight: FontWeight.w500,
                color: Colors.black,
              ),
            ),
            centerTitle: true,
          ),
          body: Padding(
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 240),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Image.asset('assets/img/foot.png', width: 30),
                    const SizedBox(width: 10),
                    const Text(
                      '서비스 이용 약관',
                      style: TextStyle(
                        fontSize: 24,
                        fontFamily: 'SCDream',
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                const Text(
                  '똑똑한 반려생활을 위한 첫걸음,\nRUP에 오신것을 환영해요!',
                  style: TextStyle(
                    fontSize: 14,
                    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),
                ),
                const SizedBox(height: 10),
              ],
            ),
          ),
          bottomSheet: Container(
            color: Colors.white,
            padding: const EdgeInsets.fromLTRB(20, 20, 20, 40),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Naver Login Button
                _SocialLoginButton(
                  text: '네이버 로그인',
                  textColor: Colors.white,
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15,
                  backgroundColor: const Color(0xFF00D03F),
                  onPressed: () {},
                  iconPath: 'assets/icons/navericon.svg',
                ),
                const SizedBox(height: 15),
                // Kakao Login Button
                _SocialLoginButton(
                  text: '카카오로 3초만에 시작하기',
                  textColor: const Color(0xFF212121),
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15,
                  backgroundColor: const Color(0xFFFAE100),
                  onPressed: () {},
                  iconPath: 'assets/icons/kakaoicon.svg',
                ),
                const SizedBox(height: 15),
                // Google Login Button
                _SocialLoginButton(
                  text: '구글 로그인',
                  textColor: const Color(0xFF17191A),
                  fontFamily: 'SCDream',
                  fontWeight: FontWeight.bold,
                  fontSize: 15,
                  backgroundColor: Colors.white,
                  onPressed: _handleGoogleLogin,
                  iconPath: 'assets/icons/googleicon.svg',
                  isBordered: true,
                ),
              ],
            ),
          ),
        ),
        if (_isLoading)
          Container(
            color: Colors.black.withOpacity(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,
    this.fontSize = 16,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50,
      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),
        ),
        child: Row(
          children: [
            SvgPicture.asset(
              iconPath,
              width: 24,
              height: 24,
              fit: BoxFit.contain,
            ),
            Expanded(
              child: Text(
                text,
                style: TextStyle(
                  fontFamily: fontFamily,
                  fontWeight: fontWeight,
                  fontSize: fontSize,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            SizedBox(width: 24),
          ],
        ),
      ),
    );
  }
}
