"use client";

import { useEffect, useState } from "react";
import { toast } from "sonner";
import AppSidebar from "@/app/components/AppSidebar";
import ControlBar from "@/app/components/ControlBar";
import DatabaseTab from "@/app/components/DatabaseTab";
import AthenaClientsTab from "@/app/components/AthenaClientsTab";
import ApiKeysTab from "@/app/components/ApiKeysTab";
import { useActionFeedback } from "@/app/hooks/useActionFeedback";
import { useDatabaseAdmin } from "@/app/hooks/useDatabaseAdmin";
import { useAthenaClientsAdmin } from "@/app/hooks/useAthenaClientsAdmin";
import { useApiKeysAdmin } from "@/app/hooks/useApiKeysAdmin";

const defaultAdminApiKey = process.env.NEXT_PUBLIC_ATHENA_ADMIN_API_KEY ?? "";
const defaultGatewayApiKey =
  process.env.NEXT_PUBLIC_ATHENA_GATEWAY_API_KEY ?? "";
const defaultManagementApiKey =
  process.env.NEXT_PUBLIC_ATHENA_MANAGEMENT_API_KEY ?? "";

type Tab = "database" | "athena-clients" | "api-keys";

export default function Home() {
  const [activeTab, setActiveTab] = useState<Tab>("database");
  const [adminApiKey, setAdminApiKey] = useState(defaultAdminApiKey);
  const [gatewayApiKey, setGatewayApiKey] = useState(defaultGatewayApiKey);
  const [managementApiKey, setManagementApiKey] = useState(
    defaultManagementApiKey,
  );

  const { busy, status, error, runAction } = useActionFeedback();

  useEffect(() => {
    if (status) toast.success(status);
  }, [status]);

  useEffect(() => {
    if (error) toast.error(error);
  }, [error]);

  const database = useDatabaseAdmin({
    adminApiKey,
    gatewayApiKey,
    managementApiKey,
    runAction,
  });

  const athenaClients = useAthenaClientsAdmin({
    adminApiKey,
    runAction,
  });

  const apiKeys = useApiKeysAdmin({
    adminApiKey,
    runAction,
  });

  return (
    <div className="h-screen w-screen overflow-hidden bg-background text-foreground">
      <div className="flex h-full">
        <AppSidebar
          activeTab={activeTab}
          onChangeTab={setActiveTab}
          busy={busy}
        />
        <main className="flex min-w-0 flex-1 flex-col">
          <ControlBar
            adminApiKey={adminApiKey}
            gatewayApiKey={gatewayApiKey}
            managementApiKey={managementApiKey}
            onAdminApiKeyChange={setAdminApiKey}
            onGatewayApiKeyChange={setGatewayApiKey}
            onManagementApiKeyChange={setManagementApiKey}
          />

          <div className="min-h-0 flex-1 p-4">
            {activeTab === "database" ? (
              <DatabaseTab
                busy={busy}
                selectedClient={database.selectedClient}
                schemaClients={database.schemaClients}
                onSelectedClientChange={database.setSelectedClient}
                onRefresh={database.handleRefresh}
                tables={database.tables}
                selectedTableName={database.selectedTableName}
                onSelectTable={database.setSelectedTable}
                visibleColumns={database.visibleColumns}
                rowConditionColumn={database.rowConditionColumn}
                onRowConditionColumnChange={database.setRowConditionColumn}
                rows={database.rows}
                rowEdits={database.rowEdits}
                onRowEditChange={(rowKey, column, value) =>
                  database.setRowEdits((prev) => ({
                    ...prev,
                    [rowKey]: {
                      ...(prev[rowKey] ?? {}),
                      [column]: value,
                    },
                  }))
                }
                onSaveRow={database.handleUpdateRow}
                onInsertSubmit={database.handleInsert}
                insertPayload={database.insertPayload}
                onInsertPayloadChange={database.setInsertPayload}
                onDeleteSubmit={database.handleDelete}
                deleteResourceId={database.deleteResourceId}
                onDeleteResourceIdChange={database.setDeleteResourceId}
                createTableJson={database.createTableJson}
                onCreateTableJsonChange={database.setCreateTableJson}
                onCreateTable={database.handleCreateTable}
                editTableJson={database.editTableJson}
                onEditTableJsonChange={database.setEditTableJson}
                onApplyTableEdit={database.handleApplyTableEdit}
                dropSchemaName={database.dropSchemaName}
                onDropSchemaNameChange={database.setDropSchemaName}
                dropCascade={database.dropCascade}
                onDropCascadeChange={database.setDropCascade}
                onDropTable={database.handleDropTable}
                createIndexJson={database.createIndexJson}
                onCreateIndexJsonChange={database.setCreateIndexJson}
                onCreateIndex={database.handleCreateIndex}
                dropIndexName={database.dropIndexName}
                onDropIndexNameChange={database.setDropIndexName}
                dropIndexSchema={database.dropIndexSchema}
                onDropIndexSchemaChange={database.setDropIndexSchema}
                onDropIndex={database.handleDropIndex}
                sql={database.sql}
                onSqlChange={database.setSql}
                sqlDriver={database.sqlDriver}
                onSqlDriverChange={database.setSqlDriver}
                sqlDbName={database.sqlDbName}
                onSqlDbNameChange={database.setSqlDbName}
                onRunSql={database.handleRunSql}
                sqlResult={database.sqlResult}
              />
            ) : null}

            {activeTab === "athena-clients" ? (
              <AthenaClientsTab
                busy={busy}
                adminApiKey={adminApiKey}
                adminClients={athenaClients.adminClients}
                runtimeClients={athenaClients.runtimeClients}
                onReload={athenaClients.handleReload}
                newClientJson={athenaClients.newClientJson}
                onNewClientJsonChange={athenaClients.setNewClientJson}
                onCreateClient={athenaClients.handleCreateClient}
                patchClientName={athenaClients.patchClientName}
                onPatchClientNameChange={athenaClients.setPatchClientName}
                patchClientJson={athenaClients.patchClientJson}
                onPatchClientJsonChange={athenaClients.setPatchClientJson}
                onUpdateClient={athenaClients.handleUpdateClient}
                freezeClientName={athenaClients.freezeClientName}
                onFreezeClientNameChange={athenaClients.setFreezeClientName}
                freezeClientValue={athenaClients.freezeClientValue}
                onFreezeClientValueChange={athenaClients.setFreezeClientValue}
                onApplyFreeze={athenaClients.handleApplyFreeze}
                deleteClientName={athenaClients.deleteClientName}
                onDeleteClientNameChange={athenaClients.setDeleteClientName}
                onDeleteClient={athenaClients.handleDeleteClient}
              />
            ) : null}

            {activeTab === "api-keys" ? (
              <ApiKeysTab
                busy={busy}
                adminApiKey={adminApiKey}
                apiKeys={apiKeys.apiKeys}
                rights={apiKeys.rights}
                apiKeyClientsConfig={apiKeys.apiKeyClientsConfig}
                createdApiKeySecret={apiKeys.createdApiKeySecret}
                onReload={apiKeys.handleReload}
                newApiKeyJson={apiKeys.newApiKeyJson}
                onNewApiKeyJsonChange={apiKeys.setNewApiKeyJson}
                onCreateApiKey={apiKeys.handleCreateApiKey}
                patchApiKeyId={apiKeys.patchApiKeyId}
                onPatchApiKeyIdChange={apiKeys.setPatchApiKeyId}
                patchApiKeyJson={apiKeys.patchApiKeyJson}
                onPatchApiKeyJsonChange={apiKeys.setPatchApiKeyJson}
                onUpdateApiKey={apiKeys.handleUpdateApiKey}
                deleteApiKeyId={apiKeys.deleteApiKeyId}
                onDeleteApiKeyIdChange={apiKeys.setDeleteApiKeyId}
                onDeleteApiKey={apiKeys.handleDeleteApiKey}
                newRightName={apiKeys.newRightName}
                onNewRightNameChange={apiKeys.setNewRightName}
                newRightDescription={apiKeys.newRightDescription}
                onNewRightDescriptionChange={apiKeys.setNewRightDescription}
                onCreateRight={apiKeys.handleCreateRight}
                deleteRightId={apiKeys.deleteRightId}
                onDeleteRightIdChange={apiKeys.setDeleteRightId}
                onDeleteRight={apiKeys.handleDeleteRight}
                globalApiKeyEnforced={apiKeys.globalApiKeyEnforced}
                onGlobalApiKeyEnforcedChange={apiKeys.setGlobalApiKeyEnforced}
                onSaveGlobalConfig={apiKeys.handleSaveGlobalConfig}
                clientOverrideName={apiKeys.clientOverrideName}
                onClientOverrideNameChange={apiKeys.setClientOverrideName}
                clientOverrideEnforced={apiKeys.clientOverrideEnforced}
                onClientOverrideEnforcedChange={
                  apiKeys.setClientOverrideEnforced
                }
                onSaveClientOverride={apiKeys.handleSaveClientOverride}
                deleteClientOverrideName={apiKeys.deleteClientOverrideName}
                onDeleteClientOverrideNameChange={
                  apiKeys.setDeleteClientOverrideName
                }
                onDeleteClientOverride={apiKeys.handleDeleteClientOverride}
              />
            ) : null}
          </div>
        </main>
      </div>
    </div>
  );
}
