"use client";

import Image from "next/image";
import React, { useCallback, useEffect, useState } from "react";
import Modal from "../../elements/Modal";
import RoundedButton from "../../elements/RoundedButton";
import { Textarea } from "@/components/ui/Textarea";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

interface IUserSuggestion {
  _id: string;
  text: string;
  createdAt: string;
}

function Suggestions() {
  const { t } = useTranslation("common");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [text, setText] = useState("");
  const [suggestions, setSuggestions] = useState<IUserSuggestion[]>([]);
  const [isLoadingList, setIsLoadingList] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { request } = useAxios();

  const loadSuggestions = useCallback(async () => {
    setIsLoadingList(true);
    try {
      const response = await request<{ suggestions?: IUserSuggestion[] }>(
        "GET",
        "/suggestions",
        null,
        { noToast: true }
      );
      setSuggestions(response?.suggestions ?? []);
    } catch {
      setSuggestions([]);
    } finally {
      setIsLoadingList(false);
    }
  }, [request]);

  useEffect(() => {
    if (!isModalOpen) return;
    void loadSuggestions();
  }, [isModalOpen, loadSuggestions]);

  const submitHandler = async () => {
    const trimmed = text.trim();
    if (trimmed.length < 3) {
      toast.error(t("settings.suggestions.minLength"));
      return;
    }

    setIsSubmitting(true);
    try {
      await request("POST", "/suggestions", { text: trimmed });
      toast.success(t("settings.suggestions.success"));
      setText("");
      await loadSuggestions();
    } catch {
      toast.error(t("settings.suggestions.error"));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      <button
        type="button"
        onClick={() => setIsModalOpen(true)}
        className="flex items-center gap-2"
      >
        <Image
          width={24}
          height={24}
          alt=""
          src="/images/icons/vuesax/bold/message-edit.svg"
          className="dark:brightness-0 dark:invert"
        />
        <span>{t("settings.suggestions.title")}</span>
      </button>

      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        height="auto"
        elevated
        panelClassName="max-h-[85vh] overflow-y-auto"
      >
        <div className="flex w-full flex-col items-center px-2 pb-2">
          <span className="text-lg font-bold">{t("settings.suggestions.title")}</span>
          <p className="my-4 text-center text-sm text-neutral-600 dark:text-neutral-400">
            {t("settings.suggestions.description")}
          </p>

          <Textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder={t("settings.suggestions.placeholder")}
            className="min-h-[120px] w-full resize-none text-sm"
            maxLength={2000}
          />

          <RoundedButton
            type="button"
            onClick={() => void submitHandler()}
            disabled={isSubmitting}
            className="mt-4 w-full max-w-sm !border-transparent h-9 !bg-sky-100 text-sky-600"
          >
            {isSubmitting
              ? t("settings.suggestions.submitting")
              : t("settings.suggestions.submit")}
          </RoundedButton>

          <div className="mt-6 w-full border-t border-border-primary-light pt-4">
            <h3 className="mb-3 text-center text-sm font-bold">
              {t("settings.suggestions.previousTitle")}
            </h3>
            {isLoadingList ? (
              <p className="text-center text-sm text-neutral-500">
                {t("common.loading")}
              </p>
            ) : suggestions.length === 0 ? (
              <p className="text-center text-sm text-neutral-500">
                {t("settings.suggestions.empty")}
              </p>
            ) : (
              <ul className="flex max-h-48 flex-col gap-3 overflow-y-auto">
                {suggestions.map((item) => (
                  <li
                    key={item._id}
                    className="rounded-2xl border border-border-primary-light p-3 text-sm"
                  >
                    <p className="leading-6 whitespace-pre-wrap">{item.text}</p>
                    <span className="mt-2 block text-xs text-neutral-500">
                      {item.createdAt}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </Modal>
    </>
  );
}

export default Suggestions;
