"use client";

import React, { useEffect } from "react";
import { Product } from "@/types";
import PriceCard from "@/components/PriceCard";
import { useState } from "react";
import PriceToggle from "@/components/PriceToggle";
import { apiPrices } from "../app/(admin)/pricing/actions";

const Payment = ({
  type = "one_time",
}: {
  type?: "one_time" | "reoccuring";
}) => {
  const [isAnnual, setIsAnnual] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const handleToggle = () => {
    setIsAnnual((prev) => !prev);
  };
  useEffect(() => {
    setIsLoading(true);
    (async () => {
      const resposeProducts: Product[] = await apiPrices();
      setProducts(resposeProducts);
      setIsLoading(false);
    })();
  }, []);
  return (
    <>
      {!(type == "one_time") && (
        <div className="flex items-center justify-center mt-10">
          <PriceToggle isAnnual={isAnnual} onChange={handleToggle} />
        </div>
      )}
      <div className="max-w-6xl mx-auto  mb-24 h-full">
        <div
          className={`w-screen lg:w-full flex gap-x-4 lg:justify-center gap-y-8 px-6  pt-12 overflow-x-scroll`}
        >
          {isLoading ? (
            <>
              <PriceCard loading={isLoading} />
              <PriceCard loading={isLoading} />
              <PriceCard loading={isLoading} />
            </>
          ) : (
            products
              .filter((x) =>
                type == "one_time" ? x.type == "one_time" : x.type != "one_time"
              )
              .map((x, i) => (
                <PriceCard key={i} product={x} isAnnual={isAnnual} />
              ))
          )}
        </div>
      </div>
    </>
  );
};

export default Payment;
