/**
 * McpServersPanel — search and browse the MCP server catalog.
 */

import { useEffect, useMemo, useState } from 'react';

import { useAppTranslation } from '@features/localization/renderer';
import { Badge } from '@renderer/components/ui/badge';
import { Button } from '@renderer/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@renderer/components/ui/select';
import { useStore } from '@renderer/store';
import { formatRelativeTime } from '@renderer/utils/formatters';
import { getRuntimeDisplayName } from '@renderer/utils/runtimeDisplayName';
import { CLI_NOT_FOUND_MARKER } from '@shared/constants/cli';
import {
  getMcpDiagnosticKey,
  getMcpProjectStateKey,
  getPreferredMcpInstallationEntry,
  sanitizeMcpServerName,
} from '@shared/utils/extensionNormalizers';
import { AlertTriangle, RefreshCw, Search, Server } from 'lucide-react';
import { useShallow } from 'zustand/react/shallow';

import { SearchInput } from '../common/SearchInput';

import { McpServerCard } from './McpServerCard';
import { McpServerDetailDialog } from './McpServerDetailDialog';

import type { CliInstallationStatus } from '@shared/types';
import type {
  InstalledMcpEntry,
  McpCatalogItem,
  McpServerDiagnostic,
} from '@shared/types/extensions';

type McpSortValue = 'name-asc' | 'name-desc' | 'tools-desc';

const MCP_SORT_OPTIONS: { value: McpSortValue; label: string }[] = [
  { value: 'name-asc', label: 'Name A→Z' },
  { value: 'name-desc', label: 'Name Z→A' },
  { value: 'tools-desc', label: 'Most tools' },
];

function getMcpSortLabel(
  value: McpSortValue,
  t: ReturnType<typeof useAppTranslation>['t']
): string {
  switch (value) {
    case 'name-asc':
      return t('mcpPanel.sort.nameAsc');
    case 'name-desc':
      return t('mcpPanel.sort.nameDesc');
    case 'tools-desc':
      return t('mcpPanel.sort.toolsDesc');
  }
}

function sortMcpServers(servers: McpCatalogItem[], sort: McpSortValue): McpCatalogItem[] {
  return [...servers].sort((a, b) => {
    switch (sort) {
      case 'name-asc':
        return a.name.localeCompare(b.name);
      case 'name-desc':
        return b.name.localeCompare(a.name);
      case 'tools-desc':
        return b.tools.length - a.tools.length;
      default:
        return 0;
    }
  });
}

interface McpServersPanelProps {
  projectPath: string | null;
  mcpSearchQuery: string;
  mcpSearch: (query: string) => void;
  mcpSearchResults: McpCatalogItem[];
  mcpSearchLoading: boolean;
  mcpSearchWarnings: string[];
  selectedMcpServerId: string | null;
  setSelectedMcpServerId: (id: string | null) => void;
  cliStatus?: Pick<
    CliInstallationStatus,
    | 'installed'
    | 'authLoggedIn'
    | 'binaryPath'
    | 'launchError'
    | 'flavor'
    | 'displayName'
    | 'providers'
  > | null;
  cliStatusLoading?: boolean;
}

