import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:taxglide/consts/comman_button.dart';
import 'package:taxglide/controller/api_contoller.dart';

class FlitterPopup {
  static void show(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return const _FilterBottomSheet();
      },
    );
  }
}

class _FilterBottomSheet extends StatefulWidget {
  const _FilterBottomSheet({Key? key}) : super(key: key);

  @override
  State<_FilterBottomSheet> createState() => _FilterBottomSheetState();
}

class _FilterBottomSheetState extends State<_FilterBottomSheet>
    with SingleTickerProviderStateMixin {
  DateTime? fromDate;
  DateTime? toDate;

  late AnimationController _controller;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 1),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> pickFromDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2020),
      lastDate: DateTime(2100),
    );

    if (picked != null) {
      setState(() => fromDate = picked);
    }
  }

  Future<void> pickToDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: fromDate ?? DateTime.now(),
      firstDate: fromDate ?? DateTime(2020),
      lastDate: DateTime(2100),
    );

    if (picked != null) {
      setState(() => toDate = picked);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: SlideTransition(
        position: _slideAnimation,
        child: Container(
          padding: const EdgeInsets.all(20),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                "Filter By Date",
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 20),

              /// FROM DATE
              InkWell(
                onTap: pickFromDate,
                child: _dateBox(title: "From Date", value: fromDate),
              ),

              const SizedBox(height: 12),

              /// TO DATE
              InkWell(
                onTap: pickToDate,
                child: _dateBox(title: "To Date", value: toDate),
              ),

              const SizedBox(height: 20),

              Row(
                children: [
                  Expanded(
                    child: SizedBox(
                      width: double.infinity,
                      height: 57,
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(
                            0xFFF7E9FF,
                          ), // ✅ background
                          elevation: 6, // ✅ shadow depth
                          shadowColor: const Color(
                            0x40000000,
                          ), // ✅ shadow color
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6), // ✅ radius
                            side: const BorderSide(
                              color: Color(0xFFD39FEA), // ✅ border color
                              width: 1, // ✅ border width
                            ),
                          ),
                        ),
                        child: const Text(
                          "Cancel",
                          style: TextStyle(
                            fontFamily: "Gilroy-SemiBold", // ✅ Font
                            fontWeight: FontWeight.w400,
                            fontSize: 16,
                            height: 1.3, // ✅ line-height 130%
                            letterSpacing: 0.64, // ✅ 4%
                            color: Color(0xFF61277A), // ✅ text color
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Consumer(
                      builder: (context, ref, _) {
                        return CommanButton(
                          text: 'Submit',
                          onPressed: () {
                            final from = fromDate == null
                                ? null
                                : "${fromDate!.year}-${fromDate!.month.toString().padLeft(2, '0')}-${fromDate!.day.toString().padLeft(2, '0')}";

                            final to = toDate == null
                                ? null
                                : "${toDate!.year}-${toDate!.month.toString().padLeft(2, '0')}-${toDate!.day.toString().padLeft(2, '0')}";

                            // ✅ Apply filter to ALL TABS
                            ref
                                .read(
                                  serviceHistoryNotifierProvider(
                                    "pending",
                                  ).notifier,
                                )
                                .applyDateFilter(from: from, to: to);

                            ref
                                .read(
                                  serviceHistoryNotifierProvider(
                                    "inprogress",
                                  ).notifier,
                                )
                                .applyDateFilter(from: from, to: to);

                            ref
                                .read(
                                  serviceHistoryNotifierProvider(
                                    "completed",
                                  ).notifier,
                                )
                                .applyDateFilter(from: from, to: to);

                            ref
                                .read(
                                  serviceHistoryNotifierProvider(
                                    "cancelled",
                                  ).notifier,
                                )
                                .applyDateFilter(from: from, to: to);

                            Navigator.pop(context); // ✅ Close popup
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),

              const SizedBox(height: 10),
            ],
          ),
        ),
      ),
    );
  }

  Widget _dateBox({required String title, DateTime? value}) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            value == null ? title : "${value.day}-${value.month}-${value.year}",
            style: const TextStyle(fontSize: 14),
          ),
          const Icon(Icons.calendar_month, size: 20),
        ],
      ),
    );
  }
}
