import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shamsi_date/shamsi_date.dart';

import '../../core/api/api_client.dart';
import '../../core/auth/auth_provider.dart';

final _shiftProvider =
    FutureProvider.autoDispose<Map<String, dynamic>?>((ref) async {
  final session = ref.watch(authProvider);
  if (session == null) return null;
  final client = ref.watch(apiClientProvider);
  try {
    final res = await client.dio.get<Map<String, dynamic>>(
      '/api/cafes/${session.cafeId}/employees/${session.userId}/shift/today',
    );
    return res.data?['data'] as Map<String, dynamic>?;
  } catch (_) {
    return null;
  }
});

class ShiftScreen extends ConsumerStatefulWidget {
  const ShiftScreen({super.key});

  @override
  ConsumerState<ShiftScreen> createState() => _ShiftScreenState();
}

class _ShiftScreenState extends ConsumerState<ShiftScreen> {
  String? _message;
  bool _busy = false;

  Future<void> _clock(bool isIn) async {
    final session = ref.read(authProvider);
    if (session == null) return;
    setState(() => _busy = true);
    try {
      final client = ref.read(apiClientProvider);
      final path = isIn ? 'clock-in' : 'clock-out';
      await client.dio.post(
        '/api/cafes/${session.cafeId}/employees/${session.userId}/attendance/$path',
      );
      ref.invalidate(_shiftProvider);
      setState(() => _message = isIn ? 'ورود ثبت شد ✓' : 'خروج ثبت شد ✓');
    } catch (_) {
      setState(() => _message = 'خطا — اتصال را بررسی کنید');
    } finally {
      setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final session = ref.watch(authProvider);
    final shiftAsync = ref.watch(_shiftProvider);
    final theme = Theme.of(context);
    final todayJ = Jalali.now();

    return Scaffold(
      appBar: AppBar(
        title: const Text('شیفت من'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            tooltip: 'خروج از حساب',
            onPressed: () async {
              await ref.read(authProvider.notifier).logout();
            },
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          // Profile card
          if (session != null)
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 26,
                      backgroundColor:
                          theme.colorScheme.primaryContainer,
                      child: Text(
                        session.displayName.isNotEmpty
                            ? session.displayName[0].toUpperCase()
                            : '؟',
                        style: TextStyle(
                          fontSize: 22,
                          color: theme.colorScheme.onPrimaryContainer,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const SizedBox(width: 14),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(session.displayName,
                            style: theme.textTheme.titleMedium),
                        Text(session.role,
                            style: theme.textTheme.bodySmall?.copyWith(
                                color:
                                    theme.colorScheme.onSurfaceVariant)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          const SizedBox(height: 16),

          // Date
          Text(
            'امروز: ${todayJ.formatter.d} ${todayJ.formatter.mN} ${todayJ.formatter.y}',
            style: theme.textTheme.titleSmall
                ?.copyWith(color: theme.colorScheme.onSurfaceVariant),
          ),
          const SizedBox(height: 12),

          // Shift info
          shiftAsync.when(
            loading: () =>
                const Center(child: CircularProgressIndicator()),
            error: (_, __) =>
                const Text('شیفت در دسترس نیست'),
            data: (shift) => Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('شیفت',
                        style: theme.textTheme.labelMedium?.copyWith(
                            color: theme.colorScheme.onSurfaceVariant)),
                    const SizedBox(height: 4),
                    Text(
                      shift?['label'] as String? ?? 'شیفت تعریف نشده',
                      style: theme.textTheme.bodyLarge,
                    ),
                    if (shift?['startTime'] != null) ...[
                      const SizedBox(height: 4),
                      Text(
                        '${shift!['startTime']} — ${shift['endTime'] ?? ''}',
                        style: theme.textTheme.bodySmall,
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
          const SizedBox(height: 20),

          // Clock in/out buttons
          Row(
            children: [
              Expanded(
                child: FilledButton.icon(
                  icon: const Icon(Icons.login),
                  label: const Text('ورود'),
                  onPressed: _busy ? null : () => _clock(true),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: OutlinedButton.icon(
                  icon: const Icon(Icons.logout),
                  label: const Text('خروج'),
                  onPressed: _busy ? null : () => _clock(false),
                ),
              ),
            ],
          ),

          if (_message != null) ...[
            const SizedBox(height: 16),
            Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              decoration: BoxDecoration(
                color: theme.colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                _message!,
                style: TextStyle(color: theme.colorScheme.onPrimaryContainer),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ],
      ),
    );
  }
}
