"use client";

import { useEffect } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useLDAPConfig } from "@/hooks/useLDAPConfig";
import { useTenantLDAPConfig } from "@/hooks/useTenantLDAPConfig";
import { useTenantUsers } from "@/hooks/useTenantUsers";
import { useAdminDashboard } from "@/hooks/useAdminDashboard";
import { useAdminUsers } from "@/hooks/useAdminUsers";
import { useAdminAudit } from "@/hooks/useAdminAudit";
import { useAdminServices } from "@/hooks/useAdminServices";
import { useAdminSecurity } from "@/hooks/useAdminSecurity";
import { useAdminUpload } from "@/hooks/useAdminUpload";
import { useAdminTenants } from "@/hooks/useAdminTenants";
import { useTenantLogos } from "@/hooks/useTenantLogos";
import { useAdminCert } from "@/hooks/useAdminCert";
import { Navbar } from "@/components/navbar";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

// Tab components
import { DashboardTab } from "@/components/admin/tabs/DashboardTab";
import { ServicesTab } from "@/components/admin/tabs/ServicesTab";
import { UsersTab } from "@/components/admin/tabs/UsersTab";
import { AuditTab } from "@/components/admin/tabs/AuditTab";
import { ImportTab } from "@/components/admin/tabs/ImportTab";
import { SecurityTab } from "@/components/admin/tabs/SecurityTab";
import { LDAPTab } from "@/components/admin/tabs/LDAPTab";
import { TenantLDAPTab } from "@/components/admin/tabs/TenantLDAPTab";
import { TenantsTab } from "@/components/admin/tabs/TenantsTab";
import { CertTab } from "@/components/admin/tabs/CertTab";
import { ModulesTab } from "@/components/admin/ModulesTab";
import { IMAPSettingsTab } from "@/components/admin/tabs/IMAPSettingsTab";
import { RetentionTab } from "@/components/admin/tabs/RetentionTab";
import { ArchivingRulesTab } from "@/components/admin/tabs/ArchivingRulesTab";
import { RoutingRulesTab } from "@/components/admin/tabs/RoutingRulesTab";
import { QuotaTab } from "@/components/admin/tabs/QuotaTab";
import { SMTPOutTab } from "@/components/admin/tabs/SMTPOutTab";
import { DSGVOTab } from "@/components/admin/tabs/DSGVOTab";
import { ResetPasswordDialog, DeleteUserDialog } from "@/components/admin/UserDialogs";

