"use client";

import { useGetAbout } from "@/app/[name]/(Main)/about/hooks/useAboutData";
import type { Food } from "@/app/[name]/(Main)/types/Types";
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import MenuItem from "@/components/listview/MenuItem";
import MenuItemRenderer from "@/components/listview/MenuItemRenderer";
import { toast } from "@/components/Toast";
import { extractErrorMessage } from "@/lib/func";
import { glassSurfaceFlat } from "@/lib/styles/glassSurface";
import { ArrowLeft, Send2 } from "iconsax-react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { FormEvent, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useChat } from "./hooks/useAiData";
import { AI_SUGGESTIONS } from "./suggestions";
import type { ChatFood } from "./types/Types";

type Message = {
  id: string;
  role: "user" | "assistant";
  content: string;
  foods?: ChatFood[];
};

function getGreetingKey() {
  const hour = new Date().getHours();
  if (hour >= 5 && hour < 12) return "morning";
  if (hour >= 12 && hour < 14) return "noon";
  if (hour >= 14 && hour < 17) return "afternoon";
  return "evening";
}

function toFood(food: ChatFood): Food {
  return {
    id: food.id,
    category: "",
    title: food.title,
    desc: food.desc,
    content: food.content ?? [],
    price: food.price,
    prepareTime: 0,
    isActive: true,
    images: food.images ?? [],
    inPlaceServe: true,
    pickupServe: true,
    discount: food.discount ?? 0,
    isSpecialOffer: food.isSpecialOffer ?? false,
    isAvailable: true,
    unavailabilityMessage: null,
  };
}

function AiPage() {
  const { t } = useTranslation("common", { keyPrefix: "AI" });
  const router = useRouter();
  const { data: about } = useGetAbout();
  const { data: profile, isSuccess } = useGetProfile();
  const { mutate: chat, isPending } = useChat();

  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Message[]>([]);
  const listRef = useRef<HTMLUListElement>(null);

  const restaurant = about?.data;
  const brandName = restaurant?.name || t("BrandFallback");
  const userName = isSuccess && profile?.data?.firstName ? profile.data.firstName : t("GuestName");

  useEffect(() => {
    listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, isPending]);

  const sendMessage = (text: string) => {
    const content = text.trim();
    if (!content || isPending) return;

    const userMessage: Message = { id: `u-${Date.now()}`, role: "user", content };
    setMessages((prev) => [...prev, userMessage]);
    setInput("");

    chat(
      { question: content },
      {
        onSuccess: (res) => {
          setMessages((prev) => [
            ...prev,
            {
              id: `a-${Date.now()}`,
              role: "assistant",
              content: res.data.answer,
              foods: res.data.foods?.length ? res.data.foods : undefined,
            },
          ]);
        },
        onError: (error) => {
          toast(extractErrorMessage(error, t("ErrorFallback")), "error");
        },
      },
    );
  };

  const onSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    sendMessage(input);
  };

  return (
    <section className="flex h-[calc(100svh-6.5rem)] flex-col pt-4 xl:h-[calc(100svh-6rem)]">
      <div className="grid shrink-0 grid-cols-3 items-center">
        <span />
        <h1 className="place-self-center text-sm2 font-medium">{t("Heading")}</h1>
        <ArrowLeft className="cursor-pointer place-self-end" size="20" color="currentColor" onClick={() => router.back()} />
      </div>

      <div className="mt-6 flex min-h-0 flex-1 flex-col">
        {messages.length > 0 ? (
          <ul ref={listRef} className="noscrollbar flex-1 space-y-3 overflow-y-auto pb-4">
            {messages.map((message) => {
              const isUser = message.role === "user";
              const hasFoods = !isUser && !!message.foods?.length;

              return (
                <li key={message.id} className={`flex flex-col gap-2 ${isUser ? "items-end" : "items-start"}`}>
                  <div
                    className={
                      isUser
                        ? "max-w-[80%] rounded-[20px] rounded-br-none bg-primary/15 px-4 py-3 dark:bg-primary/25"
                        : "max-w-[80%] rounded-[20px] rounded-bl-none bg-[#EBEDF5] px-4 py-3 dark:bg-gray-600"
                    }
                  >
                    <p className="text-xs2 leading-5 whitespace-pre-wrap">{message.content}</p>
                  </div>

                  {hasFoods && (
                    <div className="flex w-full flex-col gap-2">
                      {message.foods!.map((food) => (
                        <MenuItemRenderer key={food.id}>
                          <MenuItem food={toFood(food)} />
                        </MenuItemRenderer>
                      ))}
                    </div>
                  )}
                </li>
              );
            })}
            {isPending && (
              <li className="flex justify-start">
                <div className="max-w-[80%] rounded-[20px] rounded-bl-none bg-[#EBEDF5] px-4 py-3 dark:bg-gray-600">
                  <p className="animate-pulse text-xs2 leading-5 text-disabled-text">{t("Thinking")}</p>
                </div>
              </li>
            )}
          </ul>
        ) : (
          <div className="flex flex-1 flex-col items-center justify-center gap-8">
            <div className="flex flex-col items-center gap-2">
              <Image src={"/assets/images/logo_ai.svg"} alt={brandName} width={299} height={299} className="w-74.75 h-auto" unoptimized />
            </div>

            <div className="flex w-full flex-col items-center gap-4">
              <h2 className="text-base font-medium">{t(`Greeting.${getGreetingKey()}`, { name: userName })}</h2>

              <div className="flex w-full flex-wrap gap-2">
                {AI_SUGGESTIONS.map(({ labelKey, icon: Icon }) => (
                  <button
                    key={labelKey}
                    type="button"
                    disabled={isPending}
                    onClick={() => sendMessage(t(labelKey))}
                    className={glassSurfaceFlat("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 transition-[filter] active:brightness-95 disabled:opacity-50")}
                  >
                    <Icon size={15} className="stroke-foreground" variant="Bold" />
                    <span className="text-xs2">{t(labelKey)}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        <form onSubmit={onSubmit} className={glassSurfaceFlat("mt-3 flex h-12 shrink-0 items-center gap-1 rounded-xl border border-border px-3")}>
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder={t("InputPlaceholder")}
            autoComplete="off"
            disabled={isPending}
            className="h-full w-full bg-transparent text-[11px]! outline-none placeholder:text-disabled-text disabled:opacity-60"
          />

          <button type="submit" disabled={!input.trim() || isPending} className="rounded-full p-1.5 disabled:opacity-40">
            <Send2 size={20} variant="Bold" className="fill-primary text-primary dark:fill-foreground dark:text-foreground" />
          </button>
        </form>
      </div>
    </section>
  );
}

export default AiPage;
