'use client';

import type React from 'react';

import {
  EmptyState,
  Page,
  PageHeader,
  PaginationFooter,
  SearchBar,
} from '@/components/entity-list';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { IntegrationLogo } from '@/components/ui/integration-logo';
import { Label } from '@/components/ui/label';
import { ResizableSheetContent } from '@/components/ui/resizable-sheet-content';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Sheet,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import { Switch } from '@/components/ui/switch';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { usePagination } from '@/hooks/use-pagination';
import { formatDate } from '@/lib/format-date';
import { useApp } from '@hed-hog/next-app-provider';
import { Check, Copy, Eye, EyeOff, Pencil, PlugZap, Plus, Trash2, X } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';

// ─── Types ────────────────────────────────────────────────────────────────────

type LocaleEntry = { name: string; locale: { code: string } };

type IntegrationType = {
  id: number;
  slug: string;
  icon: string | null;
  integration_type_locale: LocaleEntry[];
};

type IntegrationProvider = {
  id: number;
  slug: string;
  type_id: number;
  integration_provider_locale: LocaleEntry[];
};

type IntegrationProfile = {
  id: number;
  slug: string;
  name: string;
  type_id: number;
  provider_id: number;
  config: Record<string, unknown> | null;
  is_active: boolean;
  uses_count: number;
  created_at: string;
  updated_at: string;
  integration_type?: IntegrationType;
  integration_provider?: IntegrationProvider;
};

type ProfileForm = {
  name: string;
  slug: string;
  type_id: string;
  provider_id: string;
  config: Record<string, string | boolean | number | string[]>;
  is_active: boolean;
};

type FieldDef = {
  key: string;
  labelKey: string;
  type: 'text' | 'password' | 'number' | 'boolean' | 'email' | 'url';
  required: boolean;
  placeholder?: string;
  colSpan?: boolean;
};

type ImportValidatedProfile = {
  index: number;
  slug: string;
  name: string;
  type_slug: string;
  provider_slug: string;
  config: Record<string, unknown> | null;
  is_active: boolean;
  has_conflict: boolean;
};

type ImportValidationResponse = {
  format: {
    type: string;
    version: number;
    generated_at: string;
    include_secrets: boolean;
  };
  total_profiles: number;
  valid_profiles: number;
  invalid_profiles: number;
  conflict_profiles: number;
  importable_profiles: number;
  conflict_slugs: string[];
  profiles: ImportValidatedProfile[];
  invalid_items: Array<{
    index: number;
    slug?: string;
    errors: string[];
  }>;
};

// ─── Provider field definitions ───────────────────────────────────────────────