export const McpServersPanel = ({
  projectPath,
  mcpSearchQuery,
  mcpSearch,
  mcpSearchResults,
  mcpSearchLoading,
  mcpSearchWarnings,
  selectedMcpServerId,
  setSelectedMcpServerId,
  cliStatus: cliStatusOverride,
  cliStatusLoading: cliStatusLoadingOverride,
}: McpServersPanelProps): React.JSX.Element => {
  const { t } = useAppTranslation('extensions');
  const projectStateKey = getMcpProjectStateKey(projectPath);
  const {
    browseCatalog,
    browseNextCursor,
    browseLoading,
    browseError,
    mcpBrowse,
    installedServersByProjectPath,
    installedServersFallback,
    fetchMcpGitHubStars,
    mcpDiagnosticsByProjectPath,
    mcpDiagnosticsFallback,
    mcpDiagnosticsLoadingByProjectPath,
    mcpDiagnosticsLoadingFallback,
    mcpDiagnosticsErrorByProjectPath,
    mcpDiagnosticsErrorFallback,
    mcpDiagnosticsLastCheckedAtByProjectPath,
    mcpDiagnosticsLastCheckedAtFallback,
    runMcpDiagnostics,
  } = useStore(
    useShallow((s) => ({
      browseCatalog: s.mcpBrowseCatalog,
      browseNextCursor: s.mcpBrowseNextCursor,
      browseLoading: s.mcpBrowseLoading,
      browseError: s.mcpBrowseError,
      mcpBrowse: s.mcpBrowse,
      installedServersByProjectPath: s.mcpInstalledServersByProjectPath,
      installedServersFallback: s.mcpInstalledServers,
      fetchMcpGitHubStars: s.fetchMcpGitHubStars,
      mcpDiagnosticsByProjectPath: s.mcpDiagnosticsByProjectPath,
      mcpDiagnosticsFallback: s.mcpDiagnostics,
      mcpDiagnosticsLoadingByProjectPath: s.mcpDiagnosticsLoadingByProjectPath,
      mcpDiagnosticsLoadingFallback: s.mcpDiagnosticsLoading,
      mcpDiagnosticsErrorByProjectPath: s.mcpDiagnosticsErrorByProjectPath,
      mcpDiagnosticsErrorFallback: s.mcpDiagnosticsError,
      mcpDiagnosticsLastCheckedAtByProjectPath: s.mcpDiagnosticsLastCheckedAtByProjectPath,
      mcpDiagnosticsLastCheckedAtFallback: s.mcpDiagnosticsLastCheckedAt,
      runMcpDiagnostics: s.runMcpDiagnostics,
    }))
  );
  const storedCliStatus = useStore((s) => s.cliStatus);
  const storedCliStatusLoading = useStore((s) => s.cliStatusLoading);
  const cliStatus = cliStatusOverride ?? storedCliStatus;
  const cliStatusLoading = cliStatusLoadingOverride ?? storedCliStatusLoading;
  const installedServers =
    installedServersByProjectPath?.[projectStateKey] ?? installedServersFallback ?? [];
  const mcpDiagnostics =
    mcpDiagnosticsByProjectPath?.[projectStateKey] ?? mcpDiagnosticsFallback ?? {};
  const mcpDiagnosticsLoading =
    mcpDiagnosticsLoadingByProjectPath?.[projectStateKey] ?? mcpDiagnosticsLoadingFallback ?? false;
  const mcpDiagnosticsError =
    mcpDiagnosticsErrorByProjectPath?.[projectStateKey] ?? mcpDiagnosticsErrorFallback ?? null;
  const mcpDiagnosticsLastCheckedAt =
    mcpDiagnosticsLastCheckedAtByProjectPath?.[projectStateKey] ??
    mcpDiagnosticsLastCheckedAtFallback ??
    null;

  const [mcpSort, setMcpSort] = useState<McpSortValue>('name-asc');

  // Load initial browse data
  useEffect(() => {
    if (browseCatalog.length === 0 && !browseLoading && !browseError) {
      void mcpBrowse();
    }
  }, [browseCatalog.length, browseError, browseLoading, mcpBrowse]);

  const diagnosticsDisableReason = useMemo(() => {
    if (cliStatus === null || typeof cliStatus === 'undefined') {
      return cliStatusLoading
        ? t('mcpPanel.diagnostics.disableReasons.checkingRuntimeStatus')
        : t('mcpPanel.diagnostics.disableReasons.checkingRuntimeAvailability');
    }

    if (cliStatus?.installed === false) {
      if (cliStatus.binaryPath && cliStatus.launchError) {
        return t('mcpPanel.diagnostics.disableReasons.runtimeFailedToStart');
      }
      return t('mcpPanel.diagnostics.disableReasons.runtimeRequired');
    }

    return null;
  }, [cliStatus, cliStatusLoading, t]);

  useEffect(() => {
    if (diagnosticsDisableReason) {
      return;
    }
    void runMcpDiagnostics(projectPath ?? undefined);
  }, [diagnosticsDisableReason, projectPath, runMcpDiagnostics]);

  // Fetch GitHub stars after catalog loads (fire-and-forget)
  useEffect(() => {
    const urls = browseCatalog.map((s) => s.repositoryUrl).filter((u): u is string => !!u);
    if (urls.length > 0) {
      fetchMcpGitHubStars(urls);
    }
  }, [browseCatalog, fetchMcpGitHubStars]);

  // Decide which list to show: search results or browse
  const isSearching = mcpSearchQuery.trim().length > 0;
  const rawServers = isSearching ? mcpSearchResults : browseCatalog;
  const isLoading = isSearching ? mcpSearchLoading : browseLoading;
  const warnings = isSearching ? mcpSearchWarnings : [];

  // Installed lookup set (lowercase CLI names)
  const installedNames = useMemo(
    () => new Set(installedServers.map((s) => s.name.toLowerCase())),
    [installedServers]
  );

  const installedEntriesByName = useMemo(() => {
    const entriesByName = new Map<string, InstalledMcpEntry[]>();
    for (const entry of installedServers) {
      const key = entry.name.toLowerCase();
      entriesByName.set(key, [...(entriesByName.get(key) ?? []), entry]);
    }
    return entriesByName;
  }, [installedServers]);

  /** Check if a catalog server is installed by comparing sanitized names */
  const isServerInstalled = (server: McpCatalogItem): boolean =>
    installedNames.has(sanitizeMcpServerName(server.name));

  const getInstalledEntries = (server: McpCatalogItem): InstalledMcpEntry[] =>
    installedEntriesByName.get(sanitizeMcpServerName(server.name)) ?? [];

  const getInstalledEntry = (server: McpCatalogItem): InstalledMcpEntry | null =>
    getPreferredMcpInstallationEntry(getInstalledEntries(server));

  const getDiagnostic = (server: McpCatalogItem): McpServerDiagnostic | null => {
    const installedEntry = getInstalledEntry(server);
    return installedEntry
      ? (mcpDiagnostics[getMcpDiagnosticKey(installedEntry.name, installedEntry.scope)] ??
          mcpDiagnostics[getMcpDiagnosticKey(installedEntry.name)] ??
          mcpDiagnostics[installedEntry.name] ??
          null)
      : null;
  };

  const allDiagnostics = useMemo(
    () => Object.values(mcpDiagnostics).sort((a, b) => a.name.localeCompare(b.name)),
    [mcpDiagnostics]
  );

  const getDiagnosticBadgeClass = (status: McpServerDiagnostic['status']): string => {
    switch (status) {
      case 'connected':
        return 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400';
      case 'needs-authentication':
        return 'border-amber-500/30 bg-amber-500/10 text-amber-400';
      case 'failed':
        return 'border-red-500/30 bg-red-500/10 text-red-400';
      default:
        return 'border-border bg-surface-raised text-text-muted';
    }
  };

  // Sort displayed servers
  const displayServers = useMemo(() => sortMcpServers(rawServers, mcpSort), [rawServers, mcpSort]);
  const runtimeLabel = getRuntimeDisplayName(cliStatus, true);

  // Find selected server (search in both lists to avoid losing selection during search toggle)
  const selectedServer = useMemo(() => {
    if (!selectedMcpServerId) return null;
    return (
      displayServers.find((s) => s.id === selectedMcpServerId) ??
      browseCatalog.find((s) => s.id === selectedMcpServerId) ??
      mcpSearchResults.find((s) => s.id === selectedMcpServerId) ??
      null
    );
  }, [displayServers, browseCatalog, mcpSearchResults, selectedMcpServerId]);

  return (
    <div className="flex flex-col gap-4">
      <div className="rounded-md border border-black/10 bg-surface-raised px-4 py-3 dark:border-white/10">
        <div className="flex items-center justify-between gap-3">
          <div>
            <p className="text-sm font-medium text-text">{t('mcpPanel.health.title')}</p>
            <p className="text-xs text-text-muted">
              {mcpDiagnosticsLoading
                ? t('mcpPanel.health.checkingViaRuntime', { runtime: runtimeLabel })
                : diagnosticsDisableReason
                  ? diagnosticsDisableReason
                  : mcpDiagnosticsLastCheckedAt
                    ? t('mcpPanel.health.lastChecked', {
                        time: formatRelativeTime(
                          new Date(mcpDiagnosticsLastCheckedAt).toISOString()
                        ),
                      })
                    : t('mcpPanel.health.description')}
            </p>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => void runMcpDiagnostics(projectPath ?? undefined)}
            disabled={mcpDiagnosticsLoading || Boolean(diagnosticsDisableReason)}
            className="whitespace-nowrap"
          >
            <RefreshCw
              className={`mr-1.5 size-3.5 ${mcpDiagnosticsLoading ? 'animate-spin' : ''}`}
            />
            {mcpDiagnosticsLoading
              ? t('mcpPanel.health.checking')
              : t('mcpPanel.health.checkStatus')}
          </Button>
        </div>

        {(mcpDiagnosticsLoading || allDiagnostics.length > 0) && (
          <div className="mt-4 border-t border-black/10 pt-4 dark:border-white/10">
            <div className="mb-3 flex items-center justify-between gap-3">
              <p className="text-sm font-medium text-text">{t('mcpPanel.diagnostics.title')}</p>
              {allDiagnostics.length > 0 && (
                <span className="text-xs text-text-muted">
                  {t('mcpPanel.diagnostics.serversCount', { count: allDiagnostics.length })}
                </span>
              )}
            </div>
            {allDiagnostics.length > 0 ? (
              <div className="mcp-diagnostics-list max-h-[18.5rem] space-y-2 overflow-y-auto pr-1">
                {allDiagnostics.map((diagnostic) => (
                  <div
                    key={getMcpDiagnosticKey(diagnostic.name, diagnostic.scope)}
                    className="flex items-start justify-between gap-3 rounded-md border border-black/10 px-3 py-2 dark:border-white/10"
                  >
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <p className="text-sm text-text">{diagnostic.name}</p>
                        {diagnostic.scope && (
                          <span className="rounded-full border border-border bg-surface-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-text-muted">
                            {diagnostic.scope}
                          </span>
                        )}
                      </div>
                      <p
                        className="truncate font-mono text-[11px] text-text-muted"
                        title={diagnostic.target}
                      >
                        {diagnostic.target}
                      </p>
                    </div>
                    <Badge className={getDiagnosticBadgeClass(diagnostic.status)} variant="outline">
                      {diagnostic.statusLabel}
                    </Badge>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-xs text-text-muted">{t('mcpPanel.diagnostics.waiting')}</p>
            )}
          </div>
        )}
      </div>

      {/* Search + sort row */}
      <div className="flex items-center gap-3">
        <div className="flex-1">
          <SearchInput
            value={mcpSearchQuery}
            onChange={mcpSearch}
            placeholder={t('mcpPanel.searchPlaceholder')}
          />
        </div>
        <Select value={mcpSort} onValueChange={(v) => setMcpSort(v as McpSortValue)}>
          <SelectTrigger className="w-36">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {MCP_SORT_OPTIONS.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                {getMcpSortLabel(opt.value, t)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Warnings */}
      {warnings.length > 0 && (
        <div className="flex flex-col gap-1">
          {warnings.map((w, i) => (
            <div
              key={i}
              className="flex items-center gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-400"
            >
              <AlertTriangle className="size-3.5 shrink-0" />
              {w}
            </div>
          ))}
        </div>
      )}

      {/* Skeleton loading */}
      {isLoading && displayServers.length === 0 && (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
          {Array.from({ length: 6 }, (_, i) => (
            <div
              key={i}
              className="skeleton-card flex flex-col gap-2 rounded-lg border border-border p-4"
              style={{ animationDelay: `${i * 80}ms` }}
            >
              <div className="flex items-start gap-2.5">
                <div className="size-9 rounded-lg bg-surface-raised" />
                <div className="flex-1 space-y-1.5">
                  <div className="h-4 w-32 rounded bg-surface-raised" />
                  <div className="h-3 w-16 rounded-full bg-surface-raised" />
                </div>
              </div>
              <div className="space-y-1.5">
                <div className="h-3 w-full rounded bg-surface-raised" />
                <div className="h-3 w-2/3 rounded bg-surface-raised" />
              </div>
              <div className="flex items-center justify-between">
                <div className="h-5 w-12 rounded-full bg-surface-raised" />
                <div className="h-7 w-16 rounded bg-surface-raised" />
              </div>
            </div>
          ))}
        </div>
      )}

      {browseError && !isSearching && (
        <div className="rounded-md border border-red-500/30 bg-red-500/5 p-4 text-sm text-red-400">
          {browseError}
        </div>
      )}

      {mcpDiagnosticsError &&
        (mcpDiagnosticsError.includes(CLI_NOT_FOUND_MARKER) ? (
          <div className="flex items-start gap-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3">
            <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-400" />
            <div>
              <p className="text-sm font-medium text-amber-300">
                {cliStatus?.flavor === 'agent_teams_orchestrator'
                  ? t('mcpPanel.runtime.notAvailable', { runtime: runtimeLabel })
                  : t('mcpPanel.runtime.notInstalled', { runtime: runtimeLabel })}
              </p>
              <p className="mt-0.5 text-xs text-text-muted">
                {t('mcpPanel.runtime.requiredDescription', { runtime: runtimeLabel })}
              </p>
            </div>
          </div>
        ) : (
          <div className="rounded-md border border-red-500/30 bg-red-500/5 p-4 text-sm text-red-400">
            {mcpDiagnosticsError}
          </div>
        ))}

      {/* Empty state */}
      {!isLoading && displayServers.length === 0 && (
        <div className="flex flex-col items-center gap-3 rounded-sm border border-dashed border-border px-8 py-16">
          <div className="flex size-10 items-center justify-center rounded-lg border border-border bg-surface-raised">
            {isSearching ? (
              <Search className="size-5 text-text-muted" />
            ) : (
              <Server className="size-5 text-text-muted" />
            )}
          </div>
          <p className="text-sm text-text-secondary">
            {isSearching ? t('mcpPanel.empty.searchTitle') : t('mcpPanel.empty.title')}
          </p>
          <p className="text-xs text-text-muted">
            {isSearching ? t('mcpPanel.empty.searchDescription') : t('mcpPanel.empty.description')}
          </p>
        </div>
      )}

      {displayServers.length > 0 && (
        <div className="mcp-servers-grid grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
          {displayServers.map((server) => (
            <McpServerCard
              key={server.id}
              server={server}
              isInstalled={isServerInstalled(server)}
              installedEntry={getInstalledEntry(server)}
              installedEntries={getInstalledEntries(server)}
              diagnostic={getDiagnostic(server)}
              diagnosticsLoading={mcpDiagnosticsLoading}
              onClick={setSelectedMcpServerId}
              cliStatus={cliStatus}
              cliStatusLoading={cliStatusLoading}
            />
          ))}
        </div>
      )}

      {/* Load more for browse */}
      {!isSearching && browseNextCursor && (
        <div className="flex justify-center py-4">
          <Button
            variant="outline"
            size="sm"
            disabled={browseLoading}
            onClick={() => void mcpBrowse(browseNextCursor)}
          >
            {t('mcpPanel.loadMore')}
          </Button>
        </div>
      )}

      {/* Detail dialog */}
      <McpServerDetailDialog
        server={selectedServer}
        isInstalled={selectedServer ? isServerInstalled(selectedServer) : false}
        installedEntry={selectedServer ? getInstalledEntry(selectedServer) : null}
        installedEntries={selectedServer ? getInstalledEntries(selectedServer) : []}
        diagnostic={selectedServer ? getDiagnostic(selectedServer) : null}
        diagnosticsLoading={mcpDiagnosticsLoading}
        projectPath={projectPath}
        open={selectedMcpServerId !== null}
        onClose={() => setSelectedMcpServerId(null)}
        cliStatus={cliStatus}
        cliStatusLoading={cliStatusLoading}
      />
    </div>
  );
};
