import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../../../core/app_theme.dart';
import '../../../core/utils/cron_utils.dart';

class AddScheduleSheet extends StatefulWidget {
  final Function(TimeOfDay time, List<int> days, int durationS) onSave;

  const AddScheduleSheet({super.key, required this.onSave});

  @override
  State<AddScheduleSheet> createState() => _AddScheduleSheetState();
}

class _AddScheduleSheetState extends State<AddScheduleSheet> {
  DateTime _selectedTime = DateTime.now();
  // Set of selected days, initially all days (0 = Sunday ... 6 = Saturday)
  final Set<int> _selectedDays = {0, 1, 2, 3, 4, 5, 6};
  
  // Durasi penyiraman dalam detik
  int _durationSeconds = 30;

  // Pilihan durasi cepat
  final List<Map<String, dynamic>> _durationOptions = [
    {'label': '15s', 'value': 15},
    {'label': '30s', 'value': 30},
    {'label': '1m', 'value': 60},
    {'label': '2m', 'value': 120},
    {'label': '5m', 'value': 300},
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: AppTheme.bgPage,
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // ── Handle / Drag Indicator ──
              Center(
                child: Container(
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade300,
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
              ),
              const SizedBox(height: 24),
              
              // ── Title ──
              const Text(
                'Tambah Jadwal Penyiraman',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimary,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),

              // ── Time Picker (Wheel) ──
              SizedBox(
                height: 180,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.time,
                  initialDateTime: _selectedTime,
                  use24hFormat: true,
                  onDateTimeChanged: (DateTime newTime) {
                    setState(() {
                      _selectedTime = newTime;
                    });
                  },
                ),
              ),
              const SizedBox(height: 24),

              // ── Day Selector ──
              const Text(
                'Ulangi pada hari:',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: AppTheme.textSecondary,
                ),
              ),
              const SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: List.generate(7, (index) {
                  // Urutan hari: Sen(1), Sel(2), Rab(3), Kam(4), Jum(5), Sab(6), Min(0)
                  // Kita ubah indeks UI agar Senin di kiri, Minggu di kanan
                  final int realDayIndex = (index + 1) % 7; 
                  final isSelected = _selectedDays.contains(realDayIndex);
                  
                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        if (isSelected) {
                          // Jangan biarkan kosong, minimal 1 hari terpilih
                          if (_selectedDays.length > 1) {
                            _selectedDays.remove(realDayIndex);
                          }
                        } else {
                          _selectedDays.add(realDayIndex);
                        }
                      });
                    },
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 200),
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: isSelected ? AppTheme.primary : Colors.grey.shade200,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        CronUtils.shortDays[realDayIndex][0], // Ambil huruf pertama
                        style: TextStyle(
                          color: isSelected ? Colors.white : AppTheme.textSecondary,
                          fontWeight: FontWeight.bold,
                          fontSize: 15,
                        ),
                      ),
                    ),
                  );
                }),
              ),
              const SizedBox(height: 24),

              // ── Duration Selector ──
              const Text(
                'Lama Penyiraman:',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: AppTheme.textSecondary,
                ),
              ),
              const SizedBox(height: 12),
              Wrap(
                spacing: 10,
                runSpacing: 10,
                children: _durationOptions.map((option) {
                  final int value = option['value'];
                  final bool isSelected = _durationSeconds == value;
                  return ChoiceChip(
                    label: Text(option['label']),
                    selected: isSelected,
                    onSelected: (selected) {
                      if (selected) {
                        setState(() {
                          _durationSeconds = value;
                        });
                      }
                    },
                    selectedColor: AppTheme.primary,
                    labelStyle: TextStyle(
                      color: isSelected ? Colors.white : AppTheme.textSecondary,
                      fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                    ),
                    backgroundColor: Colors.grey.shade200,
                  );
                }).toList(),
              ),
              const SizedBox(height: 32),

              // ── Save Button ──
              ElevatedButton(
                onPressed: () {
                  widget.onSave(
                    TimeOfDay(hour: _selectedTime.hour, minute: _selectedTime.minute),
                    _selectedDays.toList(),
                    _durationSeconds,
                  );
                  Navigator.pop(context);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppTheme.primary,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                ),
                child: const Text(
                  'Simpan Jadwal',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const SizedBox(height: 10),
            ],
          ),
        ),
      ),
    );
  }
}
