import 'package:flutter/material.dart';
import 'google_sheets_api.dart';
import 'pdf_generator.dart';

class ExportPage extends StatefulWidget {
  const ExportPage({super.key});

  @override
  State<ExportPage> createState() => _ExportPageState();
}

class _ExportPageState extends State<ExportPage> {
  DateTime? selectedDate;
  TimeOfDay? startTime;
  TimeOfDay? endTime;

  final sheets = GoogleSheetsApi();

  // ================= DATE =================
  Future<void> pickDate() async {
    final date = await showDatePicker(
      context: context,
      firstDate: DateTime(2024),
      lastDate: DateTime.now(),
      initialDate: DateTime.now(),
    );
    if (date != null) {
      setState(() => selectedDate = date);
    }
  }

  // ================= HEURES =================
  Future<void> pickStartTime() async {
    final time = await showTimePicker(
      context: context,
      initialTime: const TimeOfDay(hour: 8, minute: 0),
    );
    if (time != null) setState(() => startTime = time);
  }

  Future<void> pickEndTime() async {
    final time = await showTimePicker(
      context: context,
      initialTime: const TimeOfDay(hour: 18, minute: 0),
    );
    if (time != null) setState(() => endTime = time);
  }

  // ================= EXPORT =================
  Future<void> export() async {
    if (selectedDate == null) return;

    final day = selectedDate!.toIso8601String().split('T')[0];

    final rawData = await sheets.getAllPresences();
    final List<Map<String, String>> filtered = [];

    for (final row in rawData) {
      final datesStr = row['date_ajout'];
      if (datesStr == null || datesStr.isEmpty) continue;

      final dates = datesStr.split(';');

      for (final d in dates) {
        final dateTime = DateTime.tryParse(d.trim());
        if (dateTime == null) continue;

        //  filtre date
        if (!dateTime.toIso8601String().startsWith(day)) continue;

        final t = TimeOfDay.fromDateTime(dateTime);

        final afterStart = startTime == null ||
            (t.hour > startTime!.hour ||
                (t.hour == startTime!.hour &&
                    t.minute >= startTime!.minute));

        final beforeEnd = endTime == null ||
            (t.hour < endTime!.hour ||
                (t.hour == endTime!.hour &&
                    t.minute <= endTime!.minute));

        if (afterStart && beforeEnd) {
          filtered.add({
            ...row,
            'date_ajout': d.trim(),
          });
        }
      }
    }

    if (filtered.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Aucune donnée pour ce filtre")),
      );
      return;
    }

    await generatePdf(
      filtered,
      "$day ${startTime?.format(context) ?? ''}-${endTime?.format(context) ?? ''}",
    );

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text("PDF généré avec succès ✅")),
    );
  }

  // ================= UI =================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Exporter présence")),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(
              onPressed: pickDate,
              child: const Text("Choisir une date"),
            ),
            if (selectedDate != null)
              Text("Date : ${selectedDate!.toString().substring(0, 10)}"),

            const SizedBox(height: 16),

            ElevatedButton(
              onPressed: pickStartTime,
              child: const Text("Heure début"),
            ),
            if (startTime != null)
              Text("De : ${startTime!.format(context)}"),

            const SizedBox(height: 8),

            ElevatedButton(
              onPressed: pickEndTime,
              child: const Text("Heure fin"),
            ),
            if (endTime != null)
              Text("À : ${endTime!.format(context)}"),

            const SizedBox(height: 24),

            ElevatedButton(
              onPressed: selectedDate == null ? null : export,
              child: const Text("Générer le PDF"),
            ),
          ],
        ),
      ),
    );
  }
}
