import { useState, useEffect, useCallback, useMemo, lazy, Suspense } from 'react';
import { Card, CardContent } from './ui/card';
import { Alert, AlertDescription, AlertTitle } from './ui/alert';
import { AlertCircle, Loader2, Search } from 'lucide-react';
import { PackageCard } from './PackageCard';
import { PackageFilters } from './PackageFilters';
import { DeactivateWarningDialog } from './DeactivateWarningDialog';
import type { DeactivateWarning } from './DeactivateWarningDialog';
import { getAvailablePackages, activatePackage, deactivatePackage } from '../services/packages';
import { getIntegrations } from '../services/integrations';
import { ConnectionManagerDialog } from './ConnectionManagerDialog';
import type { PackageWithStatus } from '../types/package';
import type { Integration } from '../types/integration';
import { ApiRequestError } from '../types/api';
import { __ } from '@/lib/i18n';
import { useCapabilities } from '@/hooks/useCapabilities';

const ProIntegrations = lazy(() => import('./ProIntegrations'));

export default function Integrations() {
  const { isPro } = useCapabilities();

  if (isPro) {
    return (
      <Suspense
        fallback={
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-cyan-600" />
          </div>
        }
      >
        <ProIntegrations />
      </Suspense>
    );
  }

  return <FreeIntegrations />;
}

