import React, { useMemo, useState, useEffect } from 'react';
import Box from '@mui/material/Box';
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Avatar from '@arcblock/ux/lib/Avatar';
import Stack from '@mui/material/Stack';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';
import Tabs from '@arcblock/ux/lib/Tabs';
import { useRequest } from 'ahooks';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import PropTypes from 'prop-types';
import CodeBlock from '@arcblock/ux/lib/CodeBlock';
import { SERVER_ROLES, WELLKNOWN_SERVICE_PATH_PREFIX } from '@abtnode/constant';
import IconButton from '@mui/material/IconButton';
import LaunchIcon from '@mui/icons-material/Launch';
import { joinURL } from 'ufo';
import { api as axiosAPI } from '../../util/api';
import Tip from '../table-tips';
import { useNodeContext } from '../../contexts/node';
import { useTeamContext } from '../../contexts/team';
import { useSessionContext } from '../../contexts/session';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function MCPLinkUI({
  endpoint
}) {
  const [activeTab, setActiveTab] = useState('mcp-link');
  const node = useNodeContext();
  const {
    api
  } = useNodeContext();
  const {
    teamDid
  } = useTeamContext();
  const {
    t,
    locale
  } = useLocaleContext();
  const {
    session
  } = useSessionContext();
  const {
    data: accessKeyResult,
    run: createAccessKey,
    loading: accessKeyLoading
  } = useRequest(() => {
    const map = {
      owner: SERVER_ROLES.ADMIN
    };
    const role = map[session?.user?.role] || session?.user?.role;
    return api.createAccessKey({
      input: {
        teamDid,
        passport: role,
        authType: 'simple',
        remark: 'Generated by MCP Servers'
      }
    });
  }, {
    manual: true
  });
  const {
    imgPrefix
  } = node;
  const tabs = useMemo(() => [{
    icon: /*#__PURE__*/_jsx(Box, {
      sx: {
        width: 20,
        height: 20
      },
      children: "\uD83D\uDD17"
    }),
    value: 'mcp-link',
    label: 'MCP Link'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/claude.webp`,
      alt: "Claude",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'claude',
    label: 'Claude'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/cursor.png`,
      alt: "Cursor",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'cursor',
    label: 'Cursor'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/cline.png`,
      alt: "Cline",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'cline',
    label: 'Cline'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/roocline.png`,
      alt: "Roo Cline",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'roo-cline',
    label: 'Roo Cline'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/windsurf.png`,
      alt: "Windsurf",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'windsurf',
    label: 'Windsurf'
  }, {
    icon: /*#__PURE__*/_jsx(Box, {
      component: "img",
      src: `${imgPrefix}/mcp/witsy.png`,
      alt: "Witsy",
      sx: {
        width: 20,
        height: 20
      }
    }),
    value: 'witsy',
    label: 'Witsy'
  }
  // {
  //   icon: <Box component="img" src={`${imgPrefix}/mcp/enconvo.png`} alt="Enconvo" sx={{ width: 20, height: 20 }} />,
  //   value: 'enconvo',
  //   label: 'Enconvo',
  // },
  ], [imgPrefix]);
  const currentTab = tabs.find(tab => tab.value === activeTab);
  const accessSecret = useMemo(() => accessKeyResult?.data?.accessKeySecret, [accessKeyResult]);
  const showGenerateButton = useMemo(() => !accessSecret && activeTab !== 'mcp-link', [accessSecret, activeTab]);
  const getCommandForClient = client => {
    const command = `npx @blocklet/install-mcp@latest i ${endpoint} --client ${client} --streamableHTTP --oauth2Bearer ${accessSecret}`;
    switch (client) {
      case 'cursor':
      case 'claude':
      case 'cline':
      case 'roo-cline':
      case 'windsurf':
      case 'witsy':
        return command;
      case 'mcp-link':
      default:
        return endpoint;
    }
  };
  return /*#__PURE__*/_jsxs(Box, {
    className: "mcp-servers-container",
    children: [/*#__PURE__*/_jsx(Tabs, {
      tabs: tabs,
      current: activeTab,
      onChange: setActiveTab,
      scrollButtons: "auto",
      iconPosition: "start"
    }), /*#__PURE__*/_jsxs(Box, {
      children: [/*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          alignItems: 'center',
          gap: 0.5
        },
        children: [/*#__PURE__*/_jsx(Typography, {
          component: "span",
          variant: "h6",
          sx: {
            fontWeight: 'bold',
            my: 2
          },
          children: activeTab === 'mcp-link' ? currentTab?.label : `${currentTab?.label} ${t('installCommand')}`
        }), activeTab !== 'mcp-link' && /*#__PURE__*/_jsx(Link, {
          href: `https://www.arcblock.io/docs/blocklet-developer/${locale}/mcp-${activeTab}`,
          target: "_blank",
          rel: "noopener noreferrer",
          children: /*#__PURE__*/_jsx(IconButton, {
            size: "small",
            children: /*#__PURE__*/_jsx(LaunchIcon, {
              fontSize: "small"
            })
          })
        })]
      }), /*#__PURE__*/_jsxs(Box, {
        className: "mcp-servers-codeblock",
        sx: {
          position: 'relative',
          '& pre': {
            borderRadius: 1
          },
          '& .codeblock__inner': {
            overflow: 'auto !important',
            borderRadius: 1
          }
        },
        children: [/*#__PURE__*/_jsx(CodeBlock, {
          code: getCommandForClient(activeTab),
          language: "shell",
          style: {
            margin: 0
          },
          showDefaultText: false
        }), showGenerateButton && /*#__PURE__*/_jsx(Box, {
          sx: {
            position: 'absolute',
            top: 0,
            right: 0,
            left: 0,
            bottom: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            bgcolor: 'action.active',
            backdropFilter: 'blur(3px)',
            WebkitBackdropFilter: 'blur(3px)',
            zIndex: 1
          },
          children: accessKeyLoading ? /*#__PURE__*/_jsx(CircularProgress, {}) : /*#__PURE__*/_jsx(Button, {
            variant: "contained",
            color: "primary",
            onClick: createAccessKey,
            size: "small",
            children: `${t('common.generate')} ${t('command')}`
          })
        })]
      })]
    })]
  });
}
MCPLinkUI.propTypes = {
  endpoint: PropTypes.string.isRequired
};
export default function MCPServersUI() {
  const [selectedServer, setSelectedServer] = useState(null);
  const {
    t,
    locale
  } = useLocaleContext();
  const SERVER_URL = joinURL(WELLKNOWN_SERVICE_PATH_PREFIX, '/mcp/servers');
  const {
    data: result,
    loading,
    error
  } = useRequest(() => Promise.all([axiosAPI.get(SERVER_URL)]));
  const servers = useMemo(() => result?.[0]?.data?.servers || [], [result]);
  useEffect(() => {
    if (servers?.length) {
      setSelectedServer(servers.find(x => x.did === window?.blocklet?.did) || servers[0]);
    }
  }, [servers]);
  const handleServerChange = e => {
    const did = e.target.value;
    setSelectedServer(servers.find(s => s.did === did));
  };
  if (loading) {
    return /*#__PURE__*/_jsx(Box, {
      children: /*#__PURE__*/_jsx(CircularProgress, {})
    });
  }
  if (error) {
    return /*#__PURE__*/_jsx(Alert, {
      color: "error",
      children: error?.message
    });
  }
  if (!servers?.length) {
    return /*#__PURE__*/_jsx(Alert, {
      color: "warning",
      children: t('mcp.noServer')
    });
  }
  return /*#__PURE__*/_jsxs(Stack, {
    sx: {
      gap: 2,
      maxWidth: 1200
    },
    children: [/*#__PURE__*/_jsx(Tip, {
      title: t('mcp.listTitle'),
      tooltipTitle: t('mcp.tooltipTitle'),
      link: `https://www.arcblock.io/docs/blocklet-developer/${locale}/mcp-server`
    }), /*#__PURE__*/_jsxs(FormControl, {
      fullWidth: true,
      children: [/*#__PURE__*/_jsx(InputLabel, {
        id: "server-select-label",
        children: t('mcp.available')
      }), /*#__PURE__*/_jsx(Select, {
        labelId: "server-select-label",
        value: selectedServer?.did || '',
        label: t('mcp.available'),
        onChange: handleServerChange,
        children: servers.map(server => /*#__PURE__*/_jsx(MenuItem, {
          value: server.did,
          children: /*#__PURE__*/_jsxs(Box, {
            sx: {
              display: 'flex',
              alignItems: 'center',
              gap: 1
            },
            children: [/*#__PURE__*/_jsx(Avatar, {
              variant: "rounded",
              shape: "square",
              did: server.did,
              src: server.logo,
              size: 20
            }), /*#__PURE__*/_jsx(Box, {
              sx: {
                fontSize: 14
              },
              children: server.name
            })]
          })
        }, server.did))
      })]
    }), selectedServer && /*#__PURE__*/_jsx(MCPLinkUI, {
      endpoint: selectedServer.endpoint
    })]
  });
}