import DashboardLayout from "@/components/layout/dashboard-layout";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { ChangePasswordForm } from "@/components/auth/change-password-form";
import GeneralSettingsForm from "@/components/admin/general-settings-form";
import BackupSettingsPanel from "@/components/admin/backup-settings-panel";
import StorageConfigPanel from "@/components/admin/storage-config-panel";
import PermissionsProfilesManager from "@/components/admin/permissions-profiles-manager";
import SettingsTabsClient from "@/components/settings/settings-tabs-client";
import { verifySession } from "@/lib/auth";
import { hasEmployeePermission } from "@/lib/employee-permissions";
import { getTranslations, getCurrentLocale } from '@/lib/i18n';
import { LanguageSwitcher } from "@/components/settings/language-switcher";
import { getIpAddress } from "@/lib/ip";
import { pgQuery } from "@/lib/postgres/client";
import type { Bank, Currency, Warehouse } from "@/lib/types";
import * as fs from "fs";
import * as path from "path";

function isCurrency(value: unknown): value is Currency {
  if (!value || typeof value !== 'object') return false;
  const item = value as Record<string, unknown>;
  return (
    typeof item.id === 'string' &&
    typeof item.code === 'string' &&
    typeof item.name === 'string' &&
    typeof item.nameEn === 'string' &&
    typeof item.symbol === 'string'
  );
}

function isWarehouse(value: unknown): value is Warehouse {
  if (!value || typeof value !== 'object') return false;
  const item = value as Record<string, unknown>;
  return (
    typeof item.id === 'string' &&
    typeof item.name === 'string' &&
    Array.isArray(item.shelves)
  );
}

function isBank(value: unknown): value is Bank {
  if (!value || typeof value !== 'object') return false;
  const item = value as Record<string, unknown>;
  return (
    typeof item.id === 'string' &&
    typeof item.code === 'string' &&
    typeof item.name === 'string' &&
    typeof item.nameEn === 'string' &&
    item.isActive !== false
  );
}

