"use client";

import React, { ReactNode } from "react";
import { DynamicTabT } from "./types";
import { AnimatePresence, motion } from "framer-motion";

import { MaterialIcon } from "@shared/components/material-icon";
import { Button } from "@shared/contentful/blocks/button";
import { cx } from "@shared/utils";

export interface OrderedTabViewProps {
  items: DynamicTabT[];
  currentTabIndex: number;
  subitemColCount: number;
  onTabClick: (index: number, anchor: string) => void;
}

export interface OrderedAccordionViewProps extends OrderedTabViewProps {
  setCurrentTabIndex: (index: number) => void;
}

// Renders a tab's `tabContent` nodes arranged into `subitemColCount` columns.
export function renderOrderedChildren(
  content: ReactNode,
  subitemColCount: number
) {
  const children = Array.isArray(content) ? content : [content];
  const colCount = Math.min(subitemColCount, children.length);

  return (
    <div className="flex flex-col py-7">
      <div className="flex shrink-0 basis-0 flex-row gap-16 md:gap-20">
        {[...new Array(colCount)].map((_, colIdx) => (
          <ul
            key={`ordered-col-${colIdx}`}
            className="flex flex-col gap-5"
            style={{ width: "172px" }}
          >
            {children
              .slice(
                colIdx * Math.ceil(children.length / colCount),
                (colIdx + 1) * Math.ceil(children.length / colCount)
              )
              .map((child, rowIdx) => (
                <li key={`ordered-item-${colIdx}-${rowIdx}`}>{child}</li>
              ))}
          </ul>
        ))}
      </div>
    </div>
  );
}

export function OrderedTabView({
  items,
  currentTabIndex,
  subitemColCount,
  onTabClick,
}: OrderedTabViewProps) {
  return (
    <>
      <div className="overflow-x-auto px-5 [-ms-overflow-style:none] [scrollbar-width:none] md:flex md:justify-center [&::-webkit-scrollbar]:hidden">
        <div className="flex w-max gap-10">
          {items.map((tab, index) => (
            <Button
              showButtonAs="unstyled"
              key={index}
              onClick={() => onTabClick(index, tab.anchorId || "")}
              buttonClassName={cx(
                "py-2 whitespace-nowrap",
                index === currentTabIndex
                  ? "label1 border-b-2 border-border-focus-secondary"
                  : "body1"
              )}
            >
              {tab.tabName}
            </Button>
          ))}
        </div>
      </div>

      {items.map((tab, index) => (
        <div key={index}>
          <AnimatePresence>
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{
                height: index === currentTabIndex ? "auto" : 0,
                opacity: index === currentTabIndex ? 1 : 0,
              }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.3 }}
              className={cx(
                "overflow-hidden",
                index === currentTabIndex ? "block" : "hidden"
              )}
              id={tab.anchorId || `tab-${index}`}
            >
              <div className="px-5 py-4 md:px-10">
                {renderOrderedChildren(tab.tabContent, subitemColCount)}
              </div>
            </motion.div>
          </AnimatePresence>
        </div>
      ))}
    </>
  );
}

export function OrderedAccordionView({
  items,
  currentTabIndex,
  subitemColCount,
  onTabClick,
  setCurrentTabIndex,
}: OrderedAccordionViewProps) {
  return (
    <div className="flex w-full flex-col">
      {items.map((tab, index) => (
        <div key={index}>
          <button
            onClick={() =>
              index === currentTabIndex
                ? setCurrentTabIndex(-1)
                : onTabClick(index, tab.anchorId || "")
            }
            className={cx(
              "flex w-full items-center justify-between px-5 py-4 text-text md:px-10",
              index === currentTabIndex ? "bg-bg-surface-hover" : ""
            )}
          >
            <span className="heading6">{tab.tabName}</span>
            <MaterialIcon
              name={
                index === currentTabIndex
                  ? "keyboard_arrow_up"
                  : "keyboard_arrow_down"
              }
              className="text-text"
              size={40}
            />
          </button>
          <AnimatePresence>
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{
                height: index === currentTabIndex ? "auto" : 0,
                opacity: index === currentTabIndex ? 1 : 0,
              }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.3 }}
              className={cx(
                "overflow-hidden",
                index === currentTabIndex ? "block" : "hidden"
              )}
              id={tab.anchorId || `tab-${index}`}
            >
              <div className="px-5 py-4 md:px-10">
                {renderOrderedChildren(tab.tabContent, subitemColCount)}
              </div>
            </motion.div>
          </AnimatePresence>
        </div>
      ))}
    </div>
  );
}

export function OrderedSidebarView({
  items,
  currentTabIndex,
  subitemColCount,
  onTabClick,
}: OrderedTabViewProps) {
  return (
    <div className="flex gap-10 px-5 py-20">
      <div className="flex-shrink-0">
        <div className="flex min-w-[320px] gap-4 rounded-[20px] border-2 px-6 py-7 shadow-lg">
          {[...new Array(Math.min(2, items.length))].map((_, colIdx) => {
            const perColumn = Math.ceil(items.length / 2);

            return (
              <div
                key={`tab-col-${colIdx}`}
                className="flex flex-1 flex-col gap-4"
              >
                {items
                  .slice(colIdx * perColumn, (colIdx + 1) * perColumn)
                  .map((tab, rowIdx) => {
                    const index = colIdx * perColumn + rowIdx;

                    return (
                      <button
                        key={index}
                        onClick={() => onTabClick(index, tab.anchorId || "")}
                        className={cx(
                          "label1 whitespace-nowrap rounded-lg px-4 py-3 text-left",
                          index === currentTabIndex
                            ? "bg-bg-inverse text-white"
                            : "text-text"
                        )}
                      >
                        {tab.tabName}
                      </button>
                    );
                  })}
              </div>
            );
          })}
        </div>
      </div>

      <div className="w-full">
        {items.map((tab, index) => (
          <div key={index}>
            <AnimatePresence>
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{
                  opacity: index === currentTabIndex ? 1 : 0,
                  y: index === currentTabIndex ? 0 : 20,
                }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.3 }}
                className={cx(
                  "overflow-hidden pl-10 xl:pl-20",
                  index === currentTabIndex ? "block" : "hidden"
                )}
                id={tab.anchorId || `tab-${index}`}
              >
                {renderOrderedChildren(tab.tabContent, subitemColCount)}
              </motion.div>
            </AnimatePresence>
          </div>
        ))}
      </div>
    </div>
  );
}
