import { type FC, useMemo, useState } from "react";
import { EmptyWallet } from "iconsax-react";
import Table from "@/components/Table";
import Filters from "@/components/Filters";
import DefaulModal from "@/components/DefaulModal";
import { useGetAiChats } from "./hooks/useAiChatData";
import { useAiChatFilters } from "./hooks/useAiChatFilters";
import { getAiChatTableColumns } from "./components/AiChatTableColumns";
import { useAiChatFiltersFields } from "./components/AiChatFiltersFields";
import {
  getAiChatAnswer,
  getAiChatQuestion,
  type AiChat,
} from "./types/Types";
import type { RowDataType } from "@/components/types/TableTypes";
import { formatPrice } from "@/helpers/func";

const AiChatsList: FC = () => {
  const [selectedChat, setSelectedChat] = useState<AiChat | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const {
    filters,
    currentPage,
    apiParams,
    handleFiltersChange,
    handlePageChange,
  } = useAiChatFilters();

  const { data: chatsData, isLoading } = useGetAiChats(apiParams);

  const chats = chatsData?.data || [];
  const totalPages = chatsData?.meta?.totalPages || 1;
  const totalCost = chatsData?.meta?.totalCost;
  const pageCost = useMemo(
    () => chats.reduce((sum, chat) => sum + (chat.cost || 0), 0),
    [chats]
  );

  const filterFields = useAiChatFiltersFields();
  const columns = useMemo(
    () =>
      getAiChatTableColumns({
        onViewAnswer: (chat) => {
          setSelectedChat(chat);
          setIsModalOpen(true);
        },
      }),
    []
  );

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedChat(null);
  };

  return (
    <div className="mt-5">
      <div className="flex justify-between items-center">
        <h1 className="text-lg font-light">لیست چت‌های AI</h1>
      </div>

      <div className="mt-6 bg-[#F5F5F5] rounded-2xl px-6 py-4 flex flex-wrap items-center gap-6 w-fit">
        <div className="flex items-center gap-3">
          <EmptyWallet size={22} color="black" />
          <div>
            <div className="text-xs text-description">
              {typeof totalCost === "number"
                ? "مجموع هزینه کل"
                : "مجموع هزینه این صفحه"}
            </div>
            <div className="text-sm font-medium min-w-[100px]">
              {formatPrice(typeof totalCost === "number" ? totalCost : pageCost)}
            </div>
          </div>
        </div>
        {typeof chatsData?.meta?.total === "number" && (
          <div>
            <div className="text-xs text-description">تعداد سوالات</div>
            <div className="text-sm font-medium">
              {chatsData.meta.total.toLocaleString("fa-IR")}
            </div>
          </div>
        )}
      </div>

      <div className="mt-8">
        <Filters
          fields={filterFields}
          onChange={handleFiltersChange}
          initialValues={filters}
          searchField="search"
        />
      </div>

      <Table<AiChat & RowDataType>
        columns={columns}
        data={chats as (AiChat & RowDataType)[]}
        isloading={isLoading}
        pagination={{
          currentPage,
          totalPages,
          onPageChange: handlePageChange,
        }}
      />

      <DefaulModal
        open={isModalOpen}
        close={handleCloseModal}
        isHeader={true}
        title_header="جزئیات چت"
      >
        <div className="mt-4 space-y-4">
          <div>
            <div className="text-xs text-description mb-1">سوال</div>
            <p className="text-sm text-foreground whitespace-pre-wrap break-words">
              {(selectedChat && getAiChatQuestion(selectedChat)) || "-"}
            </p>
          </div>
          <div>
            <div className="text-xs text-description mb-1">پاسخ</div>
            <p className="text-sm text-foreground whitespace-pre-wrap break-words">
              {(selectedChat && getAiChatAnswer(selectedChat)) || "-"}
            </p>
          </div>
          {typeof selectedChat?.cost === "number" && (
            <div>
              <div className="text-xs text-description mb-1">هزینه</div>
              <p className="text-sm text-foreground">
                {formatPrice(selectedChat.cost)}
              </p>
            </div>
          )}
        </div>
      </DefaulModal>
    </div>
  );
};

export default AiChatsList;