const PROVIDER_FIELDS: Record<string, FieldDef[]> = {
  smtp: [
    {
      key: 'host',
      labelKey: 'fieldHost',
      type: 'text',
      required: true,
      placeholder: 'smtp.yourdomain.com',
    },
    {
      key: 'port',
      labelKey: 'fieldPort',
      type: 'number',
      required: true,
      placeholder: '587',
    },
    {
      key: 'username',
      labelKey: 'fieldUsername',
      type: 'text',
      required: true,
    },
    {
      key: 'password',
      labelKey: 'fieldPassword',
      type: 'password',
      required: true,
    },
    {
      key: 'from_email',
      labelKey: 'fieldFromEmail',
      type: 'email',
      required: true,
    },
    {
      key: 'from_name',
      labelKey: 'fieldFromName',
      type: 'text',
      required: false,
    },
    {
      key: 'reply_to_email',
      labelKey: 'fieldReplyTo',
      type: 'email',
      required: false,
    },
    {
      key: 'secure',
      labelKey: 'fieldSecure',
      type: 'boolean',
      required: false,
      colSpan: true,
    },
  ],
  gmail: [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
    {
      key: 'refresh_token',
      labelKey: 'fieldRefreshToken',
      type: 'password',
      required: true,
      colSpan: true,
    },
    {
      key: 'from_email',
      labelKey: 'fieldFromEmail',
      type: 'email',
      required: true,
    },
    {
      key: 'from_name',
      labelKey: 'fieldFromName',
      type: 'text',
      required: false,
    },
  ],
  ses: [
    {
      key: 'access_key_id',
      labelKey: 'fieldAccessKeyId',
      type: 'text',
      required: true,
    },
    {
      key: 'secret_access_key',
      labelKey: 'fieldSecretAccessKey',
      type: 'password',
      required: true,
    },
    {
      key: 'region',
      labelKey: 'fieldRegion',
      type: 'text',
      required: true,
      placeholder: 'us-east-1',
    },
    {
      key: 'from_email',
      labelKey: 'fieldFromEmail',
      type: 'email',
      required: true,
    },
    {
      key: 'from_name',
      labelKey: 'fieldFromName',
      type: 'text',
      required: false,
    },
  ],
  'evolution-api': [
    {
      key: 'host',
      labelKey: 'fieldHost',
      type: 'url',
      required: true,
      placeholder: 'https://evolution.yourdomain.com',
      colSpan: true,
    },
    { key: 'token', labelKey: 'fieldToken', type: 'password', required: true },
    {
      key: 'instance_name',
      labelKey: 'fieldInstanceName',
      type: 'text',
      required: true,
    },
  ],
  'whatsapp-official': [
    {
      key: 'phone_number_id',
      labelKey: 'fieldPhoneNumberId',
      type: 'text',
      required: true,
    },
    {
      key: 'access_token',
      labelKey: 'fieldAccessToken',
      type: 'password',
      required: true,
    },
    {
      key: 'business_id',
      labelKey: 'fieldBusinessId',
      type: 'text',
      required: false,
    },
  ],
  local: [
    {
      key: 'base_path',
      labelKey: 'fieldBasePath',
      type: 'text',
      required: true,
      placeholder: '/var/uploads',
      colSpan: true,
    },
  ],
  s3: [
    {
      key: 'access_key_id',
      labelKey: 'fieldAccessKeyId',
      type: 'text',
      required: true,
    },
    {
      key: 'secret_access_key',
      labelKey: 'fieldSecretAccessKey',
      type: 'password',
      required: true,
    },
    {
      key: 'region',
      labelKey: 'fieldRegion',
      type: 'text',
      required: true,
      placeholder: 'us-east-1',
    },
    { key: 'bucket', labelKey: 'fieldBucket', type: 'text', required: true },
  ],
  gcs: [
    {
      key: 'project_id',
      labelKey: 'fieldProjectId',
      type: 'text',
      required: true,
    },
    { key: 'bucket', labelKey: 'fieldBucket', type: 'text', required: true },
    {
      key: 'key_file_json',
      labelKey: 'fieldKeyFileJson',
      type: 'password',
      required: true,
      colSpan: true,
    },
  ],
  'azure-blob': [
    {
      key: 'account',
      labelKey: 'fieldAccount',
      type: 'text',
      required: true,
      placeholder: 'mystorageaccount',
    },
    {
      key: 'key',
      labelKey: 'fieldAccountKey',
      type: 'password',
      required: true,
    },
    {
      key: 'container',
      labelKey: 'fieldContainer',
      type: 'text',
      required: true,
    },
  ],
  's3-compatible': [
    {
      key: 'endpoint',
      labelKey: 'fieldEndpoint',
      type: 'url',
      required: true,
      colSpan: true,
    },
    {
      key: 'access_key_id',
      labelKey: 'fieldAccessKeyId',
      type: 'text',
      required: true,
    },
    {
      key: 'secret_access_key',
      labelKey: 'fieldSecretAccessKey',
      type: 'password',
      required: true,
    },
    { key: 'bucket', labelKey: 'fieldBucket', type: 'text', required: true },
    {
      key: 'region',
      labelKey: 'fieldRegion',
      type: 'text',
      required: false,
      placeholder: 'us-east-1',
    },
  ],
  openai: [
    {
      key: 'api_key',
      labelKey: 'fieldApiKey',
      type: 'password',
      required: true,
      colSpan: true,
    },
    {
      key: 'organization',
      labelKey: 'fieldOrganization',
      type: 'text',
      required: false,
    },
  ],
  gemini: [
    {
      key: 'api_key',
      labelKey: 'fieldApiKey',
      type: 'password',
      required: true,
      colSpan: true,
    },
  ],
  claude: [
    {
      key: 'api_key',
      labelKey: 'fieldApiKey',
      type: 'password',
      required: true,
      colSpan: true,
    },
  ],
  'google-oauth': [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
  ],
  'github-oauth': [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
  ],
  'microsoft-oauth': [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
    {
      key: 'tenant_id',
      labelKey: 'fieldTenantId',
      type: 'text',
      required: true,
      placeholder: 'common',
    },
  ],
  'facebook-oauth': [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
  ],
  'microsoft-entra-id-oauth': [
    {
      key: 'client_id',
      labelKey: 'fieldClientId',
      type: 'text',
      required: true,
    },
    {
      key: 'client_secret',
      labelKey: 'fieldClientSecret',
      type: 'password',
      required: true,
    },
    {
      key: 'tenant_id',
      labelKey: 'fieldTenantId',
      type: 'text',
      required: true,
    },
  ],
};

// ─── Helpers ─────────────────────────────────────────────────────────────────

function getLocaleName(locales: LocaleEntry[], code: string): string {
  return (
    locales.find((l) => l.locale.code === code)?.name ?? locales[0]?.name ?? ''
  );
}