export default function AdminPage() {
  const { user, loading: authLoading } = useAuth("domain_admin", "/admin/login");
  const isSuperAdmin = user?.role === "superadmin";
  const canManageDSGVO =
    user?.role === "superadmin" ||
    user?.role === "domain_admin" ||
    user?.role === "admin";
  const canViewDSGVO =
    canManageDSGVO ||
    user?.role === "auditor" ||
    user?.role === "domain_auditor";

  const dashboard = useAdminDashboard(!!user);
  const usersState = useAdminUsers();
  const audit = useAdminAudit();
  const servicesState = useAdminServices();
  const security = useAdminSecurity();
  const upload = useAdminUpload();
  const cert = useAdminCert();

  // LDAP state (global, superadmin) — managed by useLDAPConfig hook
  const {
    ldapConfig,
    ldapLoading,
    ldapSaving,
    ldapTesting,
    ldapError,
    ldapTestResult,
    ldapForm,
    setLdapForm,
    ldapChangePassword,
    setLdapChangePassword,
    loadLDAP,
    handleSaveLDAP,
    handleTestLDAP,
    handleDeleteLDAP,
  } = useLDAPConfig();

  const tenantsState = useAdminTenants();

  // Tenant LDAP state (domain_admin own tenant) — managed by useTenantLDAPConfig hook
  const {
    tenantLdapConfig,
    tenantLdapLoading,
    tenantLdapSaving,
    tenantLdapTesting,
    tenantLdapError,
    tenantLdapTestResult,
    tenantLdapForm,
    setTenantLdapForm,
    tenantLdapChangePassword,
    setTenantLdapChangePassword,
    ownLogoPreviewUrl,
    setOwnLogoPreviewUrl,
    ownLogoUploading,
    setOwnLogoUploading,
    ownLogoError,
    setOwnLogoError,
    loadTenantLDAP,
    handleSaveTenantLDAP,
    handleTestTenantLDAP,
    handleDeleteTenantLDAP,
  } = useTenantLDAPConfig();

  const logos = useTenantLogos(tenantsState.setTenants, {
    setOwnLogoPreviewUrl,
    setOwnLogoUploading,
    setOwnLogoError,
  });

  // Tenant users dialog — managed by useTenantUsers hook
  const {
    tenantUsersDialogId,
    setTenantUsersDialogId,
    tenantUsersDialogName,
    tenantUsersDialogLdap,
    tenantUsers,
    tenantUsersLoading,
    tenantUsersError,
    tenantUsersSyncing,
    tenantUsersSyncResult,
    openUsersDialog,
    handleSyncLDAPUsers,
  } = useTenantUsers();

  const { loadUsers } = usersState;
  const { loadAudit } = audit;
  const { loadServices } = servicesState;

  useEffect(() => {
    if (!user) return;
    loadUsers();
    loadAudit(1);
    loadServices();
  }, [user, loadUsers, loadAudit, loadServices]);

  return (
    <div className="min-h-screen">
      <Navbar username={user?.username ?? ""} role={user?.role ?? ""} />
      <main className="mx-auto max-w-7xl px-4 py-6">
        {(authLoading || !user) ? (
          <div className="space-y-4">
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-10 w-full max-w-sm" />
            <Skeleton className="h-64 w-full" />
          </div>
        ) : (<>
        <h1 className="mb-6 text-2xl font-bold">Administration</h1>

        <Tabs defaultValue="dashboard">
          <TabsList>
            <TabsTrigger value="dashboard">Dashboard</TabsTrigger>
            {isSuperAdmin && <TabsTrigger value="services">Dienste</TabsTrigger>}
            <TabsTrigger value="users">Benutzer</TabsTrigger>
            <TabsTrigger value="audit">Audit-Log</TabsTrigger>
            {canViewDSGVO && <TabsTrigger value="dsgvo">DSGVO-Anfragen</TabsTrigger>}
            <TabsTrigger value="import">Import</TabsTrigger>
            {isSuperAdmin && <TabsTrigger value="ldap" onClick={loadLDAP}>LDAP (Global)</TabsTrigger>}
            {!isSuperAdmin && user?.role === "domain_admin" && (
              <TabsTrigger value="tenant-ldap" onClick={loadTenantLDAP}>LDAP</TabsTrigger>
            )}
            {!isSuperAdmin && user?.role === "domain_admin" && (
              <TabsTrigger value="imap-settings">IMAP</TabsTrigger>
            )}
            {isSuperAdmin && <TabsTrigger value="security">Security</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="cert" onClick={cert.loadCert}>Zertifikat</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="tenants" onClick={tenantsState.loadTenants}>Mandanten</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="retention">Retention</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="archiving-rules">Regeln</TabsTrigger>}
            <TabsTrigger value="routing-rules">Routing-Regeln</TabsTrigger>
            {isSuperAdmin && <TabsTrigger value="quotas">Quotas</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="smtp-out">SMTP-Out</TabsTrigger>}
            {isSuperAdmin && <TabsTrigger value="modules">Module</TabsTrigger>}
          </TabsList>

          <TabsContent value="dashboard" className="mt-4 space-y-6">
            <DashboardTab
              isSuperAdmin={isSuperAdmin}
              smtpStatus={dashboard.smtpStatus}
              storageStats={dashboard.storageStats}
              systemStats={dashboard.systemStats}
              timeseries={dashboard.timeseries}
              apiOnline={dashboard.apiOnline}
              dashLoading={dashboard.dashLoading}
              dashRefreshed={dashboard.dashRefreshed}
              countdown={dashboard.countdown}
              users={usersState.users}
              usersLoading={usersState.usersLoading}
              onRefresh={dashboard.refresh}
            />
          </TabsContent>

          {isSuperAdmin && (
            <TabsContent value="services" className="mt-4">
              <ServicesTab
                isSuperAdmin={isSuperAdmin}
                services={servicesState.services}
                servicesLoading={servicesState.servicesLoading}
                serviceActionLoading={servicesState.serviceActionLoading}
                serviceError={servicesState.serviceError}
                onLoadServices={servicesState.loadServices}
                onServiceAction={servicesState.handleServiceAction}
              />
            </TabsContent>
          )}

          <TabsContent value="users">
            <UsersTab
              isSuperAdmin={isSuperAdmin}
              users={usersState.users}
              tenants={tenantsState.tenants}
              usersLoading={usersState.usersLoading}
              usersError={usersState.usersError}
              dialogOpen={usersState.dialogOpen}
              setDialogOpen={usersState.setDialogOpen}
              newUsername={usersState.newUsername}
              setNewUsername={usersState.setNewUsername}
              newEmail={usersState.newEmail}
              setNewEmail={usersState.setNewEmail}
              newPassword={usersState.newPassword}
              setNewPassword={usersState.setNewPassword}
              newRole={usersState.newRole}
              setNewRole={usersState.setNewRole}
              createLoading={usersState.createLoading}
              createError={usersState.createError}
              onCreateUser={usersState.handleCreateUser}
              userActionLoading={usersState.userActionLoading}
              onToggleActive={usersState.handleToggleActive}
              onOpenResetPassword={(userId) => {
                usersState.setResetPasswordUserId(userId);
                usersState.setResetPasswordValue("");
                usersState.setResetPasswordError("");
              }}
              onOpenDeleteDialog={(u) => { usersState.setDeleteDialogUser(u); usersState.setDeleteDialogError(""); }}
            />
          </TabsContent>

          <TabsContent value="audit">
            <AuditTab
              auditEntries={audit.auditEntries}
              auditTotal={audit.auditTotal}
              auditPage={audit.auditPage}
              auditLoading={audit.auditLoading}
              onLoadAudit={audit.loadAudit}
            />
          </TabsContent>

          {canViewDSGVO && (
            <TabsContent value="dsgvo">
              <DSGVOTab canManage={canManageDSGVO} />
            </TabsContent>
          )}

          <TabsContent value="import">
            <ImportTab
              uploadDragging={upload.uploadDragging}
              setUploadDragging={upload.setUploadDragging}
              uploadJob={upload.uploadJob}
              uploadError={upload.uploadError}
              uploadLoading={upload.uploadLoading}
              onUploadFiles={upload.handleUploadFiles}
            />
          </TabsContent>

          {isSuperAdmin && (
            <TabsContent value="security">
              <SecurityTab
                securityAudit={security.securityAudit}
                securityLoading={security.securityLoading}
                securityError={security.securityError}
                fixLoading={security.fixLoading}
                fixMessage={security.fixMessage}
                onRunAudit={security.runSecurityAudit}
                onRunFix={security.runFix}
              />
            </TabsContent>
          )}

          {isSuperAdmin && (
            <TabsContent value="ldap">
              <LDAPTab
                ldapConfig={ldapConfig}
                ldapLoading={ldapLoading}
                ldapSaving={ldapSaving}
                ldapTesting={ldapTesting}
                ldapError={ldapError}
                ldapTestResult={ldapTestResult}
                ldapForm={ldapForm}
                setLdapForm={setLdapForm}
                ldapChangePassword={ldapChangePassword}
                setLdapChangePassword={setLdapChangePassword}
                onSave={handleSaveLDAP}
                onTest={handleTestLDAP}
                onDelete={handleDeleteLDAP}
              />
            </TabsContent>
          )}

          {!isSuperAdmin && user?.role === "domain_admin" && (
            <TabsContent value="tenant-ldap">
              <TenantLDAPTab
                tenantLdapConfig={tenantLdapConfig}
                tenantLdapLoading={tenantLdapLoading}
                tenantLdapSaving={tenantLdapSaving}
                tenantLdapTesting={tenantLdapTesting}
                tenantLdapError={tenantLdapError}
                tenantLdapTestResult={tenantLdapTestResult}
                tenantLdapForm={tenantLdapForm}
                setTenantLdapForm={setTenantLdapForm}
                tenantLdapChangePassword={tenantLdapChangePassword}
                setTenantLdapChangePassword={setTenantLdapChangePassword}
                ownLogoPreviewUrl={ownLogoPreviewUrl}
                ownLogoUploading={ownLogoUploading}
                ownLogoError={ownLogoError}
                onSave={handleSaveTenantLDAP}
                onTest={handleTestTenantLDAP}
                onDelete={handleDeleteTenantLDAP}
                onOwnLogoUpload={logos.handleOwnLogoUpload}
                onOwnLogoDelete={logos.handleOwnLogoDelete}
              />
            </TabsContent>
          )}

          {isSuperAdmin && (
            <TabsContent value="cert">
              <CertTab
                certInfo={cert.certInfo}
                certLoading={cert.certLoading}
                certError={cert.certError}
                certSuccess={cert.certSuccess}
                certFile={cert.certFile}
                setCertFile={cert.setCertFile}
                keyFile={cert.keyFile}
                setKeyFile={cert.setKeyFile}
                certUploadLoading={cert.certUploadLoading}
                setCertUploadLoading={cert.setCertUploadLoading}
                selfSignedCN={cert.selfSignedCN}
                setSelfSignedCN={cert.setSelfSignedCN}
                selfSignedDNS={cert.selfSignedDNS}
                setSelfSignedDNS={cert.setSelfSignedDNS}
                selfSignedIPs={cert.selfSignedIPs}
                setSelfSignedIPs={cert.setSelfSignedIPs}
                selfSignedYears={cert.selfSignedYears}
                setSelfSignedYears={cert.setSelfSignedYears}
                selfSignedLoading={cert.selfSignedLoading}
                setSelfSignedLoading={cert.setSelfSignedLoading}
                acmeDomain={cert.acmeDomain}
                setAcmeDomain={cert.setAcmeDomain}
                acmeEmail={cert.acmeEmail}
                setAcmeEmail={cert.setAcmeEmail}
                acmeLoading={cert.acmeLoading}
                setAcmeLoading={cert.setAcmeLoading}
                acmeOutput={cert.acmeOutput}
                setAcmeOutput={cert.setAcmeOutput}
                setCertError={cert.setCertError}
                setCertSuccess={cert.setCertSuccess}
                setCertInfo={cert.setCertInfo}
                onLoadCert={cert.loadCert}
              />
            </TabsContent>
          )}

          {isSuperAdmin && (
            <TabsContent value="tenants">
              <TenantsTab
                tenants={tenantsState.tenants}
                tenantsLoading={tenantsState.tenantsLoading}
                tenantsError={tenantsState.tenantsError}
                tenantDialogOpen={tenantsState.tenantDialogOpen}
                setTenantDialogOpen={tenantsState.setTenantDialogOpen}
                newTenantName={tenantsState.newTenantName}
                setNewTenantName={tenantsState.setNewTenantName}
                newTenantSlug={tenantsState.newTenantSlug}
                setNewTenantSlug={tenantsState.setNewTenantSlug}
                tenantCreateLoading={tenantsState.tenantCreateLoading}
                tenantCreateError={tenantsState.tenantCreateError}
                onCreateTenant={tenantsState.handleCreateTenant}
                tenantCredDialogOpen={tenantsState.tenantCredDialogOpen}
                setTenantCredDialogOpen={tenantsState.setTenantCredDialogOpen}
                tenantCreatedName={tenantsState.tenantCreatedName}
                tenantCreatedUsers={tenantsState.tenantCreatedUsers}
                tenantDeleteId={tenantsState.tenantDeleteId}
                setTenantDeleteId={tenantsState.setTenantDeleteId}
                tenantDeleteLoading={tenantsState.tenantDeleteLoading}
                onDeleteTenant={tenantsState.handleDeleteTenant}
                domainDialogTenant={tenantsState.domainDialogTenant}
                setDomainDialogTenant={tenantsState.setDomainDialogTenant}
                tenantDomains={tenantsState.tenantDomains}
                domainsLoading={tenantsState.domainsLoading}
                newDomain={tenantsState.newDomain}
                setNewDomain={tenantsState.setNewDomain}
                addDomainLoading={tenantsState.addDomainLoading}
                domainError={tenantsState.domainError}
                onOpenDomainDialog={tenantsState.openDomainDialog}
                onAddDomain={tenantsState.handleAddDomain}
                onRemoveDomain={tenantsState.handleRemoveDomain}
                tenantUsersDialogId={tenantUsersDialogId}
                setTenantUsersDialogId={setTenantUsersDialogId}
                tenantUsersDialogName={tenantUsersDialogName}
                tenantUsersDialogLdap={tenantUsersDialogLdap}
                tenantUsers={tenantUsers}
                tenantUsersLoading={tenantUsersLoading}
                tenantUsersError={tenantUsersError}
                tenantUsersSyncing={tenantUsersSyncing}
                tenantUsersSyncResult={tenantUsersSyncResult}
                onOpenUsersDialog={openUsersDialog}
                onSyncLDAPUsers={handleSyncLDAPUsers}
                logoDialogTenant={logos.logoDialogTenant}
                logoPreviewUrl={logos.logoPreviewUrl}
                logoUploading={logos.logoUploading}
                logoError={logos.logoError}
                onOpenLogoDialog={logos.openLogoDialog}
                onLogoUpload={logos.handleLogoUpload}
                onLogoDelete={logos.handleLogoDelete}
                onLogoDialogClose={() => { logos.setLogoDialogTenant(null); logos.setLogoPreviewUrl(null); }}
                tenantLdapDialogId={tenantsState.tenantLdapDialogId}
                setTenantLdapDialogId={tenantsState.setTenantLdapDialogId}
                onLoadTenants={tenantsState.loadTenants}
                onToggleTenant={tenantsState.handleToggleTenant}
              />
            </TabsContent>
          )}

          {!isSuperAdmin && (
            <TabsContent value="imap-settings">
              <IMAPSettingsTab />
            </TabsContent>
          )}

          {isSuperAdmin && (
            <TabsContent value="quotas">
              <QuotaTab />
            </TabsContent>
          )}
          {isSuperAdmin && (
            <TabsContent value="retention">
              <RetentionTab />
            </TabsContent>
          )}
          {isSuperAdmin && (
            <TabsContent value="archiving-rules">
              <ArchivingRulesTab />
            </TabsContent>
          )}

          <TabsContent value="routing-rules">
            <RoutingRulesTab isSuperAdmin={isSuperAdmin} />
          </TabsContent>

          {isSuperAdmin && (
            <TabsContent value="smtp-out">
              <SMTPOutTab />
            </TabsContent>
          )}
          <TabsContent value="modules" className="mt-4">
            <ModulesTab />
          </TabsContent>
        </Tabs>
        </>)}
      </main>

      {/* Global dialogs (not tab-specific) */}
      <ResetPasswordDialog
        open={usersState.resetPasswordUserId !== null}
        onClose={() => usersState.setResetPasswordUserId(null)}
        value={usersState.resetPasswordValue}
        setValue={usersState.setResetPasswordValue}
        error={usersState.resetPasswordError}
        loading={usersState.resetPasswordLoading}
        onSubmit={usersState.handleResetPassword}
      />

      <DeleteUserDialog
        user={usersState.deleteDialogUser}
        onClose={() => usersState.setDeleteDialogUser(null)}
        deleteActionLoading={usersState.deleteActionLoading}
        deleteDialogError={usersState.deleteDialogError}
        onDeactivate={usersState.handleDeactivateConfirmed}
        onDelete={usersState.handleDeleteConfirmed}
      />
    </div>
  );
}
