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:provider/provider.dart';

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

  @override
  State<CorrectionScreen> createState() => _CorrectionScreenState();
}

class _CorrectionScreenState extends State<CorrectionScreen> {
  DateTime _selectedDate = DateTime.now();
  AttendanceEntry? _entry;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadEntryForDate(_selectedDate);
  }

  Future<void> _pickDate() async {
    final now = DateTime.now();
    final date = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(now.year - 5),
      lastDate: now,
    );
    if (date != null) {
      _loadEntryForDate(date);
    }
  }

  Future<void> _loadEntryForDate(DateTime date) async {
    setState(() {
      _isLoading = true;
      _selectedDate = date;
    });
    final attendanceService = Provider.of<AttendanceService>(
      context,
      listen: false,
    );
    var entry = await attendanceService.getEntryForDate(date);
    entry ??= AttendanceEntry(date: date);
    setState(() {
      _entry = entry;
      _isLoading = false;
    });
  }

  Future<void> _pickTime(
    BuildContext context, {
    required bool isLoginTime,
  }) async {
    final entryTime = isLoginTime ? _entry?.loginTime : _entry?.logoutTime;
    final initialTime = entryTime != null
        ? TimeOfDay.fromDateTime(entryTime)
        : TimeOfDay.now();

    final time = await showTimePicker(
      context: context,
      initialTime: initialTime,
    );

    if (time != null) {
      final newDateTime = DateTime(
        _selectedDate.year,
        _selectedDate.month,
        _selectedDate.day,
        time.hour,
        time.minute,
      );
      setState(() {
        if (isLoginTime) {
          _entry = _entry?.copyWith(loginTime: newDateTime);
        } else {
          _entry = _entry?.copyWith(logoutTime: newDateTime);
        }
      });
    }
  }

  void _saveCorrection() {
    if (_entry != null) {
      Provider.of<AttendanceService>(
        context,
        listen: false,
      ).updateOrCreateEntry(_entry!);
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Correction saved successfully!')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Correct Attendance')),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SafeArea(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    _buildDatePicker(),
                    const SizedBox(height: 24),
                    if (_entry != null) ...[
                      _buildTypeSelector(),
                      if (_entry!.entryType == EntryType.leave) ...[
                        const SizedBox(height: 16),
                        _buildLeaveTypeSelector(),
                      ],
                      if (_entry!.entryType == EntryType.work) ...[
                        const SizedBox(height: 16),
                        _buildTimePicker('Login Time', isLoginTime: true),
                        const SizedBox(height: 16),
                        _buildTimePicker('Logout Time', isLoginTime: false),
                      ],
                      const SizedBox(height: 24),
                      ElevatedButton(
                        onPressed: _saveCorrection,
                        child: const Text('Save Correction'),
                      ),
                    ],
                  ],
                ),
              ),
            ),
    );
  }

  Widget _buildDatePicker() {
    return Card(
      child: ListTile(
        leading: const Icon(Icons.calendar_today),
        title: const Text('Selected Date'),
        subtitle: Text(DateFormat.yMMMd().format(_selectedDate)),
        trailing: const Icon(Icons.edit),
        onTap: _pickDate,
      ),
    );
  }

  Widget _buildTypeSelector() {
    return DropdownButtonFormField<EntryType>(
      value: _entry!.entryType,
      decoration: const InputDecoration(
        labelText: 'Attendance Type',
        border: OutlineInputBorder(),
      ),
      items: EntryType.values
          .map(
            (type) => DropdownMenuItem(
              value: type,
              child: Text(type.name.toUpperCase()),
            ),
          )
          .toList(),
      onChanged: (value) {
        if (value != null) {
          setState(() {
            _entry = _entry!.copyWith(entryType: value);
          });
        }
      },
    );
  }

  Widget _buildLeaveTypeSelector() {
    return DropdownButtonFormField<LeaveType>(
      value: _entry!.leaveType,
      decoration: const InputDecoration(
        labelText: 'Leave Type',
        border: OutlineInputBorder(),
      ),
      items: LeaveType.values
          .map((type) => DropdownMenuItem(value: type, child: Text(type.name)))
          .toList(),
      onChanged: (value) {
        if (value != null) {
          setState(() {
            _entry = _entry!.copyWith(leaveType: value);
          });
        }
      },
    );
  }

  Widget _buildTimePicker(String label, {required bool isLoginTime}) {
    final time = isLoginTime ? _entry?.loginTime : _entry?.logoutTime;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),
        InkWell(
          onTap: () => _pickTime(context, isLoginTime: isLoginTime),
          borderRadius: BorderRadius.circular(8),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
            decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).colorScheme.outline),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  time != null ? DateFormat.jm().format(time) : 'Not Set',
                  style: Theme.of(context).textTheme.bodyLarge,
                ),
                const Icon(Icons.access_time, color: Colors.grey),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
