import 'package:flutter/material.dart';
import '../common/settings.dart';

class PlanDetails extends StatefulWidget {
  final Map<String, dynamic> plan;

  const PlanDetails({super.key, required this.plan});

  @override
  State<PlanDetails> createState() => _PlanDetailsState();
}

class _PlanDetailsState extends State<PlanDetails> {
  late List<Map<String, dynamic>> deliveryDates;

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

    // 🔥 Now expecting:
    // "dates": [
    //   { "date": "2026-02-10", "status": "scheduled" }
    // ]

    deliveryDates =
    List<Map<String, dynamic>>.from(widget.plan["dates"] ?? []);
  }

  // ================= INFO CARD =================
  Widget _buildInfoCard(String value, String label, {Color? bg}) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: bg ?? const Color(0xFFF7F7F7),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          children: [
            Text(value,
                style: fontTextStyle(18, Colors.black, FontWeight.w600)),
            const SizedBox(height: 4),
            Text(label,
                style: fontTextStyle(13, Colors.black54, FontWeight.w400)),
          ],
        ),
      ),
    );
  }

  // ================= DELIVERY CARD =================
  Widget _buildDeliveryCard(Map<String, dynamic> delivery) {
    DateTime date = DateTime.parse(delivery["date"]);
    String status = delivery["status"] ?? "scheduled";

    String buttonText = "";
    bool showButton = false;

    Color statusBg;
    Color statusText;

    switch (status) {
      case "completed":
        statusBg = Colors.green.withOpacity(0.15);
        statusText = Colors.green;
        break;

      case "rescheduled":
        statusBg = Colors.purple.withOpacity(0.15);
        statusText = Colors.purple;
        buttonText = "View Details";
        showButton = true;
        break;

      case "in-progress":
        statusBg = Colors.blue.withOpacity(0.15);
        statusText = Colors.blue;
        buttonText = "Track Order";
        showButton = true;
        break;

      default: // scheduled
        statusBg = Colors.orange.withOpacity(0.15);
        statusText = Colors.orange;
        buttonText = "Assign Tanker";
        showButton = false;
    }

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border.all(color: const Color(0xFFE0E0E0)),
        borderRadius: BorderRadius.circular(12),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding:
                const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: statusBg,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  status.toUpperCase(),
                  style:
                  fontTextStyle(12, statusText, FontWeight.w600),
                ),
              ),
              const Spacer(),
              Text(
                "${date.day}-${date.month}-${date.year}",
                style: fontTextStyle(
                    12, Colors.black54, FontWeight.w400),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            "${widget.plan["capacity"]} - ${widget.plan["type_of_water"]}",
            style: fontTextStyle(14, Colors.black, FontWeight.w600),
          ),
          const SizedBox(height: 10),
          if (showButton)
            Align(
              alignment: Alignment.centerRight,
              child: ElevatedButton(
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF8270DB),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                child: Text(
                  buttonText,
                  style:
                  fontTextStyle(13, Colors.white, FontWeight.w600),
                ),
              ),
            ),
        ],
      ),
    );
  }

  // ================= BUILD =================
  @override
  Widget build(BuildContext context) {
    final plan = widget.plan;

    final int totalDeliveries = deliveryDates.length;

    final int pendingCount = deliveryDates
        .where((d) => d["status"] == "scheduled")
        .length;

    final int rescheduledCount = deliveryDates
        .where((d) => d["status"] == "rescheduled")
        .length;

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon:
          const Icon(Icons.arrow_back_ios_new, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          "Plan Details",
          style: fontTextStyle(16, Colors.black, FontWeight.w600),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // IMAGE HEADER
            Stack(
              children: [
                Image.asset(
                  'images/building.png',
                  height: 180,
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
                Positioned(
                  top: 16,
                  left: 16,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.green,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      "Active",
                      style: fontTextStyle(
                          12, Colors.white, FontWeight.w600),
                    ),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // PLAN SUMMARY
            Column(
              children: [
                Text(plan["customerId"],
                    style: fontTextStyle(
                        18, Colors.black, FontWeight.w600)),
                const SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.water_drop,
                        size: 16, color: Color(0xFF8270DB)),
                    const SizedBox(width: 4),
                    Text(plan["type_of_water"],
                        style: fontTextStyle(
                            14,
                            const Color(0xFF8270DB),
                            FontWeight.w500)),
                  ],
                ),
                const SizedBox(height: 4),
                Text(
                  "${plan["start_date"]} • $totalDeliveries deliveries",
                  style: fontTextStyle(
                      13, Colors.black54, FontWeight.w400),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // INFO ROWS
            Padding(
              padding:
              const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  _buildInfoCard(plan["capacity"], "Quantity"),
                  const SizedBox(width: 12),
                  _buildInfoCard(
                    "₹${plan["my_supplier"]["quoted_amount"]}",
                    "Balance",
                    bg: const Color(0xFFEFF8F1),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 16),

            Padding(
              padding:
              const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  _buildInfoCard("${plan["frequencyDisplay"] ?? "0"}/week", "Schedule"),
                  const SizedBox(width: 12),
                  _buildInfoCard("$pendingCount", "Pending"),
                  const SizedBox(width: 12),
                  _buildInfoCard(
                      "$rescheduledCount", "Rescheduled"),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // DELIVERY LIST
            ...deliveryDates.map(_buildDeliveryCard).toList(),

            const SizedBox(height: 24),

            // BOTTOM BUTTONS
           /* Padding(
              padding:
              const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () {},
                      style: OutlinedButton.styleFrom(
                        side: const BorderSide(
                            color: Color(0xFF8270DB)),
                        shape: RoundedRectangleBorder(
                          borderRadius:
                          BorderRadius.circular(24),
                        ),
                        padding:
                        const EdgeInsets.symmetric(
                            vertical: 14),
                      ),
                      child: Text(
                        "Edit Plan",
                        style: fontTextStyle(
                            14,
                            const Color(0xFF8270DB),
                            FontWeight.w600),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {},
                      style: ElevatedButton.styleFrom(
                        backgroundColor:
                        const Color(0xFFE2483D),
                        shape: RoundedRectangleBorder(
                          borderRadius:
                          BorderRadius.circular(24),
                        ),
                        padding:
                        const EdgeInsets.symmetric(
                            vertical: 14),
                      ),
                      child: Text(
                        "Discontinue",
                        style: fontTextStyle(
                            14,
                            Colors.white,
                            FontWeight.w600),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 24),*/
          ],
        ),
      ),
    );
  }
}
