"use client";

import { useState } from "react";

import { Skeleton } from "@/components/ui";
import { Chips } from "@/components/widgets";
import { useBalance } from "@/hooks/balance/useBalance";
import { useChats } from "@/providers/chats-provider";

import { CategoryChats, ChatItemsList } from "..";

const MAX_HIDE_VISIBLE_COUNT = 3;

export default function ChatCategories() {
  const { categorizedChats } = useChats();
  const { balance } = useBalance();

  const [activeChip, setActiveChip] = useState<string>("All");
  const [maxVisibleChats, setMaxVisibleChats] = useState<
    Partial<Record<string, number | null>>
  >({});

  const chips = Object.keys(categorizedChats).map(key => ({
    text: key,
  }));
  chips.unshift({
    text: "All",
  });

  const filteredChats = Object.keys(categorizedChats).filter(key => {
    if (activeChip === "All") return true;
    return categorizedChats[key].some(chat => chat.category === activeChip);
  });

  return (
    <>
      <Chips
        chips={chips}
        activeChips={[activeChip]}
        onChipClick={chip => setActiveChip(chip.text)}
      />

      {filteredChats.map(key => (
        <ChatItemsList
          title={key}
          key={key}
          viewAllProps={{
            count: categorizedChats[key].length,
            isAll: !!maxVisibleChats[key],
            onClick: () => {
              setMaxVisibleChats(prev => ({
                ...prev,
                [key]: !!prev[key] ? null : categorizedChats[key].length,
              }));
            },
          }}
          isVisibleViewAll={
            categorizedChats[key].length > MAX_HIDE_VISIBLE_COUNT
          }
        >
          <CategoryChats
            chats={categorizedChats[key]}
            maxVisibleChats={maxVisibleChats[key] ?? MAX_HIDE_VISIBLE_COUNT}
            currentBalance={balance}
          />
        </ChatItemsList>
      ))}
    </>
  );
}

export const ChatCategoriesSkeleton = () => {
  return <Skeleton style={{ height: 300, width: "100%" }} />;
};
