import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:my_attendance/models/attendance_entry.dart';
import 'package:my_attendance/services/attendance_service.dart';
import 'package:my_attendance/services/settings_service.dart';
import 'package:provider/provider.dart';

class DayDetailScreen extends StatefulWidget {
  const DayDetailScreen({super.key});
  static const routeName = '/detail';

  @override
  State<DayDetailScreen> createState() => _DayDetailScreenState();
}

class _DayDetailScreenState extends State<DayDetailScreen> {
  late TextEditingController _notesController;

  @override
  void initState() {
    super.initState();
    _notesController = TextEditingController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final entry = ModalRoute.of(context)!.settings.arguments as AttendanceEntry;
    _notesController.text = entry.notes ?? '';
  }

  @override
  void dispose() {
    _notesController.dispose();
    super.dispose();
  }

  void _saveNotes(AttendanceEntry entry) {
    final newNotes = _notesController.text;
    if (entry.id != null) {
      Provider.of<AttendanceService>(
        context,
        listen: false,
      ).updateNotes(entry.id!, newNotes);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('Notes saved!')));
    }
  }

  @override
  Widget build(BuildContext context) {
    final entry = ModalRoute.of(context)!.settings.arguments as AttendanceEntry;

    return Scaffold(
      appBar: AppBar(title: Text(DateFormat.yMMMd().format(entry.date))),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildDetailCard(context, entry),
              const SizedBox(height: 24),
              _buildNotesCard(context, entry),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDetailCard(BuildContext context, AttendanceEntry entry) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: (entry.entryType != EntryType.work || entry.loginTime == null)
            ? _buildFinalizedUI(context, entry)
            : _buildWorkDayDetails(context, entry),
      ),
    );
  }

  Widget _buildWorkDayDetails(BuildContext context, AttendanceEntry entry) {
    final settings = Provider.of<SettingsService>(
      context,
      listen: false,
    ).settings;
    final standardDuration = settings.dailyWorkDuration;

    Duration? workDuration;
    if (entry.logoutTime != null) {
      workDuration = entry.logoutTime!.difference(entry.loginTime!);
    }

    Duration? deviation;
    if (workDuration != null) {
      deviation = workDuration - standardDuration;
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text('Timestamps', style: Theme.of(context).textTheme.titleLarge),
        const Divider(height: 20),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildTimestamp(
              context,
              icon: Icons.login,
              label: 'Login',
              time: entry.loginTime!,
            ),
            if (entry.logoutTime != null)
              _buildTimestamp(
                context,
                icon: Icons.logout,
                label: 'Logout',
                time: entry.logoutTime!,
              ),
          ],
        ),
        const SizedBox(height: 16),
        Text('Summary', style: Theme.of(context).textTheme.titleLarge),
        const Divider(height: 20),
        if (workDuration != null)
          _buildSummaryRow(
            context,
            icon: Icons.timer_outlined,
            label: 'Total Hours Worked',
            value: _formatDuration(workDuration),
          ),
        if (deviation != null)
          _buildSummaryRow(
            context,
            icon: deviation.isNegative
                ? Icons.arrow_downward
                : Icons.arrow_upward,
            label: deviation.isNegative ? 'Undertime' : 'Overtime',
            value:
                '${deviation.isNegative ? '' : '+'}${_formatDuration(deviation.abs())}',
            valueColor: deviation.isNegative
                ? Colors.red.shade400
                : Colors.green.shade400,
          ),
      ],
    );
  }

  Widget _buildTimestamp(
    BuildContext context, {
    required IconData icon,
    required String label,
    required DateTime time,
  }) {
    return Column(
      children: [
        Icon(icon, size: 32, color: Theme.of(context).colorScheme.primary),
        const SizedBox(height: 8),
        Text(label, style: Theme.of(context).textTheme.labelLarge),
        const SizedBox(height: 4),
        Text(
          DateFormat.jm().format(time),
          style: Theme.of(context).textTheme.titleLarge,
        ),
        Text(
          DateFormat.yMMMd().format(time),
          style: Theme.of(context).textTheme.bodySmall,
        ),
      ],
    );
  }

  Widget _buildSummaryRow(
    BuildContext context, {
    required IconData icon,
    required String label,
    required String value,
    Color? valueColor,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: Theme.of(context).colorScheme.primary),
          const SizedBox(width: 16),
          Text(label, style: Theme.of(context).textTheme.titleMedium),
          const Spacer(),
          Text(
            value,
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: valueColor,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFinalizedUI(BuildContext context, AttendanceEntry entry) {
    String message = 'Status for the day:';
    String status = '';

    if (entry.entryType == EntryType.wfh) {
      status = 'Work From Home';
    } else if (entry.entryType == EntryType.leave) {
      switch (entry.leaveType) {
        case LeaveType.sick:
          status = 'On Sick Leave';
          break;
        case LeaveType.annual:
          status = 'On Annual Leave';
          break;
        case LeaveType.nationalHoliday:
          status = 'National Holiday';
          break;
        case LeaveType.companyWfh:
          status = 'Company WFH';
          break;
        default:
          status = 'On Leave';
      }
    }

    return Column(
      children: [
        Text(
          message,
          style: Theme.of(context).textTheme.titleLarge,
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 16),
        Text(
          status,
          style: Theme.of(context).textTheme.headlineSmall?.copyWith(
            fontWeight: FontWeight.bold,
            color: Theme.of(context).colorScheme.primary,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildNotesCard(BuildContext context, AttendanceEntry entry) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text('Notes', style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            TextField(
              controller: _notesController,
              maxLines: 4,
              decoration: const InputDecoration(
                hintText: 'Add notes about your day...',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => _saveNotes(entry),
              child: const Text('Save Notes'),
            ),
          ],
        ),
      ),
    );
  }
}

String _formatDuration(Duration d) {
  d = d.abs();
  final hours = d.inHours;
  final minutes = d.inMinutes.remainder(60);
  return '$hours h ${minutes.toString().padLeft(2, '0')} m';
}
 