import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMcpTools, useMcpConfig, useExecuteMcpTool } from '@/api/mcp';
import {
  useMcpServers,
  useCreateMcpServer,
  useUpdateMcpServer,
  useDeleteMcpServer,
  useMcpServerTools,
  type McpServerConfigEntry,
  type McpServerConfigCreate,
} from '@/api/mcpClient';

export function SettingsMcpPage() {
  const { t } = useTranslation();
  const { data: toolsData, isLoading: toolsLoading } = useMcpTools();
  const { data: config } = useMcpConfig();
  const executeMutation = useExecuteMcpTool();

  const { data: servers, isLoading: serversLoading } = useMcpServers();
  const createMutation = useCreateMcpServer();
  const updateMutation = useUpdateMcpServer();
  const deleteMutation = useDeleteMcpServer();

  const [showAddForm, setShowAddForm] = useState(false);
  const [editingServer, setEditingServer] = useState<McpServerConfigEntry | null>(null);
  const [selectedServerForTools, setSelectedServerForTools] = useState<string | null>(null);
  const [formData, setFormData] = useState<McpServerConfigCreate>({ name: '', url: '', api_token: '', enabled: true, description: '' });
  const [executeToolName, setExecuteToolName] = useState('');
  const [executeArgs, setExecuteArgs] = useState('{}');
  const [executeResult, setExecuteResult] = useState<string | null>(null);

  const { data: serverTools } = useMcpServerTools(selectedServerForTools);

  const handleAddServer = async () => {
    try {
      await createMutation.mutateAsync(formData);
      setShowAddForm(false);
      setFormData({ name: '', url: '', api_token: '', enabled: true, description: '' });
    } catch { /* error handled by mutation */ }
  };

  const handleUpdateServer = async () => {
    if (!editingServer) return;
    try {
      await updateMutation.mutateAsync({
        id: editingServer.id,
        payload: { name: formData.name, url: formData.url, api_token: formData.api_token, enabled: formData.enabled, description: formData.description },
      });
      setEditingServer(null);
      setShowAddForm(false);
      setFormData({ name: '', url: '', api_token: '', enabled: true, description: '' });
    } catch { /* error handled by mutation */ }
  };

  const handleDeleteServer = async (id: string) => {
    if (window.confirm(t('mcp.client.deleteConfirm'))) {
      await deleteMutation.mutateAsync(id);
    }
  };

  const handleEditServer = (server: McpServerConfigEntry) => {
    setEditingServer(server);
    setFormData({ name: server.name, url: server.url, api_token: server.api_token || '', enabled: server.enabled, description: server.description || '' });
    setShowAddForm(true);
  };

  const handleExecuteTool = async () => {
    if (!executeToolName) return;
    try {
      const args = JSON.parse(executeArgs);
      const result = await executeMutation.mutateAsync({ toolName: executeToolName, args });
      setExecuteResult(JSON.stringify(result, null, 2));
    } catch (e) {
      setExecuteResult(`Error: ${e}`);
    }
  };

  return (
    <div className="space-y-8" data-testid="settings-mcp-page">
      <div>
        <h2 className="text-2xl font-bold text-secondary-900">{t('mcp.title')}</h2>
      </div>

      {/* MCP Server Section */}
      <section className="bg-white rounded-lg border border-secondary-200 p-6">
        <h3 className="text-lg font-semibold mb-2">{t('mcp.server.title')}</h3>
        <p className="text-sm text-secondary-600 mb-4">{t('mcp.server.description')}</p>

        {config && (
          <div className="mb-4 p-3 bg-secondary-50 rounded text-sm">
            <div><strong>{t('mcp.server.serverName')}:</strong> {config.server_name}</div>
            <div><strong>{t('mcp.server.serverVersion')}:</strong> {config.server_version}</div>
            <div><strong>{t('mcp.server.protocolVersion')}:</strong> {config.protocol_version}</div>
            <div><strong>{t('mcp.server.authMethod')}:</strong> {config.auth_method}</div>
            <div><strong>{t('mcp.server.availableTools')}:</strong> {config.available_tools.join(', ')}</div>
          </div>
        )}

        {toolsLoading ? (
          <div className="text-secondary-500">Loading...</div>
        ) : toolsData && toolsData.tools.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead>
                <tr className="border-b border-secondary-200 text-left">
                  <th className="py-2 pr-4">{t('mcp.server.toolName')}</th>
                  <th className="py-2 pr-4">{t('mcp.server.toolDescription')}</th>
                  <th className="py-2 pr-4">{t('mcp.server.toolCategory')}</th>
                  <th className="py-2 pr-4">{t('mcp.server.toolPermission')}</th>
                </tr>
              </thead>
              <tbody>
                {toolsData.tools.map((tool) => (
                  <tr key={tool.name} className="border-b border-secondary-100">
                    <td className="py-2 pr-4 font-mono text-xs">{tool.name}</td>
                    <td className="py-2 pr-4">{tool.description}</td>
                    <td className="py-2 pr-4"><span className="px-2 py-0.5 bg-primary-100 text-primary-700 rounded text-xs">{tool.category}</span></td>
                    <td className="py-2 pr-4 font-mono text-xs">{tool.required_permission || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-secondary-500 text-sm">{t('mcp.server.noTools')}</div>
        )}

        {/* Tool Execution */}
        <div className="mt-6 pt-4 border-t border-secondary-200">
          <h4 className="font-medium mb-2">{t('mcp.server.executeTool')}</h4>
          <div className="flex gap-2 items-start">
            <select
              value={executeToolName}
              onChange={(e) => setExecuteToolName(e.target.value)}
              className="border border-secondary-300 rounded px-3 py-1.5 text-sm"
            >
              <option value="">-- Select --</option>
              {toolsData?.tools.map((tool) => (
                <option key={tool.name} value={tool.name}>{tool.name}</option>
              ))}
            </select>
            <input
              type="text"
              value={executeArgs}
              onChange={(e) => setExecuteArgs(e.target.value)}
              placeholder={t('mcp.server.arguments')}
              className="flex-1 border border-secondary-300 rounded px-3 py-1.5 text-sm font-mono"
            />
            <button
              onClick={handleExecuteTool}
              disabled={!executeToolName || executeMutation.isPending}
              className="px-4 py-1.5 bg-primary-600 text-white rounded text-sm hover:bg-primary-700 disabled:opacity-50"
            >
              {t('mcp.server.execute')}
            </button>
          </div>
          {executeResult && (
            <pre className="mt-2 p-3 bg-secondary-900 text-secondary-100 rounded text-xs overflow-x-auto max-h-60">{executeResult}</pre>
          )}
        </div>
      </section>

      {/* MCP Client Section */}
      <section className="bg-white rounded-lg border border-secondary-200 p-6">
        <div className="flex justify-between items-center mb-2">
          <h3 className="text-lg font-semibold">{t('mcp.client.title')}</h3>
          <button
            onClick={() => { setShowAddForm(!showAddForm); setEditingServer(null); setFormData({ name: '', url: '', api_token: '', enabled: true, description: '' }); }}
            className="px-3 py-1.5 bg-primary-600 text-white rounded text-sm hover:bg-primary-700"
          >
            {t('mcp.client.addServer')}
          </button>
        </div>
        <p className="text-sm text-secondary-600 mb-4">{t('mcp.client.description')}</p>

        {showAddForm && (
          <div className="mb-4 p-4 border border-secondary-200 rounded space-y-3">
            <div>
              <label className="block text-sm font-medium mb-1">{t('mcp.client.serverName')}</label>
              <input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} className="w-full border border-secondary-300 rounded px-3 py-1.5 text-sm" />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">{t('mcp.client.serverUrl')}</label>
              <input type="text" value={formData.url} onChange={(e) => setFormData({ ...formData, url: e.target.value })} className="w-full border border-secondary-300 rounded px-3 py-1.5 text-sm" />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">{t('mcp.client.apiToken')}</label>
              <input type="password" value={formData.api_token || ''} onChange={(e) => setFormData({ ...formData, api_token: e.target.value })} className="w-full border border-secondary-300 rounded px-3 py-1.5 text-sm" />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">{t('mcp.client.description')}</label>
              <input type="text" value={formData.description || ''} onChange={(e) => setFormData({ ...formData, description: e.target.value })} className="w-full border border-secondary-300 rounded px-3 py-1.5 text-sm" />
            </div>
            <div className="flex items-center gap-2">
              <input type="checkbox" id="mcp-enabled" checked={formData.enabled} onChange={(e) => setFormData({ ...formData, enabled: e.target.checked })} />
              <label htmlFor="mcp-enabled" className="text-sm">{t('mcp.client.enabled')}</label>
            </div>
            <div className="flex gap-2">
              <button onClick={editingServer ? handleUpdateServer : handleAddServer} className="px-4 py-1.5 bg-primary-600 text-white rounded text-sm hover:bg-primary-700">
                {editingServer ? t('mcp.client.editServer') : t('mcp.client.addServer')}
              </button>
              <button onClick={() => { setShowAddForm(false); setEditingServer(null); }} className="px-4 py-1.5 border border-secondary-300 rounded text-sm hover:bg-secondary-100">
                Cancel
              </button>
            </div>
          </div>
        )}

        {serversLoading ? (
          <div className="text-secondary-500">Loading...</div>
        ) : servers && servers.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead>
                <tr className="border-b border-secondary-200 text-left">
                  <th className="py-2 pr-4">{t('mcp.client.serverName')}</th>
                  <th className="py-2 pr-4">{t('mcp.client.serverUrl')}</th>
                  <th className="py-2 pr-4">{t('mcp.client.enabled')}</th>
                  <th className="py-2 pr-4">{t('mcp.client.lastConnected')}</th>
                  <th className="py-2 pr-4">Actions</th>
                </tr>
              </thead>
              <tbody>
                {servers.map((server) => (
                  <tr key={server.id} className="border-b border-secondary-100">
                    <td className="py-2 pr-4 font-medium">{server.name}</td>
                    <td className="py-2 pr-4 font-mono text-xs">{server.url}</td>
                    <td className="py-2 pr-4">
                      <span className={`px-2 py-0.5 rounded text-xs ${server.enabled ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                        {server.enabled ? '✓' : '✗'}
                      </span>
                    </td>
                    <td className="py-2 pr-4 text-xs text-secondary-500">{server.last_connected_at || '-'}</td>
                    <td className="py-2 pr-4">
                      <div className="flex gap-2">
                        <button onClick={() => handleEditServer(server)} className="text-xs text-primary-600 hover:underline">{t('mcp.client.editServer')}</button>
                        <button onClick={() => setSelectedServerForTools(selectedServerForTools === server.id ? null : server.id)} className="text-xs text-primary-600 hover:underline">{t('mcp.client.viewTools')}</button>
                        <button onClick={() => handleDeleteServer(server.id)} className="text-xs text-red-600 hover:underline">{t('mcp.client.deleteServer')}</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-secondary-500 text-sm">{t('mcp.client.noServers')}</div>
        )}

        {selectedServerForTools && serverTools && (
          <div className="mt-4 p-3 bg-secondary-50 rounded">
            <h4 className="font-medium text-sm mb-2">{t('mcp.client.tools')} ({serverTools.count})</h4>
            {serverTools.tools.length > 0 ? (
              <ul className="text-xs space-y-1">
                {serverTools.tools.map((tool) => (
                  <li key={tool.name} className="font-mono"><strong>{tool.name}</strong>: {tool.description}</li>
                ))}
              </ul>
            ) : (
              <span className="text-xs text-secondary-500">{t('mcp.client.noTools')}</span>
            )}
          </div>
        )}
      </section>
    </div>
  );
}
