"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useGetAllModelsQuery, useBulkDeleteModelsMutation, useToggleModelStatusMutation } from "@/src/redux/api/aiModelApi";
import { toast } from "sonner";
import CommonHeader from "@/src/shared/CommonHeader";
import AIModelsList from "./AIModelsList";
import { useRouter } from "next/navigation";
import { AIModel } from "@/src/types/store";
import { ROUTES } from "@/src/constants";

const AIModelsContainer = () => {
  const { t } = useTranslation();
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedModels, setSelectedModels] = useState<string[]>([]);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortBy, setSortBy] = useState("created_at");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  const handleSortChange = (key: string, order: "asc" | "desc") => {
    setSortBy(key);
    setSortOrder(order);
    setPage(1);
  };

  const { data, isLoading, refetch, isFetching } = useGetAllModelsQuery({
    search: searchTerm,
    page,
    limit,
    sort_by: sortBy,
    sort_order: sortOrder.toUpperCase() as "ASC" | "DESC",
  });

  const [bulkDeleteModels, { isLoading: isBulkDeleting }] = useBulkDeleteModelsMutation();
  const [toggleStatus, { isLoading: isToggling }] = useToggleModelStatusMutation();

  const handleToggleStatus = async (id: string, currentStatus: AIModel["status"]) => {
    try {
      const newStatus = currentStatus === "active" ? "inactive" : "active";
      await toggleStatus({ id: id, status: newStatus }).unwrap();
      toast.success(t("ai_models_status_update_success"));
      refetch();
    } catch {
      toast.error(t("ai_models_status_update_error"));
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await bulkDeleteModels([id]).unwrap();
      toast.success(t("ai_models_delete_success"));
      refetch();
    } catch {
      toast.error(t("ai_models_delete_error"));
    }
  };

  const handleBulkDelete = async () => {
    try {
      await bulkDeleteModels(selectedModels).unwrap();
      toast.success(t("ai_models_bulk_delete_success", { count: selectedModels.length }));
      setSelectedModels([]);
      refetch();
    } catch {
      toast.error(t("ai_models_bulk_delete_error"));
    }
  };

  const [columns, setColumns] = useState([
    { id: "display_name", label: t("ai_models_name"), isVisible: true },
    { id: "provider", label: t("ai_models_provider"), isVisible: true },
    { id: "model_id", label: t("ai_models_model_name"), isVisible: true },
    { id: "api_endpoint", label: t("ai_models_base_url"), isVisible: true },
    { id: "status", label: t("common_status"), isVisible: true },
    { id: "is_default", label: t("ai_models_is_default"), isVisible: true },
  ]);

  const handleColumnToggle = (columnId: string) => {
    setColumns((prev) => prev.map((col) => (col.id === columnId ? { ...col, isVisible: !col.isVisible } : col)));
  };

  return (
    <div>
      <CommonHeader title={t("ai_models_title")} description={t("ai_models_add_subtitle")} searchTerm={searchTerm} onSearch={setSearchTerm} onAddClick={() => router.push(`${ROUTES.AIModels}/create`)} addLabel={t("ai_models_add_new")} addPermission="create.ai_models" bulkDeletePermission="delete.ai_models" isLoading={isLoading || isFetching} selectedCount={selectedModels.length} onBulkDelete={handleBulkDelete} columns={columns} onColumnToggle={handleColumnToggle} />

      <div className="mt-8">
        <AIModelsList
          models={data?.data.models || []}
          isLoading={isLoading || isFetching || isBulkDeleting || isToggling}
          selectedIds={selectedModels}
          onSelectionChange={setSelectedModels}
          onToggleStatus={handleToggleStatus}
          onDelete={handleDelete}
          onEdit={(id) => router.push(`${ROUTES.AIModels}/edit/${id}`)}
          columns={columns}
          page={page}
          limit={limit}
          totalCount={data?.data.pagination.totalItems || 0}
          totalPages={data?.data.pagination.totalPages || 1}
          onPageChange={setPage}
          onLimitChange={setLimit}
          onBulkDelete={handleBulkDelete}
          onSortChange={handleSortChange}
          searchTerm={searchTerm}
        />
      </div>
    </div>
  );
};

export default AIModelsContainer;
