import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../domain/notifiers/profile_notifier.dart';
import '../widgets/profile_info_row.dart';

class ProfilePage extends ConsumerWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // profileState is AsyncValue<UserProfile?>
    final profileState = ref.watch(profileProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('내 정보'),
        actions: [
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: () => context.push('/profile/edit'),
          ),
        ],
      ),
      body: profileState.when(
        data: (profile) {
          if (profile == null) {
            return const Center(child: Text('정보를 불러올 수 없습니다.'));
          }
          return RefreshIndicator(
            onRefresh: () => ref.read(profileProvider.notifier).loadProfile(),
            child: ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                const Center(
                  child: CircleAvatar(
                    radius: 40,
                    child: Icon(Icons.person, size: 40),
                  ),
                ),
                const SizedBox(height: 24),
                ProfileInfoRow(label: '이름', value: profile.name),
                ProfileInfoRow(label: '이메일', value: profile.email),
                ProfileInfoRow(label: '전화번호', value: profile.phone),
                const Divider(height: 32),
                ProfileInfoRow(label: '소속', value: profile.department),
                ProfileInfoRow(label: '구분', value: profile.affiliationType),
                if (profile.companyCode.isNotEmpty)
                  ProfileInfoRow(label: '회사코드', value: profile.companyCode),
              ],
            ),
          );
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('오류 발생: $err'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () => ref.read(profileProvider.notifier).loadProfile(),
                child: const Text('재시도'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}