import 'package:flutter/material.dart';

class PirStatusCard extends StatefulWidget {
  final bool pirDetected;

  const PirStatusCard({super.key, required this.pirDetected});

  @override
  State<PirStatusCard> createState() => _PirStatusCardState();
}

class _PirStatusCardState extends State<PirStatusCard>
    with SingleTickerProviderStateMixin {

  late AnimationController _controller;

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

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    if (widget.pirDetected) {
      _controller.repeat(reverse: true);
    }
  }

  @override
  void didUpdateWidget(covariant PirStatusCard oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (widget.pirDetected) {
      _controller.repeat(reverse: true);
    } else {
      _controller.stop();
      _controller.value = 1;
    }
  }

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

  @override
  Widget build(BuildContext context) {

    final isActive = widget.pirDetected;

    final color = isActive ? Colors.redAccent : Colors.greenAccent;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF1E293B).withOpacity(0.9),
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: Colors.white10),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.4),
            blurRadius: 12,
            offset: const Offset(0, 6),
          )
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          const Text(
            "PIR Sensor",
            style: TextStyle(color: Colors.white70),
          ),

          const SizedBox(height: 12),

          /// ICON + ANIMATION
          ScaleTransition(
            scale: Tween(begin: 1.0, end: 1.2).animate(_controller),
            child: Icon(
              Icons.directions_run,
              size: 45,
              color: color,
            ),
          ),

          const SizedBox(height: 12),

          /// STATUS TEXT
          Text(
            isActive ? "GERAKAN TERDETEKSI" : "AMAN",
            style: TextStyle(
              color: color,
              fontWeight: FontWeight.bold,
            ),
          ),

          const SizedBox(height: 6),

          /// SUBTEXT
          Text(
            isActive
                ? "Monitoring aktif"
                : "Tidak ada aktivitas",
            style: const TextStyle(
              color: Colors.white54,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}