"use client";

import { Table } from "@tanstack/react-table";
import { ArrowDownToLineIcon, Loader2Icon, Trash2Icon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TResponseWithQuotas } from "@formbricks/types/responses";
import { Button } from "@/modules/ui/components/button";
import { DecrementQuotasCheckbox } from "@/modules/ui/components/decrement-quotas-checkbox";
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/modules/ui/components/dropdown-menu";
import { cn } from "@/modules/ui/lib/utils";

interface SelectedRowSettingsProps<T> {
  table: Table<T>;
  updateRowList: (rowId: string[]) => void;
  type: "response" | "contact" | "attribute";
  deleteAction: (id: string, params?: Record<string, boolean>) => Promise<void>;
  downloadRowsAction?: (rowIds: string[], format: "xlsx" | "csv") => Promise<void>;
  isQuotasAllowed: boolean;
}

export const SelectedRowSettings = <T,>({
  table,
  updateRowList,
  type,
  deleteAction,
  downloadRowsAction,
  isQuotasAllowed,
}: SelectedRowSettingsProps<T>) => {
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const { t } = useTranslation();
  const selectedRowCount = table.getFilteredSelectedRowModel().rows.length;

  const hasQuotas =
    type === "response" &&
    table
      .getFilteredSelectedRowModel()
      .rows.some((row) => (row.original as TResponseWithQuotas).quotas?.length);

  const [decrementQuotas, setDecrementQuotas] = useState<boolean>(hasQuotas);

  // Toggle all rows selection
  const handleToggleAllRowsSelection = useCallback(
    (selectAll: boolean) => {
      table.toggleAllPageRowsSelected(selectAll);
    },
    [table]
  );

  useEffect(() => {
    setDecrementQuotas(hasQuotas);
  }, [hasQuotas]);

  // Handle deletion
  const handleDelete = async () => {
    try {
      setIsDeleting(true);
      const rowsToBeDeleted = table.getFilteredSelectedRowModel().rows.map((row) => row.id);

      const CHUNK_SIZE = 5;
      for (let i = 0; i < rowsToBeDeleted.length; i += CHUNK_SIZE) {
        const chunk = rowsToBeDeleted.slice(i, i + CHUNK_SIZE);
        if (type === "response") {
          await Promise.all(chunk.map((rowId) => deleteAction(rowId, { decrementQuotas })));
        } else {
          await Promise.all(chunk.map((rowId) => deleteAction(rowId)));
        }
      }

      // Update the row list UI
      updateRowList(rowsToBeDeleted);
      const capitalizedType = type.charAt(0).toUpperCase() + type.slice(1);
      toast.success(t("common.table_items_deleted_successfully", { type: capitalizedType }));
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message);
      } else {
        const capitalizedType = type.charAt(0).toUpperCase() + type.slice(1);
        toast.error(
          t("common.an_unknown_error_occurred_while_deleting_table_items", {
            type: capitalizedType,
          })
        );
      }
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
    }
  };

  // Handle download selected rows
  const handleDownloadSelectedRows = async (format: "xlsx" | "csv") => {
    setIsDownloading(true);
    const rowsToDownload = table.getFilteredSelectedRowModel().rows.map((row) => row.id);
    if (downloadRowsAction && rowsToDownload.length > 0) {
      await downloadRowsAction(rowsToDownload, format);
    }
    setIsDownloading(false);
  };

  // Helper component for the separator
  const Separator = () => <div>|</div>;

  const quotasDialogText = isQuotasAllowed
    ? t("environments.contacts.delete_contact_confirmation_with_quotas", {
        value: selectedRowCount,
      })
    : t("environments.contacts.delete_contact_confirmation");

  let deleteDialogText: string;
  if (type === "response") {
    deleteDialogText = t("environments.surveys.responses.delete_response_confirmation");
  } else if (type === "attribute") {
    deleteDialogText = t("environments.contacts.delete_attribute_confirmation", { value: selectedRowCount });
  } else {
    deleteDialogText = quotasDialogText;
  }

  let selectedTypeLabel: string;
  if (type === "response") {
    selectedTypeLabel = t("common.responses");
  } else if (type === "contact") {
    selectedTypeLabel = t("common.contacts");
  } else {
    selectedTypeLabel = t("common.attributes");
  }

  let deleteWhatText: string;
  if (type === "response") {
    deleteWhatText = t("common.count_responses", { count: selectedRowCount });
  } else if (type === "contact") {
    deleteWhatText = t("common.count_contacts", { count: selectedRowCount });
  } else {
    deleteWhatText = t("common.count_attributes", { count: selectedRowCount });
  }

  return (
    <>
      <div className="flex items-center gap-x-2 rounded-md bg-primary p-1 px-2 text-xs text-white">
        <div className="lowercase">{`${selectedRowCount} ${selectedTypeLabel} ${t("common.selected")}`}</div>
        <Separator />
        <Button
          variant="outline"
          size="sm"
          className="h-6 border-none px-2"
          onClick={() => handleToggleAllRowsSelection(true)}>
          {t("common.select_all")}
        </Button>
        <Button
          variant="outline"
          size="sm"
          className="h-6 border-none px-2"
          onClick={() => handleToggleAllRowsSelection(false)}>
          {t("common.clear_selection")}
        </Button>
        <Separator />
        {downloadRowsAction && (
          <DropdownMenu>
            <DropdownMenuTrigger
              asChild
              className={cn(isDownloading && "cursor-not-allowed opacity-50")}
              disabled={isDownloading}>
              <Button variant="outline" size="sm" className="h-6 gap-1 border-none px-2">
                {isDownloading ? <Loader2Icon className="h-4 w-4 animate-spin" /> : <ArrowDownToLineIcon />}
                {t("common.download")}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem
                onClick={() => {
                  handleDownloadSelectedRows("csv");
                }}>
                <p className="text-slate-700">{t("environments.surveys.summary.selected_responses_csv")}</p>
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => {
                  handleDownloadSelectedRows("xlsx");
                }}>
                <p>{t("environments.surveys.summary.selected_responses_excel")}</p>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        )}
        <Button
          variant="secondary"
          size="sm"
          className="h-6 gap-1 px-2"
          onClick={() => setIsDeleteDialogOpen(true)}>
          {t("common.delete")}
          <Trash2Icon />
        </Button>
      </div>
      <DeleteDialog
        open={isDeleteDialogOpen}
        setOpen={setIsDeleteDialogOpen}
        deleteWhat={deleteWhatText}
        onDelete={handleDelete}
        isDeleting={isDeleting}
        text={deleteDialogText}>
        {hasQuotas && (
          <DecrementQuotasCheckbox
            title={t("environments.surveys.responses.bulk_delete_response_quotas")}
            checked={decrementQuotas ?? hasQuotas}
            onCheckedChange={setDecrementQuotas}
          />
        )}
      </DeleteDialog>
    </>
  );
};
