"use client";
import Button from "@/components/ui/Button";
import OptionButton from "@/components/ui/OptionButton";
import { useTranslation } from "@/hooks/useTranslation";
import { GenreModel } from "@/models";
import { Onboarding } from "@/models/onboarding";
import { firstWordCapital } from "@/utils/text";
import React, { Dispatch, SetStateAction } from "react";
import Footer from "./components/Footer";

interface GenreProps {
  onConfirm: () => void;
  genres: GenreModel[];
  selected: Onboarding;
  setSelected: (Dispatch<SetStateAction<Onboarding>>);
}

const Genre: React.FC<GenreProps> = ({ onConfirm, genres, selected, setSelected }) => {
  const { t } = useTranslation();

  const shortenText = (text: string, maxLength: number) => {
    return text.length > maxLength
      ? text.substring(0, maxLength) + "..."
      : text;
  };

  const toggleGenre = (genre: GenreModel) => {
    setSelected(prev => {
      const exists = prev.interstedGenre.some(g => g.id === genre.id);

      return {
        ...prev,
        interstedGenre: exists
          ? prev.interstedGenre.filter(g => g.id !== genre.id)
          : [...prev.interstedGenre, genre]
      };
    });
  };

  return (
    <>
      <div className="flex flex-col gap-4 text-center">
        <h1 className="text-2xl text-dark-500 md:text-3xl font-semibold cursor-default">
          {firstWordCapital(t("select genre that interests you"))}
        </h1>

        <h3 className="text-sm text-dark-300 cursor-default">
          {firstWordCapital(t("so we can show you novels that suit you"))}.
        </h3>
      </div>

      <div className="grid grid-cols-2 gap-3 max-h-60 overflow-y-auto pr-1">
        {genres.map((item) => (
          <OptionButton
            key={item.id}
            onClick={() => toggleGenre(item)}
            selected={selected.interstedGenre.some(g => g.id === item.id)}
            className="py-2 text-sm"
          >
            {shortenText(item.title, 10)}
          </OptionButton>
        ))}
      </div>

      <Button
        text={
          t("continue")
        }
        disabled={selected.interstedGenre.length === 0}
        onClick={onConfirm}
      />

      <Footer />
    </>
  );
};

export default Genre;
