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

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

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  @override
  void initState() {
    super.initState();
    // Use addPostFrameCallback to avoid calling provider during build
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<AttendanceService>(context, listen: false).loadHistory();
    });
  }

  Future<void> _selectDateAndNavigate() async {
    final now = DateTime.now();
    final selectedDate = await showDatePicker(
      context: context,
      initialDate: now,
      firstDate: DateTime(now.year - 5), // Allow searching up to 5 years back
      lastDate: now,
    );

    if (selectedDate == null) return; // User canceled the picker

    final attendanceService = Provider.of<AttendanceService>(
      context,
      listen: false,
    );
    final entry = await attendanceService.getEntryForDate(selectedDate);

    if (!mounted) return; // Check if the widget is still in the tree

    if (entry != null) {
      Navigator.of(
        context,
      ).pushNamed(DayDetailScreen.routeName, arguments: entry);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'No entry found for ${DateFormat.yMMMd().format(selectedDate)}',
          ),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  Future<void> _refreshHistory() async {
    await Provider.of<AttendanceService>(context, listen: false).loadHistory();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Attendance History'),
        actions: [
          IconButton(
            icon: const Icon(Icons.calendar_today),
            onPressed: _selectDateAndNavigate,
          ),
        ],
      ),
      body: SafeArea(
        child: Consumer<AttendanceService>(
          builder: (ctx, attendanceService, child) {
            final history = attendanceService.history;
            if (attendanceService.isLoading && history.isEmpty) {
              return const Center(child: CircularProgressIndicator());
            }
            if (history.isEmpty) {
              return const Center(
                child: Text(
                  'No history found.',
                  style: TextStyle(fontSize: 18),
                ),
              );
            }
            return RefreshIndicator(
              onRefresh: _refreshHistory,
              child: ListView.builder(
                padding: const EdgeInsets.all(8),
                itemCount: history.length,
                itemBuilder: (ctx, i) => _buildHistoryItem(context, history[i]),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildHistoryItem(BuildContext context, AttendanceEntry entry) {
    final dayOfWeek = DateFormat.EEEE().format(entry.date);
    final date = DateFormat.yMMMd().format(entry.date);

    String totalHours = 'N/A';
    if (entry.entryType == EntryType.work &&
        entry.loginTime != null &&
        entry.logoutTime != null) {
      final duration = entry.logoutTime!.difference(entry.loginTime!);
      totalHours = _formatDuration(duration);
    }

    final Color accentColor = entry.entryType == EntryType.work
        ? Colors.green
        : entry.entryType == EntryType.wfh
        ? Colors.blue
        : Colors.orange;

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      child: InkWell(
        onTap: () {
          Navigator.of(
            context,
          ).pushNamed(DayDetailScreen.routeName, arguments: entry);
        },
        borderRadius: BorderRadius.circular(12),
        child: Row(
          children: [
            Container(
              width: 5,
              height: 80, // Adjust height to match card content
              decoration: BoxDecoration(
                color: accentColor,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  bottomLeft: Radius.circular(12),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$date ($dayOfWeek)',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Divider(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        if (entry.loginTime != null)
                          _buildTimeColumn(
                            'Login',
                            DateFormat.jm().format(entry.loginTime!),
                            context,
                          ),
                        if (entry.logoutTime != null)
                          _buildTimeColumn(
                            'Logout',
                            DateFormat.jm().format(entry.logoutTime!),
                            context,
                          ),
                        if (entry.entryType == EntryType.work &&
                            entry.loginTime != null)
                          _buildTimeColumn(
                            'Total',
                            totalHours,
                            context,
                            isTotal: true,
                          )
                        else
                          Expanded(
                            child: Text(
                              _getLeaveTypeName(entry),
                              style: Theme.of(context).textTheme.titleMedium
                                  ?.copyWith(fontWeight: FontWeight.bold),
                              textAlign: TextAlign.center,
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTimeColumn(
    String title,
    String value,
    BuildContext context, {
    bool isTotal = false,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.labelMedium),
        const SizedBox(height: 4),
        Text(
          value,
          style: isTotal
              ? Theme.of(
                  context,
                ).textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.bold)
              : Theme.of(context).textTheme.bodyLarge,
        ),
      ],
    );
  }

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

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