"use client";

import { Button } from "@/components/ui/button";
import { subScriptionList } from "@/components/profile/profile.type";
import {
  useGetSubScriptionList,
  useSubscriptionCoin,
} from "@/state/profile/profile.action";
import { useSettingsStore } from "@/state/store/settings.store";
import { Check, Coins } from "lucide-react";
import { useSession } from "next-auth/react";
import React from "react";

const PLAN_SKELETON_COUNT = 3;

const parseFeatures = (plan: subScriptionList) =>
  (plan?.description ?? "")
    .split(/\r?\n|,|·/)
    .map((feature) => feature.trim())
    .filter(Boolean);

const Pricing = () => {
  const { data: session } = useSession();
  const { setIsSocialOpen } = useSettingsStore();

  const { data: plans = [], isLoading } = useGetSubScriptionList(true);
  const { mutate: createSubscription, isPending } = useSubscriptionCoin();

  const handleSubscribe = (plan: subScriptionList) => {
    if (!session?.user?.id) {
      setIsSocialOpen(true);
      return;
    }

    createSubscription({ subscriptionId: plan?.subscription_id ?? plan?.id });
  };

  return (
    <section
      id="pricing"
      className="scroll-mt-24 border-y border-white/10 bg-[#100a0d] py-24 md:py-32"
    >
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <p className="text-xs font-bold uppercase tracking-[0.24em] text-[#ED3A57]">
          Pricing
        </p>
        <div className="mt-3 flex flex-wrap items-end justify-between gap-6">
          <h2 className="max-w-2xl text-[36px] md:text-[48px] font-extrabold leading-[1.1] tracking-tight text-white">
            One price. The whole ReelFlix library.
          </h2>
          <p className="flex max-w-sm items-start gap-3 text-sm leading-relaxed text-gray-400">
            <Coins
              className="mt-0.5 h-4 w-4 shrink-0 text-[#ED3A57]"
              aria-hidden="true"
            />
            Other apps make you buy coins to unlock episode 14. We think a
            cliffhanger should never be a checkout screen.
          </p>
        </div>

        {isLoading ? (
          <div className="mt-12 grid gap-5 lg:grid-cols-3">
            {Array.from({ length: PLAN_SKELETON_COUNT })?.map((_, index) => (
              <div
                key={index}
                className="h-[420px] animate-pulse rounded-2xl bg-gray-800"
              />
            ))}
          </div>
        ) : plans.length === 0 ? (
          <p className="mt-12 rounded-2xl border border-dashed border-white/15 bg-[#141014] p-12 text-center text-sm text-gray-400">
            Plans are being updated. Check back shortly.
          </p>
        ) : (
          <div className="mt-12 grid gap-5 lg:grid-cols-3">
            {plans?.map((plan, index) => {
              const isFeatured = plans.length > 1 && index === 1;
              const features = parseFeatures(plan);

              return (
                <div
                  key={plan?.subscription_id ?? plan?.id ?? index}
                  className={`relative flex h-full flex-col rounded-2xl border p-7 ${
                    isFeatured
                      ? "border-[#ED3A57] bg-[#141014] shadow-[0_0_0_1px_rgba(232,40,75,0.35),0_24px_60px_-24px_rgba(232,40,75,0.35)]"
                      : "border-white/10 bg-[#141014]/60"
                  }`}
                >
                  {isFeatured && (
                    <span className="absolute -top-3 left-7 rounded-full bg-[#ED3A57] px-3 py-1 text-[11px] font-bold uppercase tracking-wide text-white">
                      Most popular
                    </span>
                  )}

                  <h3 className="text-[18px] font-semibold text-white">
                    {plan?.subscription_name}
                  </h3>
                  <p className="mt-3 flex items-baseline gap-2">
                    <span className="text-[36px] font-extrabold tabular-nums text-white">
                      ${plan?.price}
                    </span>
                  </p>

                  <ul className="mt-6 flex-1 space-y-3">
                    {features?.map((feature) => (
                      <li
                        key={feature}
                        className="flex items-start gap-3 text-sm text-gray-300"
                      >
                        <Check
                          className="mt-0.5 h-4 w-4 shrink-0 text-[#ED3A57]"
                          aria-hidden="true"
                        />
                        {feature}
                      </li>
                    ))}
                  </ul>

                  <Button
                    disabled={isPending}
                    onClick={() => handleSubscribe(plan)}
                    className={`mt-7 h-11 w-full cursor-pointer transition-transform active:scale-[0.98] ${
                      isFeatured
                        ? "border border-[#E50914] bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E] text-white hover:from-[#c72a40] hover:via-[#c72a40] hover:to-[#e03d1a]"
                        : "border border-white/15 bg-transparent text-white hover:bg-white/10"
                    }`}
                  >
                    {session?.user?.id ? "Subscribe" : "Sign in to subscribe"}
                  </Button>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </section>
  );
};

export default Pricing;
