import 'package:flutter/material.dart';
import 'package:lucide_icons/lucide_icons.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/theme/design_tokens.dart';
import '../../data/services/mock_calendar_service.dart';
import '../../data/models/schedule_item_model.dart';
import '../widgets/create_event_sheet.dart';

class CalendarEventDetailScreen extends StatefulWidget {
  final String eventId;

  const CalendarEventDetailScreen({super.key, required this.eventId});

  @override
  State<CalendarEventDetailScreen> createState() =>
      _CalendarEventDetailScreenState();
}

class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
  ScheduleItemModel? _event;

  @override
  void initState() {
    super.initState();
    _loadEvent();
  }

  void _loadEvent() {
    try {
      _event = CalendarService().getEventById(widget.eventId);
    } catch (e) {
      _event = null;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (_event == null) {
      return Scaffold(
        backgroundColor: const Color(0xFFF8FAFC),
        body: SafeArea(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'Event not found',
                  style: TextStyle(color: AppColors.slate600),
                ),
                const SizedBox(height: 16),
                GestureDetector(
                  onTap: () => context.pop(),
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.blue600,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: const Text(
                      '返回',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    final event = _event!;
    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      body: SafeArea(
        child: Column(
          children: [
            _buildHeader(context),
            Expanded(child: _buildDetailOverlay(event)),
            _buildInputContainer(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return SizedBox(
      height: 64,
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 8),
        child: Row(
          children: [
            GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child: Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: const Color(0xFFF8FAFF),
                  borderRadius: BorderRadius.circular(18),
                  border: Border.all(color: const Color(0xFFDEE7F6)),
                ),
                child: const Icon(
                  LucideIcons.chevronLeft,
                  size: 16,
                  color: AppColors.slate700,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailOverlay(ScheduleItemModel event) {
    final startAt = event.startAt;
    final endAt = event.endAt;
    final dateStr =
        '${startAt.year}年${startAt.month}月${startAt.day}日 ${_getWeekday(startAt.weekday)}';
    final timeStr = endAt != null
        ? '${_formatTime(startAt)} - ${_formatTime(endAt)}'
        : _formatTime(startAt);

    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 12),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24),
          border: Border.all(color: const Color(0xFFD8E3F5)),
        ),
        child: SingleChildScrollView(
          child: SizedBox(
            width: double.infinity,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildTitleRow(event),
                const SizedBox(height: 14),
                Container(height: 1, color: const Color(0xFFE5E7EB)),
                const SizedBox(height: 14),
                _buildDetailField('日期', dateStr),
                const SizedBox(height: 14),
                _buildDetailField('时间范围', timeStr),
                const SizedBox(height: 14),
                _buildDetailField('提醒时间', '开始前30分钟'),
                const SizedBox(height: 14),
                _buildColorField(event.metadata?.color),
                const SizedBox(height: 14),
                if (event.metadata?.location != null) ...[
                  _buildDetailField('地点', event.metadata!.location!),
                  const SizedBox(height: 14),
                ],
                if (event.description != null) ...[
                  _buildDetailField('描述', event.description!),
                  const SizedBox(height: 14),
                ],
                if (event.metadata?.notes != null) ...[
                  _buildNotesField(event.metadata!.notes!),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  String _getWeekday(int weekday) {
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    return weekdays[weekday - 1];
  }

  String _formatTime(DateTime time) {
    return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  }

  Widget _buildTitleRow(ScheduleItemModel event) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Row(
            children: [
              Container(
                width: 4,
                height: 20,
                decoration: BoxDecoration(
                  color: _parseColor(event.metadata?.color),
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              const SizedBox(width: 10),
              Flexible(
                child: Text(
                  event.title,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w700,
                    color: AppColors.slate900,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
        Row(
          children: [
            GestureDetector(
              onTap: () => CreateEventSheet.edit(
                context,
                event,
                onSaved: () {
                  setState(() {
                    _loadEvent();
                  });
                },
              ),
              child: Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: const Color(0xFFF8FAFF),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: const Color(0xFFDCE5F4)),
                ),
                child: const Icon(
                  LucideIcons.pencil,
                  size: 18,
                  color: AppColors.slate600,
                ),
              ),
            ),
            const SizedBox(width: 8),
            GestureDetector(
              onTap: _showDeleteConfirmation,
              child: Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: const Color(0xFFFFF1F2),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: const Color(0xFFFECACA)),
                ),
                child: const Icon(
                  LucideIcons.trash2,
                  size: 18,
                  color: AppColors.red500,
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除日程'),
        content: const Text('确定要删除这个日程吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              CalendarService().deleteEvent(widget.eventId);
              Navigator.pop(context);
              context.pop();
            },
            child: Text('删除', style: TextStyle(color: AppColors.red500)),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailField(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: AppColors.slate400,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 15,
            fontWeight: FontWeight.w600,
            color: AppColors.slate900,
          ),
        ),
      ],
    );
  }

  Widget _buildColorField(String? colorHex) {
    final color = _parseColor(colorHex);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '日程颜色',
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: AppColors.slate400,
          ),
        ),
        const SizedBox(height: 6),
        Row(
          children: [
            Container(
              width: 28,
              height: 28,
              decoration: BoxDecoration(color: color, shape: BoxShape.circle),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildNotesField(String notes) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '备注',
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: AppColors.slate400,
          ),
        ),
        const SizedBox(height: 6),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: const Color(0xFFFDFEFF),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: const Color(0xFFDCE5F4)),
          ),
          child: Text(
            notes,
            style: const TextStyle(fontSize: 14, color: AppColors.slate700),
          ),
        ),
      ],
    );
  }

  Color _parseColor(String? hex) {
    if (hex == null || hex.isEmpty) return AppColors.blue600;
    try {
      return Color(int.parse(hex.replaceFirst('#', '0xFF')));
    } catch (_) {
      return AppColors.blue600;
    }
  }

  Widget _buildInputContainer() {
    return Container(
      height: 80,
      padding: const EdgeInsets.all(16),
      color: const Color(0xFFF8FAFC),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(18),
              border: Border.all(color: const Color(0xFFDCE5F4)),
            ),
            child: const Icon(
              LucideIcons.plus,
              size: 20,
              color: AppColors.slate500,
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Container(
              height: 48,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(24),
              ),
              child: Row(
                children: [
                  const Expanded(
                    child: Text(
                      '输入消息...',
                      style: TextStyle(fontSize: 14, color: AppColors.slate400),
                    ),
                  ),
                  const Icon(
                    LucideIcons.mic,
                    size: 20,
                    color: AppColors.slate500,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