function FreeIntegrations() {
  const [packages, setPackages] = useState<PackageWithStatus[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');

  // Integrations (for connection status)
  const [integrations, setIntegrations] = useState<Integration[]>([]);
  const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
  const [connectionDialogIntegration, setConnectionDialogIntegration] = useState<Integration | null>(null);

  // Package actions
  const [actionInProgress, setActionInProgress] = useState<string | null>(null);
  const [actionType, setActionType] = useState<'activate' | 'deactivate' | null>(null);
  const [deactivateWarning, setDeactivateWarning] = useState<DeactivateWarning | null>(null);

  const fetchPackages = useCallback(async () => {
    try {
      setError(null);
      const pkgs = await getAvailablePackages();
      setPackages(pkgs);
    } catch (err) {
      setError(err instanceof Error ? err.message : __('Failed to load packages'));
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchIntegrations = useCallback(async () => {
    try {
      const data = await getIntegrations();
      setIntegrations(data);
    } catch {
      // Non-critical — Connect buttons just won't appear
    }
  }, []);

  useEffect(() => {
    fetchPackages();
    fetchIntegrations();
  }, [fetchPackages, fetchIntegrations]);

  // Map integrations by slug for quick lookup
  const integrationMap = useMemo(() => {
    const map = new Map<string, Integration>();
    for (const i of integrations) {
      map.set(i.slug, i);
    }
    return map;
  }, [integrations]);

  // Extract categories from packages
  const categories = useMemo(
    () => [...new Set(packages.map((p) => p.category))].sort(),
    [packages],
  );

  // Filter packages by search + category
  const filteredPackages = useMemo(() => {
    return packages.filter((pkg) => {
      const query = searchQuery.toLowerCase();
      const matchesSearch =
        !searchQuery ||
        pkg.name.toLowerCase().includes(query) ||
        pkg.description.toLowerCase().includes(query) ||
        pkg.category.toLowerCase().includes(query);
      const matchesCategory = categoryFilter === 'all' || pkg.category === categoryFilter;
      return matchesSearch && matchesCategory;
    });
  }, [packages, searchQuery, categoryFilter]);

  function handleConnect(slug: string) {
    const integration = integrationMap.get(slug);
    if (integration) {
      setConnectionDialogIntegration(integration);
      setConnectionDialogOpen(true);
    }
  }

  async function handleActivate(slug: string) {
    try {
      setActionInProgress(slug);
      setActionType('activate');
      setError(null);
      await activatePackage(slug);
      await Promise.all([fetchPackages(), fetchIntegrations()]);
    } catch (err) {
      setError(err instanceof Error ? err.message : __('Failed to activate package'));
    } finally {
      setActionInProgress(null);
      setActionType(null);
    }
  }

  async function handleDeactivate(slug: string) {
    try {
      setActionInProgress(slug);
      setActionType('deactivate');
      setError(null);
      await deactivatePackage(slug);
      await Promise.all([fetchPackages(), fetchIntegrations()]);
    } catch (err) {
      if (
        err instanceof ApiRequestError &&
        err.code === 'workflows_affected' &&
        err.data?.affected_workflows
      ) {
        const pkg = packages.find((p) => p.slug === slug);
        setDeactivateWarning({
          slug,
          packageName: pkg?.name ?? slug,
          workflows: err.data.affected_workflows as Array<{ id: number; name: string }>,
          message: err.message,
        });
      } else {
        setError(err instanceof Error ? err.message : __('Failed to deactivate package'));
      }
    } finally {
      setActionInProgress(null);
      setActionType(null);
    }
  }

  async function handleConfirmDeactivate() {
    if (!deactivateWarning) return;
    const { slug } = deactivateWarning;
    setDeactivateWarning(null);
    try {
      setActionInProgress(slug);
      setActionType('deactivate');
      setError(null);
      await deactivatePackage(slug, { confirmDeactivateWorkflows: true });
      await Promise.all([fetchPackages(), fetchIntegrations()]);
    } catch (err) {
      setError(err instanceof Error ? err.message : __('Failed to deactivate package'));
    } finally {
      setActionInProgress(null);
      setActionType(null);
    }
  }

  function hasCredentials(integration: Integration): boolean {
    return Object.keys(integration.credentials ?? {}).length > 0;
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-cyan-600" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="seq-page-title">{__('Integrations')}</h1>
        <p className="seq-body mt-1">
          {__('Manage your bundled integration packages.')}
        </p>
      </div>

      {/* Error */}
      {error && (
        <Alert className="bg-error-muted border-error">
          <AlertCircle className="h-4 w-4 text-error" />
          <AlertTitle className="text-slate-900">{__('Error')}</AlertTitle>
          <AlertDescription className="text-slate-500">{error}</AlertDescription>
        </Alert>
      )}

      {/* Search and Filters */}
      <Card className="shadow-sm">
        <CardContent className="p-4">
          <PackageFilters
            searchQuery={searchQuery}
            onSearchChange={setSearchQuery}
            categories={categories}
            categoryFilter={categoryFilter}
            onCategoryChange={setCategoryFilter}
          />
        </CardContent>
      </Card>

      {/* Package Grid */}
      {filteredPackages.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16">
          <div className="w-14 h-14 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
            <Search className="h-6 w-6 text-slate-400" />
          </div>
          <p className="text-slate-600 font-medium">{__('No packages found')}</p>
          <p className="text-sm text-slate-400 mt-1">
            {__('Try adjusting your search or filters')}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2">
          {filteredPackages.map((pkg) => {
            const integration = integrationMap.get(pkg.slug);
            const showConnect = integration && hasCredentials(integration);
            return (
              <PackageCard
                key={pkg.slug}
                package={pkg}
                showInstall={false}
                showUninstall={false}
                onActivate={handleActivate}
                onDeactivate={handleDeactivate}
                onConnect={showConnect ? handleConnect : undefined}
                connectionStatus={integration?.connected ? 'connected' : 'not_connected'}
                actionInProgress={actionInProgress}
                actionTypeInProgress={actionType}
              />
            );
          })}
        </div>
      )}

      {/* Deactivation Warning Dialog */}
      <DeactivateWarningDialog
        warning={deactivateWarning}
        onConfirm={handleConfirmDeactivate}
        onCancel={() => setDeactivateWarning(null)}
      />

      {/* Connection Manager Dialog */}
      <ConnectionManagerDialog
        open={connectionDialogOpen}
        onOpenChange={setConnectionDialogOpen}
        integration={connectionDialogIntegration}
        onConnectionsChange={fetchIntegrations}
      />
    </div>
  );
}
