import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import PlanCardSkeleton from "./PlanCardSkeleton";
import { useSubscription } from "../../hooks/useAuth";

const SubscriptionPlans = () => {
  const [plans, setPlans] = useState([]);
  const [frequency, setFrequency] = useState(1);
  const { data, isLoading, isError, error } = useSubscription(frequency);
  const [loading, setLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(true);
  console.log(data);
  const frequencyLabel = (freq) => {
    switch (freq) {
      case 0:
        return "1 mo";
      case 1:
        return "3 mo";
      case 2:
        return "6 mo";
      case 3:
        return "1 yr";
      default:
        return "mo";
    }
  };

  return (
    <div className="container py-5">
      {/* Frequency Switcher */}
      <div className="text-center mb-4">
        <div className="btn-group" role="group" aria-label="Plan frequency">
          {["Monthly", "Quarterly", "Half-Yearly", "Yearly"].map(
            (label, idx) => (
              <button
                key={idx}
                type="button"
                className={`btn btn-${frequency === idx ? "primary" : "outline-secondary"
                  }`}
                onClick={() => setFrequency(idx)}
              >
                {label}
              </button>
            )
          )}
        </div>
      </div>

      {/* Cards */}
      <div className="row g-4 mt-10">
        {isLoading ? (
          // Show 3 skeletons
          <>
            <PlanCardSkeleton />
            <PlanCardSkeleton />
            <PlanCardSkeleton />
          </>
        ) : data?.length === 0 ? (
          <div className="text-center">No plans found</div>
        ) : isError ? (
          <div className="text-start bg-light">
            <p>{error.message}</p>
            <p>{error.name}</p>
          </div>
        ) : (
          data.map((plan, index) => (
            <div key={plan.id} className="col-xl-4 col-lg-6 col-md-6">
              <div className="card h-100 shadow-lg border-0 p-3 text-center p-10">
                {/* Header */}
                <div className="mb-3">
                  <i className="bx bxs-package text-primary fs-1 mb-2"></i>
                  <p className="card-title fs-3 fw-bold mb-1">
                    {plan.planName}
                  </p>
                  <p className="text-muted mb-0 fs-5">{plan.description}</p>
                </div>

                {/* Price */}
                <div className="mb-3">
                  <h4 className="fw-semibold mt-auto mb-0 fs-3">
                    {plan.currency?.symbol} {plan.price}
                    <small className="text-muted ms-1">
                      / {frequencyLabel(frequency)}
                    </small>
                  </h4>
                </div>

                {/* Storage & Trial */}
                <div className="text-muted mb-5 d-flex justify-content-center gap-4">
                  <div>
                    <i className="fa-solid fa-hdd me-2"></i>
                    Storage {plan.maxStorage} MB
                  </div>
                  <div>
                    <i className="fa-regular fa-calendar-check text-success me-2"></i>
                    Trial Days {plan.trialDays}
                  </div>
                </div>

                {/* Features */}
                <h6 className="fw-bold text-uppercase border-top pt-3 mb-3 text-center">
                  Features
                </h6>

                <div className="accordion" id={`planFeatures-${plan.id}`}>
                  {plan.features?.modules &&
                    Object.entries(plan.features.modules)
                      .sort(([, a], [, b]) => Number(b.enabled) - Number(a.enabled))
                      .map(([key, mod]) => {

                        if (!mod || !mod.name) return null;
                        const isFirst = index === 0;

                        return (
                          <div className="accordion-item mb-2" key={`${plan.id}-${mod.id}`}>
                            <h2 id={`heading-${plan.id}-${mod.id}`} className="accordion-header">
                              <button
                                className="accordion-button py-2 d-flex justify-content-between align-items-center"
                                type="button"
                                data-bs-toggle="collapse"
                                data-bs-target={`#collapse-${plan.id}-${mod.id}`}
                                aria-expanded={`${isFirst ? "true" : "false"}`}
                                aria-controls={`collapse-${plan.id}-${mod.id}`}
                              >
                                <span className="fw-semibold d-flex align-items-center">
                                  {mod.enabled ? (
                                    <i className="fa-regular fa-circle-check text-success me-2"></i>
                                  ) : (
                                    <i className="fa-regular fa-circle-xmark text-danger me-2"></i>
                                  )}
                                  {mod.name}
                                </span>

                                <i className="bx bx-chevron-down ms-2"></i>
                              </button>
                            </h2>

                            <div
                              id={`collapse-${plan.id}-${mod.id}`}
                              className={`accordion-collapse collapse ${isFirst ? "show" : ""}`}
                              aria-labelledby={`heading-${plan.id}-${mod.id}`}
                            >
                              <div className="accordion-body py-2">
                                {mod.features?.length > 0 ? (
                                  <ul className="list-unstyled ms-2">
                                    {mod.features.map((feat) => (
                                      <li key={feat.id} className="d-flex align-items-start mb-1">
                                        <i
                                          className={`bx bxs-circle ${mod.enabled ? "text-success" : "text-danger"
                                            } me-2 mt-1`}
                                          style={{ fontSize: "8px" }}
                                        ></i>
                                        <span>{feat.name}</span>
                                      </li>
                                    ))}
                                  </ul>
                                ) : (
                                  <p className="text-muted small mb-0">No additional features</p>
                                )}
                              </div>
                            </div>
                          </div>

                        );
                      })}
                </div>

                {/* Button */}
                <div className="mt-auto">
                  <Link
                    to={`/auth/subscripe/${frequency}/${plan.id}`}
                    className="btn btn-green btn-square-small w-100 fw-bold mb-2"
                  >
                    Subscribe
                  </Link>
                  <Link
                    to="/auth/reqest/demo"
                    className="btn btn-outline-success w-100 fw-bold"
                  >
                    Request a Demo
                  </Link>
                </div>
              </div>
            </div>

          ))
        )}
      </div>
    </div>
  );
};

export default SubscriptionPlans;
