"use client";

import { RefreshCcwIcon, Trash2Icon } from "lucide-react";
import { useState } from "react";
import { toast } from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TIntegrationItem } from "@formbricks/types/integration";
import { TIntegrationAirtable } from "@formbricks/types/integration/airtable";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { deleteIntegrationAction } from "@/app/(app)/environments/[environmentId]/workspace/integrations/actions";
import { AddIntegrationModal } from "@/app/(app)/environments/[environmentId]/workspace/integrations/airtable/components/AddIntegrationModal";
import { timeSince } from "@/lib/time";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { Alert, AlertButton, AlertDescription } from "@/modules/ui/components/alert";
import { Button } from "@/modules/ui/components/button";
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
import { EmptyState } from "@/modules/ui/components/empty-state";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/modules/ui/components/tooltip";
import { IntegrationModalInputs } from "../lib/types";

interface ManageIntegrationProps {
  airtableIntegration: TIntegrationAirtable;
  environmentId: string;
  setIsConnected: (data: boolean) => void;
  surveys: TSurvey[];
  airtableArray: TIntegrationItem[];
  locale: TUserLocale;
  showReconnectButton: boolean;
  handleAirtableAuthorization: () => Promise<void>;
}

export const ManageIntegration = ({
  airtableIntegration,
  environmentId,
  setIsConnected,
  surveys,
  airtableArray,
  showReconnectButton,
  handleAirtableAuthorization,
  locale,
}: ManageIntegrationProps) => {
  const { t } = useTranslation();

  const tableHeaders = [
    t("common.survey"),
    t("environments.integrations.airtable.table_name"),
    t("common.questions"),
    t("common.updated_at"),
  ];
  const [isDeleting, setisDeleting] = useState(false);
  const [isDeleteIntegrationModalOpen, setIsDeleteIntegrationModalOpen] = useState(false);
  const [defaultValues, setDefaultValues] = useState<(IntegrationModalInputs & { index: number }) | null>(
    null
  );
  const [isModalOpen, setIsModalOpen] = useState(false);

  const integrationData = airtableIntegration?.config?.data ?? [];

  const handleDeleteIntegration = async () => {
    setisDeleting(true);

    const deleteIntegrationActionResult = await deleteIntegrationAction({
      integrationId: airtableIntegration.id,
    });

    if (deleteIntegrationActionResult?.data) {
      toast.success(t("environments.integrations.integration_removed_successfully"));
      setIsConnected(false);
    } else {
      const errorMessage = getFormattedErrorMessage(deleteIntegrationActionResult);
      toast.error(errorMessage);
    }

    setisDeleting(false);
    setIsDeleteIntegrationModalOpen(false);
  };

  const handleModal = (val: boolean) => {
    setIsModalOpen(val);
  };

  const data = defaultValues
    ? { isEditMode: true as const, defaultData: defaultValues }
    : { isEditMode: false as const };
  return (
    <div className="mt-6 flex w-full flex-col items-center justify-center p-6">
      {showReconnectButton && (
        <Alert variant="warning" size="small" className="mb-4 w-full">
          <AlertDescription>{t("environments.integrations.reconnect_button_description")}</AlertDescription>
          <AlertButton onClick={handleAirtableAuthorization}>
            {t("environments.integrations.reconnect_button")}
          </AlertButton>
        </Alert>
      )}
      <div className="flex w-full justify-end space-x-2">
        <div className="mr-6 flex items-center">
          <span className="mr-4 h-4 w-4 rounded-full bg-green-600"></span>
          <span className="text-slate-500">
            {t("environments.integrations.connected_with_email", {
              email: airtableIntegration.config.email,
            })}
          </span>
        </div>
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button variant="outline" onClick={handleAirtableAuthorization}>
                <RefreshCcwIcon className="mr-2 h-4 w-4" />
                {t("environments.integrations.reconnect_button")}
              </Button>
            </TooltipTrigger>
            <TooltipContent>{t("environments.integrations.reconnect_button_tooltip")}</TooltipContent>
          </Tooltip>
        </TooltipProvider>
        <Button
          onClick={() => {
            setDefaultValues(null);
            handleModal(true);
          }}>
          {t("environments.integrations.airtable.link_new_table")}
        </Button>
      </div>

      {integrationData.length ? (
        <div className="mt-6 w-full rounded-lg border border-slate-200">
          <div className="grid h-12 grid-cols-8 content-center rounded-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
            {tableHeaders.map((header) => (
              <div key={header} className={`col-span-2 hidden text-center sm:block`}>
                {header}
              </div>
            ))}
          </div>

          {integrationData.map((data, index) => (
            <button
              key={`${index}-${data.baseId}-${data.tableId}-${data.surveyId}`}
              className="grid h-16 w-full grid-cols-8 content-center rounded-lg p-2 hover:bg-slate-100"
              onClick={() => {
                setDefaultValues({
                  base: data.baseId,
                  elements: data.elementIds,
                  survey: data.surveyId,
                  table: data.tableId,
                  includeVariables: !!data.includeVariables,
                  includeHiddenFields: !!data.includeHiddenFields,
                  includeMetadata: !!data.includeMetadata,
                  includeCreatedAt: !!data.includeCreatedAt,
                  index,
                });
                setIsModalOpen(true);
              }}>
              <div className="col-span-2 text-center">{data.surveyName}</div>
              <div className="col-span-2 text-center">{data.tableName}</div>
              <div className="col-span-2 text-center">{data.elements}</div>
              <div className="col-span-2 text-center">{timeSince(data.createdAt.toString(), locale)}</div>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 w-full">
          <EmptyState text={t("environments.integrations.airtable.no_integrations_yet")} />
        </div>
      )}

      <Button variant="ghost" onClick={() => setIsDeleteIntegrationModalOpen(true)} className="mt-4">
        <Trash2Icon />
        {t("environments.integrations.delete_integration")}
      </Button>

      <DeleteDialog
        open={isDeleteIntegrationModalOpen}
        setOpen={setIsDeleteIntegrationModalOpen}
        deleteWhat={t("environments.integrations.airtable.airtable_integration")}
        onDelete={handleDeleteIntegration}
        text={t("environments.integrations.delete_integration_confirmation")}
        isDeleting={isDeleting}
      />

      {isModalOpen && (
        <AddIntegrationModal
          airtableArray={airtableArray}
          open={isModalOpen}
          setOpenWithStates={handleModal}
          environmentId={environmentId}
          surveys={surveys}
          airtableIntegration={airtableIntegration}
          {...data}
        />
      )}
    </div>
  );
};
