import { useEffect, useRef, useState } from 'react';
import { useGetBasketQuery } from '@akinon/next/data/client/basket';
import { checkoutApi } from '@akinon/next/data/client/checkout';
import { useAppDispatch } from '@akinon/next/redux/hooks';
import { useLocalization } from '@akinon/next/hooks';
import PluginModule, { Component } from '@akinon/next/components/plugin-module';
import { BasketItem } from '@theme/views/basket';
import { Icon, Link, Button, LoaderSpinner } from '@theme/components';
import { ROUTES } from '@theme/routes';
import settings from '@theme/settings';

const BasketSection = () => {
  const { t } = useLocalization();
  const dispatch = useAppDispatch();
  const { data: basket, isLoading, isSuccess } = useGetBasketQuery();
  const [collapsed, setCollapsed] = useState(false);

  const multiBasket = (settings as { plugins?: { multiBasket?: boolean } })
    ?.plugins?.multiBasket ?? false;

  const totalQuantity = basket?.total_quantity ?? 0;
  const totalAmount = basket?.total_amount ?? '0';
  const initialSnapshotRef = useRef<{
    qty: number;
    amount: string;
  } | null>(null);

  useEffect(() => {
    if (!isSuccess) return;
    if (initialSnapshotRef.current === null) {
      initialSnapshotRef.current = { qty: totalQuantity, amount: totalAmount };
      return;
    }
    const prev = initialSnapshotRef.current;
    if (prev.qty !== totalQuantity || prev.amount !== totalAmount) {
      initialSnapshotRef.current = { qty: totalQuantity, amount: totalAmount };
      dispatch(checkoutApi.util.invalidateTags(['Checkout']));
    }
  }, [isSuccess, totalQuantity, totalAmount, dispatch]);

  if (isLoading) {
    return (
      <section
        className="mb-5 rounded-2xl bg-white py-10 shadow-[0_2px_8px_-4px_rgba(0,0,0,0.06)] ring-1 ring-black/[0.04]"
        data-testid="basket-section-loading"
      >
        <div className="flex justify-center">
          <LoaderSpinner />
        </div>
      </section>
    );
  }

  if (
    isSuccess &&
    (!basket?.basketitem_set || basket.basketitem_set.length === 0)
  ) {
    return (
      <section
        className="mb-5 rounded-2xl border-2 border-dashed border-gray-200 bg-white px-6 py-12 text-center"
        data-testid="basket-section-empty"
      >
        <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-gray-100">
          <Icon
            name="basket"
            size={24}
            className="fill-gray-500"
            aria-hidden="true"
          />
        </div>
        <h2 className="mb-2 text-lg font-semibold text-black-800">
          {t('basket.empty.title')}
        </h2>
        <p className="mb-5 text-sm text-gray-600">
          {t('basket.empty.content_first')}
        </p>
        <Link href={ROUTES.HOME} passHref>
          <Button
            appearance="filled"
            className="px-6"
            data-testid="basket-section-empty-cta"
          >
            {t('basket.empty.button')}
          </Button>
        </Link>
      </section>
    );
  }

  if (!basket) return null;

  const itemCount = basket.basketitem_set.length;

  return (
    <section
      className="mb-5 overflow-hidden rounded-2xl bg-white shadow-[0_2px_8px_-4px_rgba(0,0,0,0.06)] ring-1 ring-black/[0.04]"
      data-testid="basket-section"
    >
      <header className="flex items-center justify-between gap-3 px-6 py-5 sm:px-7">
        <div className="flex items-baseline gap-3">
          <h2 className="text-base font-semibold leading-tight text-black-800 sm:text-lg">
            {t('checkout.one_page.basket.title')}
          </h2>
          <span className="text-[11px] font-medium uppercase tracking-wider text-gray-500">
            {itemCount} {t('checkout.summary.items')}
          </span>
        </div>
        <button
          type="button"
          onClick={() => setCollapsed((prev) => !prev)}
          aria-expanded={!collapsed}
          aria-controls="basket-section-content"
          className="rounded-lg px-3 py-1.5 text-xs font-medium text-gray-700 transition-all hover:bg-gray-100 hover:text-black-800 focus:outline-none focus-visible:ring-2 focus-visible:ring-secondary"
          data-testid="basket-section-toggle"
        >
          {collapsed
            ? t('checkout.one_page.basket.show')
            : t('checkout.one_page.basket.hide')}
        </button>
      </header>

      {!collapsed && (
        <div
          id="basket-section-content"
          className="max-h-[28rem] overflow-y-auto border-t border-gray-100 px-6 sm:px-7"
        >
          <ul>
            {multiBasket ? (
              <PluginModule
                component={Component.MultiBasket}
                props={{ BasketItem }}
              />
            ) : (
              basket.basketitem_set.map((basketItem, index) => (
                <BasketItem
                  basketItem={basketItem}
                  namespace={basket.namespace}
                  key={`${basketItem.id}-${index}`}
                />
              ))
            )}
          </ul>
        </div>
      )}
    </section>
  );
};

export default BasketSection;
