import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:eanapo/widgets/DatabaseHelper.dart';
import 'package:eanapo/widgets/MessageDetailScreen.dart'; // 수정된 경로 확인
import 'dart:io';

class ScheduleScreen extends StatefulWidget {
  @override
  _ScheduleScreenState createState() => _ScheduleScreenState();
}

class _ScheduleScreenState extends State<ScheduleScreen> {
  Map<DateTime, List<Map<String, dynamic>>> _events = {};
  DateTime _selectedDay = DateTime.now();

  @override
  void initState() {
    super.initState();
    _loadEvents(DateTime.now());
  }

  Future<void> _loadEvents(DateTime date) async {
    final dbHelper = DatabaseHelper.instance;
    final formattedDate = date.toIso8601String().split('T').first;

    final data = await dbHelper.getLastDataByDate(formattedDate);
    final images = await dbHelper.getImagesByDate(formattedDate);

    setState(() {
      _events[date] = [
        ...data.map((entry) => {
              'type': 'text',
              'title': entry['title'],
              'content': entry['content'],
              'date_time': entry['date_time']
            }),
        ...images.map((entry) => {
              'type': 'image',
              'title': entry['title'],
              'path': entry['path'],
              'date_time': entry['date_time']
            })
      ];
    });
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    setState(() {
      _selectedDay = selectedDay;
    });
    _loadEvents(selectedDay);
  }

  void _viewMessageDetails(Map<String, dynamic> message) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MessageDetailScreen(message: message),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('일정 관리'),
        backgroundColor: Colors.blue[100],
      ),
      body: Column(
        children: [
          TableCalendar(
            focusedDay: _selectedDay,
            firstDay: DateTime.utc(2010, 10, 16),
            lastDay: DateTime.utc(2030, 3, 14),
            selectedDayPredicate: (day) => isSameDay(day, _selectedDay),
            onDaySelected: _onDaySelected,
            eventLoader: (day) => _events[day] ?? [],
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _events[_selectedDay]?.length ?? 0,
              itemBuilder: (context, index) {
                final message = _events[_selectedDay]![index];
                if (message['type'] == 'text') {
                  return ListTile(
                    title: Text(message['title'] ?? 'No Title'),
                    subtitle: Text(message['content'] ?? 'No Content'),
                    onTap: () => _viewMessageDetails(message),
                  );
                } else if (message['type'] == 'image') {
                  return ListTile(
                    leading: Image.file(File(message['path'] ?? '')),
                    title: Text(message['title'] ?? 'No Title'),
                    onTap: () => _viewMessageDetails(message),
                  );
                }
                return Container();
              },
            ),
          )
        ],
      ),
    );
  }
}