function toSlug(name: string): string {
  return name
    .toLowerCase()
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

const defaultForm = (): ProfileForm => ({
  name: '',
  slug: '',
  type_id: '',
  provider_id: '',
  config: {},
  is_active: true,
});

// ─── Tab list component ───────────────────────────────────────────────────────

function TypeTab({
  typeId,
  localeCode,
  types,
  providers,
  onEdit,
  onDelete,
  refreshKey,
  t,
  getSettingValue,
  currentLocaleCode,
  selectedProfileIds,
  onToggleProfileSelection,
  onToggleAllVisible,
}: {
  typeId: number;
  localeCode: string;
  types: IntegrationType[];
  providers: IntegrationProvider[];
  onEdit: (profile: IntegrationProfile) => void;
  onDelete: (id: number) => void;
  refreshKey: number;
  t: ReturnType<typeof useTranslations>;
  getSettingValue: (key: string) => string | undefined;
  currentLocaleCode: string;
  selectedProfileIds: Set<number>;
  onToggleProfileSelection: (id: number, checked: boolean) => void;
  onToggleAllVisible: (ids: number[], checked: boolean) => void;
}) {
  const {
    items,
    refetch,
    page,
    setPage,
    pageSize,
    setPageSize,
    totalItems,
    search,
    setSearch,
  } = usePagination({ url: `/integration-profile?typeId=${typeId}` });

  useEffect(() => {
    if (refreshKey > 0) refetch();
  }, [refreshKey]);

  const profiles = Array.isArray(items) ? (items as IntegrationProfile[]) : [];
  const allVisibleSelected =
    profiles.length > 0 &&
    profiles.every((profile) => selectedProfileIds.has(profile.id));

  const typeById = new Map(types.map((type) => [type.id, type]));
  const providerById = new Map(
    providers.map((provider) => [provider.id, provider])
  );

  const toTitle = (value: string) =>
    value.replace(/[-_]+/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase());

  const getResolvedType = (profile: IntegrationProfile) => {
    return profile.integration_type ?? typeById.get(profile.type_id);
  };

  const getResolvedProvider = (profile: IntegrationProfile) => {
    return (
      profile.integration_provider ?? providerById.get(profile.provider_id)
    );
  };

  const getProviderName = (profile: IntegrationProfile) => {
    const provider = getResolvedProvider(profile);
    if (!provider) return '';
    return (
      getLocaleName(provider.integration_provider_locale, localeCode) ||
      toTitle(provider.slug)
    );
  };

  const getProviderSlug = (profile: IntegrationProfile) => {
    return getResolvedProvider(profile)?.slug ?? '';
  };

  const getConfigurationLabel = (profile: IntegrationProfile) => {
    const providerSlug = getProviderSlug(profile);
    if (providerSlug) return providerSlug.toUpperCase();

    const typeSlug = getResolvedType(profile)?.slug;
    if (typeSlug === 'email') return 'SMTP';

    return '—';
  };

  return (
    <div className="space-y-4">
      <SearchBar
        searchQuery={search}
        onSearchChange={(value) => {
          setSearch(value);
          setPage(1);
        }}
        onSearch={() => setPage(1)}
        placeholder={t('searchPlaceholder')}
      />

      {profiles.length === 0 ? (
        <EmptyState
          icon={<PlugZap className="h-12 w-12" />}
          title={t('noProfilesFound')}
          description={t('noProfilesHint')}
        />
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-10">
                  <Checkbox
                    checked={allVisibleSelected}
                    onCheckedChange={(checked) =>
                      onToggleAllVisible(
                        profiles.map((profile) => profile.id),
                        checked === true
                      )
                    }
                    aria-label={t('selectAllVisible')}
                  />
                </TableHead>
                <TableHead>{t('tableName')}</TableHead>
                <TableHead>{t('tableSlug')}</TableHead>
                <TableHead>{t('tableProvider')}</TableHead>
                <TableHead>
                  {currentLocaleCode.startsWith('pt')
                    ? 'Configuração'
                    : 'Configuration'}
                </TableHead>
                <TableHead>{t('tableStatus')}</TableHead>
                <TableHead className="text-right">{t('tableUses')}</TableHead>
                <TableHead>{t('tableUpdated')}</TableHead>
                <TableHead className="text-right">
                  {t('tableActions')}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {profiles.map((profile) => (
                <TableRow
                  key={profile.id}
                  className="cursor-pointer"
                  onDoubleClick={() => onEdit(profile)}
                >
                  <TableCell>
                    <Checkbox
                      checked={selectedProfileIds.has(profile.id)}
                      onCheckedChange={(checked) =>
                        onToggleProfileSelection(profile.id, checked === true)
                      }
                      onClick={(event) => event.stopPropagation()}
                      aria-label={t('selectProfile')}
                    />
                  </TableCell>
                  <TableCell className="font-medium">{profile.name}</TableCell>
                  <TableCell className="font-mono text-sm text-muted-foreground">
                    {profile.slug}
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary" className="gap-1.5">
                      <IntegrationLogo
                        provider={getProviderSlug(profile)}
                        size={14}
                        decorative
                      />
                      {getProviderName(profile)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {getConfigurationLabel(profile)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant={profile.is_active ? 'default' : 'outline'}>
                      {profile.is_active
                        ? t('statusActive')
                        : t('statusInactive')}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    {profile.uses_count > 0 ? (
                      <Badge variant="secondary">{profile.uses_count}</Badge>
                    ) : (
                      <span className="text-muted-foreground">—</span>
                    )}
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {formatDate(
                      profile.updated_at,
                      getSettingValue,
                      currentLocaleCode
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={(e) => {
                          e.stopPropagation();
                          onEdit(profile);
                        }}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={(e) => {
                          e.stopPropagation();
                          onDelete(profile.id);
                        }}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <PaginationFooter
        currentPage={page}
        pageSize={pageSize}
        totalItems={totalItems}
        onPageChange={setPage}
        onPageSizeChange={(newSize) => {
          setPageSize(newSize);
          setPage(1);
        }}
      />
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function IntegrationProfilesPage() {
  const t = useTranslations('core.IntegrationProfilePage');
  const { request, currentLocaleCode, getSettingValue } = useApp();

  const [types, setTypes] = useState<IntegrationType[]>([]);
  const [providers, setProviders] = useState<IntegrationProvider[]>([]);
  const [activeTab, setActiveTab] = useState<string>('');
  const [refreshKey, setRefreshKey] = useState(0);

  const [isSheetOpen, setIsSheetOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [profileToDelete, setProfileToDelete] = useState<number | null>(null);
  const [editingProfile, setEditingProfile] =
    useState<IntegrationProfile | null>(null);
  const [formData, setFormData] = useState<ProfileForm>(defaultForm());
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [visibleFields, setVisibleFields] = useState<Record<string, boolean>>(
    {}
  );
  const [copiedUrlIndex, setCopiedUrlIndex] = useState<number | null>(null);
  const [selectedProfileIds, setSelectedProfileIds] = useState<Set<number>>(
    new Set()
  );
  const [isExportDialogOpen, setIsExportDialogOpen] = useState(false);
  const [exportIncludeSecrets, setExportIncludeSecrets] = useState(false);
  const [pendingExportScope, setPendingExportScope] = useState<
    'all' | 'selected'
  >('all');
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
  const [isImportSubmitting, setIsImportSubmitting] = useState(false);
  const [importPreview, setImportPreview] =
    useState<ImportValidationResponse | null>(null);
  const [conflictActions, setConflictActions] = useState<
    Record<string, 'ignore' | 'replace' | 'rename_auto'>
  >({});
  const fileInputRef = useRef<HTMLInputElement>(null);
  const slugAutoRef = useRef(true);

  // Providers filtered by the type currently selected in the form
  const formTypeProviders = providers.filter(
    (p) => String(p.type_id) === formData.type_id
  );
  const selectedProvider = formTypeProviders.find(
    (p) => String(p.id) === formData.provider_id
  );
  const providerFields = selectedProvider
    ? (PROVIDER_FIELDS[selectedProvider.slug] ?? [])
    : [];

  const isOAuthProvider = (selectedProvider?.slug ?? '').endsWith('-oauth');
  const oauthProviderName = isOAuthProvider
    ? selectedProvider!.slug.replace(/-oauth$/, '')
    : '';
  const appUrl =
    typeof window !== 'undefined'
      ? window.location.origin
      : String(getSettingValue?.('url') ?? '').replace(/\/+$/, '');
  const defaultCallbackUrls =
    isOAuthProvider && appUrl
      ? [
          `${appUrl}/callback/${oauthProviderName}/login`,
          `${appUrl}/callback/${oauthProviderName}/register`,
          `${appUrl}/callback/${oauthProviderName}/connect`,
        ]
      : [];
  const callbackUrls: string[] = (() => {
    const saved = formData.config.callback_urls;
    if (Array.isArray(saved)) return saved as string[];
    return defaultCallbackUrls;
  })();

  useEffect(() => {
    request<IntegrationType[]>({
      url: '/integration-profile/types',
      method: 'GET',
    })
      .then(({ data }) => {
        const list = Array.isArray(data) ? data : ((data as any).data ?? []);
        setTypes(list);
        if (list.length > 0 && !activeTab) setActiveTab(list[0].slug);
      })
      .catch(() => toast.error(t('loadError')));

    request<IntegrationProvider[]>({
      url: '/integration-profile/providers',
      method: 'GET',
    })
      .then(({ data }) => {
        const list = Array.isArray(data) ? data : ((data as any).data ?? []);
        setProviders(list);
      })
      .catch(() => {});
  }, []);

  const handleCreate = () => {
    const activeType = types.find((ty) => ty.slug === activeTab);
    setEditingProfile(null);
    slugAutoRef.current = true;
    setFormData({
      ...defaultForm(),
      type_id: activeType ? String(activeType.id) : '',
    });
    setIsSheetOpen(true);
  };

  const handleEdit = async (profile: IntegrationProfile) => {
    setEditingProfile(profile);
    slugAutoRef.current = false;
    try {
      const { data } = await request<IntegrationProfile>({
        url: `/integration-profile/${profile.id}`,
        method: 'GET',
      });
      const loadedConfig =
        (data.config as Record<
          string,
          string | boolean | number | string[]
        >) ?? {};
      const providerSlug =
        providers.find((p) => p.id === data.provider_id)?.slug ?? '';
      if (
        providerSlug.endsWith('-oauth') &&
        !Array.isArray(loadedConfig.callback_urls)
      ) {
        const pName = providerSlug.replace(/-oauth$/, '');
        if (appUrl) {
          loadedConfig.callback_urls = [
            `${appUrl}/callback/${pName}/login`,
            `${appUrl}/callback/${pName}/register`,
            `${appUrl}/callback/${pName}/connect`,
          ];
        }
      }
      setFormData({
        name: data.name,
        slug: data.slug,
        type_id: String(data.type_id),
        provider_id: String(data.provider_id),
        config: loadedConfig,
        is_active: data.is_active,
      });
    } catch {
      toast.error(t('loadError'));
      return;
    }
    setIsSheetOpen(true);
  };

  const handleDelete = (id: number) => {
    setProfileToDelete(id);
    setIsDeleteDialogOpen(true);
  };

  const handleToggleProfileSelection = (id: number, checked: boolean) => {
    setSelectedProfileIds((prev) => {
      const next = new Set(prev);
      if (checked) next.add(id);
      else next.delete(id);
      return next;
    });
  };

  const handleToggleAllVisible = (ids: number[], checked: boolean) => {
    setSelectedProfileIds((prev) => {
      const next = new Set(prev);
      ids.forEach((id) => {
        if (checked) next.add(id);
        else next.delete(id);
      });
      return next;
    });
  };

  const openExportDialog = (scope: 'all' | 'selected') => {
    setPendingExportScope(scope);
    setExportIncludeSecrets(false);
    setIsExportDialogOpen(true);
  };

  const handleExport = async () => {
    const ids = Array.from(selectedProfileIds);
    if (pendingExportScope === 'selected' && ids.length === 0) {
      toast.error(t('noProfilesSelected'));
      return;
    }

    const params = new URLSearchParams();
    params.set('include_secrets', exportIncludeSecrets ? 'true' : 'false');
    if (pendingExportScope === 'selected') {
      params.set('ids', ids.join(','));
    }

    try {
      const response = await request<Blob>({
        url: `/integration-profile/export?${params.toString()}`,
        method: 'GET',
        responseType: 'blob',
      });

      const blob = new Blob([response.data], {
        type: 'application/octet-stream',
      });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = `integration-profiles-${new Date().toISOString().split('T')[0]}.hedhog`;
      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);
      URL.revokeObjectURL(url);

      setIsExportDialogOpen(false);
      toast.success(t('exportSuccess'));
    } catch {
      toast.error(t('exportError'));
    }
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleImportFileChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    event.target.value = '';
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await request<ImportValidationResponse>({
        url: '/integration-profile/import/validate',
        method: 'POST',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      const initialConflictActions = Object.fromEntries(
        response.data.conflict_slugs.map((slug) => [
          slug,
          'rename_auto' as const,
        ])
      );

      setImportPreview(response.data);
      setConflictActions(initialConflictActions);
      setIsImportDialogOpen(true);
    } catch (error: any) {
      const message =
        error?.response?.data?.message || t('importValidateError');
      toast.error(String(message));
    }
  };

  const handleConfirmImport = async () => {
    if (!importPreview) return;

    if (importPreview.conflict_slugs.length > 0) {
      const allResolved = importPreview.conflict_slugs.every(
        (slug) => !!conflictActions[slug]
      );

      if (!allResolved) {
        toast.error(t('importResolveAllConflicts'));
        return;
      }
    }

    setIsImportSubmitting(true);
    try {
      const response = await request<{
        imported: number;
      }>({
        url: '/integration-profile/import/confirm',
        method: 'POST',
        data: {
          profiles: importPreview.profiles.map((profile) => ({
            slug: profile.slug,
            name: profile.name,
            type_slug: profile.type_slug,
            provider_slug: profile.provider_slug,
            config: profile.config,
            is_active: profile.is_active,
          })),
          conflict_resolutions: Object.entries(conflictActions).map(
            ([slug, action]) => ({ slug, action })
          ),
        },
      });

      setIsImportDialogOpen(false);
      setImportPreview(null);
      setConflictActions({});
      setSelectedProfileIds(new Set());
      setRefreshKey((k) => k + 1);
      toast.success(
        t('importSuccessCount', { count: Number(response.data.imported ?? 0) })
      );
    } catch (error: any) {
      const message = error?.response?.data?.message || t('importError');
      toast.error(String(message));
    } finally {
      setIsImportSubmitting(false);
    }
  };

  const confirmDelete = async () => {
    if (profileToDelete === null) return;
    try {
      await request({
        url: '/integration-profile',
        method: 'DELETE',
        data: { ids: [profileToDelete] },
      });
      toast.success(t('deleteSuccess'));
      setIsDeleteDialogOpen(false);
      setProfileToDelete(null);
      setRefreshKey((k) => k + 1);
    } catch {
      toast.error(t('deleteError'));
    }
  };

  const handleNameChange = (name: string) => {
    setFormData((p) => ({
      ...p,
      name,
      slug: slugAutoRef.current ? toSlug(name) : p.slug,
    }));
  };

  const handleSlugChange = (slug: string) => {
    slugAutoRef.current = false;
    setFormData((p) => ({ ...p, slug }));
  };

  const handleTypeChange = (type_id: string) => {
    setFormData((p) => ({ ...p, type_id, provider_id: '', config: {} }));
  };

  const handleProviderChange = (provider_id: string) => {
    const provider = formTypeProviders.find((p) => String(p.id) === provider_id);
    const initialConfig: Record<string, string | boolean | number | string[]> = {};
    if (provider?.slug?.endsWith('-oauth')) {
      const pName = provider.slug.replace(/-oauth$/, '');
      initialConfig.callback_urls = appUrl
        ? [
            `${appUrl}/callback/${pName}/login`,
            `${appUrl}/callback/${pName}/register`,
            `${appUrl}/callback/${pName}/connect`,
          ]
        : [];
    }
    setFormData((p) => ({ ...p, provider_id, config: initialConfig }));
    setVisibleFields({});
  };

  const updateConfig = (key: string, value: string | boolean | number | string[]) => {
    setFormData((p) => ({ ...p, config: { ...p.config, [key]: value } }));
  };

  const updateCallbackUrl = (index: number, value: string) => {
    const urls = [...callbackUrls];
    urls[index] = value;
    setFormData((p) => ({ ...p, config: { ...p.config, callback_urls: urls } }));
  };

  const addCallbackUrl = () => {
    setFormData((p) => ({
      ...p,
      config: { ...p.config, callback_urls: [...callbackUrls, ''] },
    }));
  };

  const removeCallbackUrl = (index: number) => {
    setFormData((p) => ({
      ...p,
      config: {
        ...p.config,
        callback_urls: callbackUrls.filter((_, i) => i !== index),
      },
    }));
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!formData.type_id || !formData.provider_id) return;

    setIsSubmitting(true);
    const payload = {
      slug: formData.slug,
      name: formData.name,
      type_id: Number(formData.type_id),
      provider_id: Number(formData.provider_id),
      config: isOAuthProvider
        ? { ...formData.config, callback_urls: callbackUrls }
        : formData.config,
      is_active: formData.is_active,
    };

    try {
      if (editingProfile) {
        await request({
          url: `/integration-profile/${editingProfile.id}`,
          method: 'PATCH',
          data: payload,
        });
        toast.success(t('updateSuccess'));
      } else {
        await request({
          url: '/integration-profile',
          method: 'POST',
          data: payload,
        });
        toast.success(t('createSuccess'));
      }
      setIsSheetOpen(false);
      setRefreshKey((k) => k + 1);
    } catch {
      toast.error(editingProfile ? t('updateError') : t('createError'));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Page>
      <PageHeader
        breadcrumbs={[
          { label: t('breadcrumbHome'), href: '/' },
          { label: t('breadcrumbTitle') },
        ]}
        actions={[
          ...(selectedProfileIds.size > 0
            ? [
                {
                  label: t('exportSelected'),
                  onClick: () => openExportDialog('selected'),
                  variant: 'outline' as const,
                },
              ]
            : []),
          {
            label: t('exportAll'),
            onClick: () => openExportDialog('all'),
            variant: 'outline' as const,
          },
          {
            label: t('import'),
            onClick: handleImportClick,
            variant: 'outline' as const,
          },
          {
            label: t('newProfile'),
            onClick: handleCreate,
            variant: 'default' as const,
          },
        ]}
        title={t('title')}
        description={t('description')}
      />

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          {types.map((ty) => (
            <TabsTrigger key={ty.slug} value={ty.slug}>
              {getLocaleName(ty.integration_type_locale, currentLocaleCode)}
            </TabsTrigger>
          ))}
        </TabsList>

        {types.map((ty) => (
          <TabsContent key={ty.slug} value={ty.slug} className="mt-4">
            <TypeTab
              typeId={ty.id}
              localeCode={currentLocaleCode}
              types={types}
              providers={providers}
              onEdit={handleEdit}
              onDelete={handleDelete}
              refreshKey={refreshKey}
              t={t}
              getSettingValue={getSettingValue}
              currentLocaleCode={currentLocaleCode}
              selectedProfileIds={selectedProfileIds}
              onToggleProfileSelection={handleToggleProfileSelection}
              onToggleAllVisible={handleToggleAllVisible}
            />
          </TabsContent>
        ))}
      </Tabs>

      <input
        ref={fileInputRef}
        type="file"
        accept=".hedhog,application/octet-stream"
        className="hidden"
        onChange={handleImportFileChange}
      />

      <Dialog open={isExportDialogOpen} onOpenChange={setIsExportDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t('exportDialogTitle')}</DialogTitle>
            <DialogDescription>
              {pendingExportScope === 'selected'
                ? t('exportDialogDescriptionSelected')
                : t('exportDialogDescriptionAll')}
            </DialogDescription>
          </DialogHeader>
          <label className="flex items-center gap-3 rounded-md border px-3 py-2">
            <Checkbox
              checked={exportIncludeSecrets}
              onCheckedChange={(checked) =>
                setExportIncludeSecrets(checked === true)
              }
            />
            <span className="text-sm">{t('exportIncludeSecrets')}</span>
          </label>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsExportDialogOpen(false)}
            >
              {t('cancel')}
            </Button>
            <Button onClick={handleExport}>{t('export')}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={isImportDialogOpen} onOpenChange={setIsImportDialogOpen}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>{t('importDialogTitle')}</DialogTitle>
            <DialogDescription>
              {t('importDialogDescription')}
            </DialogDescription>
          </DialogHeader>

          {importPreview && (
            <div className="space-y-4">
              <div className="grid gap-2 sm:grid-cols-2">
                <div className="rounded-md border p-3 text-sm">
                  <p className="text-muted-foreground">
                    {t('importTotalProfiles')}
                  </p>
                  <p className="text-lg font-semibold">
                    {importPreview.total_profiles}
                  </p>
                </div>
                <div className="rounded-md border p-3 text-sm">
                  <p className="text-muted-foreground">
                    {t('importValidProfiles')}
                  </p>
                  <p className="text-lg font-semibold">
                    {importPreview.valid_profiles}
                  </p>
                </div>
                <div className="rounded-md border p-3 text-sm">
                  <p className="text-muted-foreground">
                    {t('importInvalidProfiles')}
                  </p>
                  <p className="text-lg font-semibold">
                    {importPreview.invalid_profiles}
                  </p>
                </div>
                <div className="rounded-md border p-3 text-sm">
                  <p className="text-muted-foreground">
                    {t('importConflictProfiles')}
                  </p>
                  <p className="text-lg font-semibold">
                    {importPreview.conflict_profiles}
                  </p>
                </div>
              </div>

              {importPreview.invalid_items.length > 0 && (
                <div className="space-y-2 rounded-md border p-3">
                  <p className="text-sm font-semibold">
                    {t('importInvalidItemsTitle')}
                  </p>
                  <div className="space-y-2">
                    {importPreview.invalid_items.map((item) => (
                      <div
                        key={item.index}
                        className="rounded border p-2 text-xs"
                      >
                        <p className="font-semibold">
                          {item.slug
                            ? t('importInvalidItemWithSlug', {
                                slug: item.slug,
                              })
                            : t('importInvalidItemWithoutSlug', {
                                index: item.index,
                              })}
                        </p>
                        {item.errors.map((error, errorIndex) => (
                          <p key={errorIndex} className="text-muted-foreground">
                            {error}
                          </p>
                        ))}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {importPreview.conflict_slugs.length > 0 && (
                <div className="space-y-3 rounded-md border p-3">
                  <p className="text-sm font-semibold">
                    {t('importConflictTitle')}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {t('importConflictDescription')}
                  </p>

                  {importPreview.conflict_slugs.map((slug) => (
                    <div
                      key={slug}
                      className="grid gap-2 rounded border p-2 sm:grid-cols-[1fr_180px] sm:items-center"
                    >
                      <Badge variant="destructive" className="w-fit font-mono">
                        {slug}
                      </Badge>
                      <Select
                        value={conflictActions[slug] ?? 'rename_auto'}
                        onValueChange={(value) =>
                          setConflictActions((prev) => ({
                            ...prev,
                            [slug]: value as
                              | 'ignore'
                              | 'replace'
                              | 'rename_auto',
                          }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="ignore">
                            {t('conflictActionIgnore')}
                          </SelectItem>
                          <SelectItem value="replace">
                            {t('conflictActionReplace')}
                          </SelectItem>
                          <SelectItem value="rename_auto">
                            {t('conflictActionRenameAuto')}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsImportDialogOpen(false);
                setImportPreview(null);
                setConflictActions({});
              }}
              disabled={isImportSubmitting}
            >
              {t('cancel')}
            </Button>
            <Button onClick={handleConfirmImport} disabled={isImportSubmitting}>
              {isImportSubmitting ? t('importing') : t('confirmImport')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ── Create / Edit Sheet ── */}
      <Sheet open={isSheetOpen} onOpenChange={setIsSheetOpen}>
        <ResizableSheetContent
          sheetId="integration-profile-form"
          defaultWidth={680}
        >
          <SheetHeader>
            <SheetTitle>
              {editingProfile ? t('editProfile') : t('newProfileTitle')}
            </SheetTitle>
            <SheetDescription>
              {editingProfile
                ? t('editProfileDescription')
                : t('newProfileDescription')}
            </SheetDescription>
          </SheetHeader>

          <form
            onSubmit={handleSubmit}
            className="flex flex-col gap-6 px-3 pb-8 sm:px-4"
          >
            {/* ── Identity ── */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="ip-name">
                  {t('nameLabel')} <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="ip-name"
                  value={formData.name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  placeholder={t('namePlaceholder')}
                  required
                  autoFocus
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="ip-slug">
                  {t('slugLabel')} <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="ip-slug"
                  value={formData.slug}
                  onChange={(e) => handleSlugChange(e.target.value)}
                  placeholder={t('slugPlaceholder')}
                  required
                  className="font-mono text-sm"
                />
              </div>
            </div>

            {/* ── Type + Provider ── */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="ip-type">
                  {t('typeLabel')} <span className="text-destructive">*</span>
                </Label>
                <Select
                  value={formData.type_id}
                  onValueChange={handleTypeChange}
                  disabled={!!editingProfile}
                >
                  <SelectTrigger className="w-full" id="ip-type">
                    <SelectValue placeholder={t('typePlaceholder')} />
                  </SelectTrigger>
                  <SelectContent>
                    {types.map((ty) => (
                      <SelectItem key={ty.id} value={String(ty.id)}>
                        {getLocaleName(
                          ty.integration_type_locale,
                          currentLocaleCode
                        )}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="ip-provider">
                  {t('providerLabel')}{' '}
                  <span className="text-destructive">*</span>
                </Label>
                <Select
                  value={formData.provider_id}
                  onValueChange={handleProviderChange}
                  disabled={!formData.type_id || !!editingProfile}
                >
                  <SelectTrigger className="w-full" id="ip-provider">
                    <SelectValue
                      placeholder={
                        !formData.type_id
                          ? t('providerSelectTypFirst')
                          : t('providerPlaceholder')
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    {formTypeProviders.map((prov) => (
                      <SelectItem key={prov.id} value={String(prov.id)}>
                        <span className="flex items-center gap-2">
                          <Avatar className="size-6 border bg-muted/40">
                            <AvatarFallback className="text-[10px] font-semibold">
                              <IntegrationLogo
                                provider={prov.slug}
                                size={14}
                                decorative
                              />
                            </AvatarFallback>
                          </Avatar>
                          {getLocaleName(
                            prov.integration_provider_locale,
                            currentLocaleCode
                          )}
                        </span>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* ── Dynamic credential fields ── */}
            {providerFields.length > 0 && (
              <div className="rounded-lg border">
                <div className="border-b px-4 py-3">
                  <p className="text-sm font-semibold">
                    {t('configSectionTitle')}
                  </p>
                </div>
                <div className="grid gap-4 p-4 sm:grid-cols-2">
                  {providerFields.map((field) => {
                    if (field.type === 'boolean') {
                      return (
                        <div
                          key={field.key}
                          className="col-span-full flex items-center justify-between rounded-md border px-4 py-3"
                        >
                          <p className="text-sm font-medium">
                            {t(field.labelKey as any)}
                          </p>
                          <Switch
                            checked={Boolean(formData.config[field.key])}
                            onCheckedChange={(checked) =>
                              updateConfig(field.key, checked)
                            }
                          />
                        </div>
                      );
                    }

                    const isPassword = field.type === 'password';
                    const isVisible = visibleFields[field.key] ?? false;

                    return (
                      <div
                        key={field.key}
                        className={
                          field.colSpan
                            ? 'col-span-full space-y-2'
                            : 'space-y-2'
                        }
                      >
                        <Label htmlFor={`ip-cfg-${field.key}`}>
                          {t(field.labelKey as any)}
                          {field.required && (
                            <span className="text-destructive"> *</span>
                          )}
                        </Label>
                        <div className={isPassword ? 'relative' : undefined}>
                          <Input
                            id={`ip-cfg-${field.key}`}
                            type={
                              isPassword
                                ? isVisible
                                  ? 'text'
                                  : 'password'
                                : field.type === 'number'
                                  ? 'number'
                                  : 'text'
                            }
                            value={String(formData.config[field.key] ?? '')}
                            onChange={(e) =>
                              updateConfig(field.key, e.target.value)
                            }
                            placeholder={field.placeholder}
                            required={field.required}
                            autoComplete={
                              isPassword ? 'new-password' : undefined
                            }
                            className={isPassword ? 'pr-10' : undefined}
                          />
                          {isPassword && (
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
                              onClick={() =>
                                setVisibleFields((p) => ({
                                  ...p,
                                  [field.key]: !p[field.key],
                                }))
                              }
                              aria-label={
                                isVisible
                                  ? t('hidePassword')
                                  : t('showPassword')
                              }
                            >
                              {isVisible ? (
                                <EyeOff className="h-4 w-4" />
                              ) : (
                                <Eye className="h-4 w-4" />
                              )}
                            </Button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* ── Callback URLs (OAuth only) ── */}
            {isOAuthProvider && (
              <div className="rounded-lg border">
                <div className="flex items-center justify-between border-b px-4 py-3">
                  <div>
                    <p className="text-sm font-semibold">
                      {t('callbackUrlsSectionTitle')}
                    </p>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {t('callbackUrlsDescription')}
                    </p>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addCallbackUrl}
                  >
                    <Plus className="mr-1.5 h-3.5 w-3.5" />
                    {t('addCallbackUrl')}
                  </Button>
                </div>
                <div className="space-y-2 p-4">
                  {callbackUrls.length === 0 && (
                    <p className="py-1 text-center text-sm text-muted-foreground">
                      {t('noCallbackUrls')}
                    </p>
                  )}
                  {callbackUrls.map((url, index) => (
                    <div key={index} className="flex gap-2">
                      <Input
                        value={url}
                        onChange={(e) => updateCallbackUrl(index, e.target.value)}
                        placeholder={t('callbackUrlPlaceholder')}
                        className="font-mono text-sm"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="shrink-0"
                        disabled={!url}
                        onClick={() => {
                          navigator.clipboard.writeText(url);
                          setCopiedUrlIndex(index);
                          setTimeout(() => setCopiedUrlIndex(null), 1500);
                        }}
                      >
                        {copiedUrlIndex === index ? (
                          <Check className="h-4 w-4 text-green-500" />
                        ) : (
                          <Copy className="h-4 w-4" />
                        )}
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        onClick={() => removeCallbackUrl(index)}
                        className="shrink-0"
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* ── Active ── */}
            <div className="flex items-center justify-between rounded-md border px-4 py-3">
              <p className="text-sm font-medium">{t('isActiveLabel')}</p>
              <Switch
                checked={formData.is_active}
                onCheckedChange={(checked) =>
                  setFormData((p) => ({ ...p, is_active: checked }))
                }
              />
            </div>

            <div className="flex justify-end border-t pt-4">
              <Button
                type="submit"
                className="min-w-40"
                disabled={
                  isSubmitting || !formData.type_id || !formData.provider_id
                }
              >
                {editingProfile ? t('saveChanges') : t('createProfile')}
              </Button>
            </div>
          </form>
        </ResizableSheetContent>
      </Sheet>

      {/* ── Delete confirmation ── */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('deleteConfirmTitle')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('deleteConfirmDescription')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t('delete')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Page>
  );
}
