// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * /dashboard/plugin-settings — top-level Widget Configuration route.
 *
 * Mirrors the Knowledge pattern: a single canonical surface for editing
 * plugin settings, reachable via the sidebar AND from per-tenant deep links
 * (TenantsList / TenantDetail Megaphone buttons forward here with
 * ?tenantId=<id>). Resolves the active tenant from the URL search param, or
 * falls back to the first available tenant in the company.
 */

import { useEffect, useMemo } from 'react';
import { createFileRoute, useNavigate, Link } from '@tanstack/react-router';
import { z } from 'zod';
import { Globe, Megaphone } from 'lucide-react';
import { PageLayout } from '@/components/shared';
import { PluginSettingsPage } from '@/features/plugin-settings/PluginSettingsPage';
import { useTenants } from '@/features/tenants/hooks';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { TFunction } from '@/features/plugin-settings/lib/constants';
import type { Tenant } from '@/domain/entities';
import { CPZone } from '@archer/domain';
import { requireZone } from '@/presentation/guards/requireZone';

const pluginSettingsSearchSchema = z.object({
  tenantId: z.string().uuid().optional().catch(undefined),
});

function EmptyTenantsCard({ t }: { t: TFunction }) {
  return (
    <div className="p-8">
      <div className="bg-white border border-gray-200 rounded-lg p-8 text-center">
        <Globe className="mx-auto h-12 w-12 text-gray-400 mb-3" />
        <h3 className="text-lg font-semibold text-gray-900 mb-2">
          {t('knowledge.noTenantsTitle')}
        </h3>
        <p className="text-gray-500 mb-4">{t('knowledge.noTenantsHint')}</p>
        <Link
          to="/dashboard/tenants"
          className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-cyan-600 rounded-lg hover:bg-cyan-700"
        >
          {t('knowledge.goToTenants')}
        </Link>
      </div>
    </div>
  );
}

interface TenantSelectorBarProps {
  tenants: Tenant[];
  activeTenant: Tenant;
  onChange: (nextTenantId: string) => void;
  t: TFunction;
}

function TenantSelectorBar({ tenants, activeTenant, onChange, t }: TenantSelectorBarProps) {
  return (
    <div className="flex items-center gap-3 min-w-0">
      <select
        value={activeTenant.id}
        onChange={(event) => onChange(event.target.value)}
        className="px-3 py-2 pr-8 min-w-[240px] max-w-sm border border-gray-300 rounded-lg bg-white text-sm font-semibold text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"
        aria-label={t('knowledge.tenantSelector')}
      >
        {tenants.map((tenant) => (
          <option key={tenant.id} value={tenant.id}>
            {tenant.name}
          </option>
        ))}
      </select>
      <div className="flex items-center gap-2 text-sm text-gray-500 min-w-0">
        <Globe size={14} className="shrink-0" />
        <span className="truncate">{activeTenant.domain}</span>
        <span
          className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
            activeTenant.isActive()
              ? 'bg-green-100 text-green-800'
              : 'bg-gray-100 text-gray-600'
          }`}
        >
          {activeTenant.status}
        </span>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-6 p-8">
      <div className="h-8 bg-gray-200 rounded w-1/3" />
      <div className="h-12 bg-gray-200 rounded" />
      <div className="h-96 bg-gray-200 rounded" />
    </div>
  );
}

function PluginSettingsRoute() {
  const { tenantId } = Route.useSearch();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const tenantsQuery = useTenants();
  const tenants = useMemo<Tenant[]>(
    () => tenantsQuery.data?.tenants ?? [],
    [tenantsQuery.data?.tenants],
  );

  const resolvedTenantId = useMemo(() => {
    if (tenantId && tenants.some((tenant) => tenant.id === tenantId)) return tenantId;
    return tenants[0]?.id;
  }, [tenantId, tenants]);

  useEffect(() => {
    if (resolvedTenantId && resolvedTenantId !== tenantId) {
      navigate({
        to: '/dashboard/plugin-settings',
        search: { tenantId: resolvedTenantId },
        replace: true,
      });
    }
  }, [resolvedTenantId, tenantId, navigate]);

  const activeTenant = tenants.find((tenant) => tenant.id === resolvedTenantId);
  const hasNoTenants = !tenantsQuery.isLoading && tenants.length === 0;

  const switchTenant = (nextTenantId: string) => {
    navigate({
      to: '/dashboard/plugin-settings',
      search: { tenantId: nextTenantId },
      replace: true,
    });
  };

  return (
    <PageLayout
      title={t('tenants.pluginSettings.pageTitle')}
      subtitle={t('tenants.pluginSettings.pageSubtitle')}
      icon={<Megaphone size={24} />}
      gradient={true}
    >
      {hasNoTenants ? (
        <EmptyTenantsCard t={t} />
      ) : resolvedTenantId && activeTenant ? (
        <>
          <TenantSelectorBar
            tenants={tenants}
            activeTenant={activeTenant}
            onChange={switchTenant}
            t={t}
          />
          <PluginSettingsPage tenantId={resolvedTenantId} hasHeader={false} />
        </>
      ) : (
        <LoadingSkeleton />
      )}
    </PageLayout>
  );
}

export const Route = createFileRoute('/_authenticated/dashboard/plugin-settings')({
  validateSearch: pluginSettingsSearchSchema,
  beforeLoad: () => requireZone(CPZone.WIDGET_CONFIG),
  component: PluginSettingsRoute,
});