export default async function SettingsPage() {
  const { user } = await verifySession();
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const settingsT = t.Settings;
  const tGlobal = t.Global ?? {};
  const tGeneralSettings = t.GeneralSettings ?? {};

  const isAdmin = true;

  const settings = isAdmin
    ? await (await import('@/lib/postgres/data-access')).pgGetSettings()
    : null;
  if (!user || !hasEmployeePermission(user, settings || {}, 'settings.manage')) {
    return (
      <DashboardLayout>
        <div className="mx-auto grid w-full max-w-6xl gap-2">
          <h1 className="text-3xl font-semibold">{settingsT.title}</h1>
          <p className="text-destructive">{tGlobal.accessDenied ?? 'Access denied'}</p>
          <p className="text-muted-foreground">{tGlobal.noPermission ?? 'You do not have permission to access this page.'}</p>
        </div>
      </DashboardLayout>
    );
  }
  const approvedIpAddress = isAdmin ? String(settings?.approvedIpAddress || '') : '';

  const rawCurrencies: unknown[] = isAdmin
    ? (await (await import('@/lib/postgres/data-access')).pgGetCurrencies({ page: 1, pageSize: 5000 })).items as unknown[]
    : [];
  const currencies: Currency[] = rawCurrencies.filter(isCurrency);

  const rawDefaultCurrency = isAdmin
    ? await (await import('@/lib/postgres/data-access')).pgGetDefaultCurrency()
    : undefined;
  const defaultCurrency = isCurrency(rawDefaultCurrency) ? rawDefaultCurrency : undefined;

  const rawWarehouses: unknown[] = isAdmin
    ? (await (await import('@/lib/postgres/data-access')).pgGetActiveWarehouses()).items as unknown[]
    : [];
  const warehouses: Warehouse[] = rawWarehouses.filter(isWarehouse);

  const rawBanks: unknown[] = isAdmin
    ? await (await import('@/lib/postgres/data-access')).pgGetGeneralBanks() as unknown[]
    : [];
  const banks: Bank[] = (rawBanks || []).filter(isBank);

  const dbDir = path.join(process.cwd(), "db");
  const dbFiles = isAdmin
    ? (await pgQuery<{ table_name: string }>(
          `
          SELECT table_name
          FROM information_schema.tables
          WHERE table_schema = 'public'
            AND table_type = 'BASE TABLE'
            AND table_name <> '__drizzle_migrations'
          ORDER BY table_name
          `
        )).rows
          .map((row) => String(row.table_name || '').trim())
          .filter((name) => name.length > 0)
    : [];
  const backupDir = path.join(dbDir, "backups");
  const backupIds = isAdmin && fs.existsSync(backupDir)
    ? fs.readdirSync(backupDir).filter((entry) => fs.statSync(path.join(backupDir, entry)).isDirectory())
    : [];
  const appCurrency = String((settings as any)?.appCurrency || '');
  const currentCurrencyCode = isAdmin && settings && currencies.some((c) => c.code === appCurrency)
    ? appCurrency
    : defaultCurrency?.code || "USD";

  // Detect current IP address from headers using the centralized function
  const detectedIp = await getIpAddress();

  return (
    <DashboardLayout>
      <div className="mx-auto grid w-full max-w-6xl gap-2">
        <h1 className="text-3xl font-semibold">{settingsT.title}</h1>
      </div>
      <div className="mx-auto w-full max-w-6xl mt-6">
        <SettingsTabsClient
          isAdmin={isAdmin}
          accountContent={
            <>
              <LanguageSwitcher t={settingsT} currentLocale={locale} />
              <Card>
                <CardHeader>
                  <CardTitle>{settingsT.changePasswordTitle}</CardTitle>
                  <CardDescription>
                    {settingsT.changePasswordDescription}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <ChangePasswordForm formId="settings-account-form" t={settingsT.changePasswordForm} username={String(user.username || '')} />
                </CardContent>
              </Card>
            </>
          }
          systemContent={
            isAdmin && settings ? (
              <Card>
                <CardHeader>
                  <CardTitle>{tGeneralSettings.title ?? 'الإعدادات العامة'}</CardTitle>
                  <CardDescription>
                    {tGeneralSettings.description ?? 'إعدادات النظام الأساسية.'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <GeneralSettingsForm
                    formId="settings-system-form"
                    t={tGeneralSettings}
                    tGlobal={tGlobal}
                    currentSettings={settings}
                    sectionMode="system"
                    currencies={currencies}
                    defaultCurrency={defaultCurrency}
                    currentCurrencyCode={currentCurrencyCode}
                    warehouses={warehouses}
                    banks={banks}
                    currentApprovedIp={approvedIpAddress}
                    detectedIp={detectedIp}
                    dbFiles={dbFiles}
                    backupIds={backupIds}
                  />
                </CardContent>
              </Card>
            ) : <></>
          }
          posSettingsContent={
            isAdmin && settings ? (
              <GeneralSettingsForm
                formId="settings-pos-form"
                t={tGeneralSettings}
                tGlobal={tGlobal}
                currentSettings={settings}
                sectionMode="pos"
                currencies={currencies}
                defaultCurrency={defaultCurrency}
                currentCurrencyCode={currentCurrencyCode}
                warehouses={warehouses}
                banks={banks}
                currentApprovedIp={approvedIpAddress}
                detectedIp={detectedIp}
                dbFiles={dbFiles}
                backupIds={backupIds}
              />
            ) : <></>
          }
          permissionsContent={
            isAdmin && settings ? (
              <PermissionsProfilesManager
                formId="settings-permissions-form"
                currentSettings={settings}
                tGlobal={tGlobal}
              />
            ) : <></>
          }
          backupContent={
            isAdmin ? (
              <BackupSettingsPanel
                dbFiles={dbFiles}
                backupIds={backupIds}
              />
            ) : <></>
          }
          storageConfigContent={
            isAdmin ? (
              <StorageConfigPanel />
            ) : <></>
          }
        />
      </div>
    </DashboardLayout>
  );
}
