'use client';

import { useState, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { useRouter, useParams } from 'next/navigation';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface ServerDetail {
  id: string;
  hostname: string;
  host: string;
  sshPort: number;
  environment: 'dev' | 'staging' | 'prod';
  role: string;
  status: 'online' | 'offline' | 'maintenance';
  tags: string[];
  description: string;
  jumpServerId?: string;
  jumpServerName?: string;
  credentialId?: string;
  credentialName?: string;
  os?: string;
  cpuCores?: number;
  memoryGb?: number;
  region?: string;
  cloudProvider?: string;
  createdAt: string;
  updatedAt: string;
}

interface ServerFormData {
  hostname: string;
  host: string;
  sshPort: number;
  environment: 'dev' | 'staging' | 'prod';
  role: string;
  tags: string;
  description: string;
}

interface HealthCheck {
  id: string;
  serverId: string;
  status: 'healthy' | 'unhealthy' | 'degraded' | 'timeout';
  latencyMs: number;
  message?: string;
  createdAt: string;
}

interface RecentCommand {
  id: string;
  command: string;
  exitCode: number | null;
  riskLevel: 'L0' | 'L1' | 'L2' | 'L3';
  createdAt: string;
}

type HealthChecksResponse = HealthCheck[];

type RecentCommandsResponse = RecentCommand[];

// ---------------------------------------------------------------------------
// Status badge
// ---------------------------------------------------------------------------

function StatusBadge({ status }: { status: ServerDetail['status'] }) {
  const styles: Record<ServerDetail['status'], string> = {
    online: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    offline: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    maintenance: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
  };

  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        styles[status],
      )}
    >
      {status}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Health check status badge
// ---------------------------------------------------------------------------

function HealthStatusBadge({ status }: { status: HealthCheck['status'] }) {
  const styles: Record<HealthCheck['status'], string> = {
    healthy: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    unhealthy: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    degraded: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    timeout: 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400',
  };

  return (
    <span
      className={cn(
        'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium capitalize',
        styles[status],
      )}
    >
      {status}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Risk level badge
// ---------------------------------------------------------------------------

function RiskBadge({ level }: { level: RecentCommand['riskLevel'] }) {
  const styles: Record<RecentCommand['riskLevel'], string> = {
    L0: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    L1: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    L2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    L3: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
  };

  return (
    <span
      className={cn(
        'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
        styles[level],
      )}
    >
      {level}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Delete confirmation dialog
// ---------------------------------------------------------------------------

function DeleteDialog({
  open,
  hostname,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  hostname: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('servers');
  const { t: tc } = useTranslation('common');

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative z-10 w-full max-w-sm bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-2">{t('deleteServer')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {t('dialog.deleteConfirm')} <strong>{hostname}</strong>? {t('dialog.deleteWarning')}
        </p>
        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={deleting}
          >
            {tc('cancel')}
          </button>
          <button
            onClick={onConfirm}
            disabled={deleting}
            className="px-4 py-2 text-sm rounded-md bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
          >
            {deleting ? tc('deleting') : tc('delete')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helper: format date
// ---------------------------------------------------------------------------

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return dateStr;
  }
}

function formatRelative(dateStr: string): string {
  try {
    const diff = Date.now() - new Date(dateStr).getTime();
    const seconds = Math.floor(diff / 1000);
    if (seconds < 60) return `${seconds}s ago`;
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    return `${days}d ago`;
  } catch {
    return dateStr;
  }
}

// ---------------------------------------------------------------------------
// Info row component
// ---------------------------------------------------------------------------

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 py-2">
      <dt className="text-sm text-muted-foreground sm:w-36 shrink-0">{label}</dt>
      <dd className="text-sm font-medium">{value || '--'}</dd>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function ServerDetailPage() {
  const { t } = useTranslation('servers');
  const { t: tc } = useTranslation('common');
  const router = useRouter();
  const params = useParams();
  const queryClient = useQueryClient();
  const id = params.id as string;

  // State ----------------------------------------------------------------
  const [isEditing, setIsEditing] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [form, setForm] = useState<ServerFormData>({
    hostname: '',
    host: '',
    sshPort: 22,
    environment: 'dev',
    role: '',
    tags: '',
    description: '',
  });
  const [errors, setErrors] = useState<Partial<Record<keyof ServerFormData, string>>>({});

  // Queries --------------------------------------------------------------
  const {
    data: server,
    isLoading,
    error,
  } = useQuery({
    queryKey: queryKeys.servers.detail(id),
    queryFn: () => apiClient<ServerDetail>(`/api/v1/inventory/servers/${id}`),
    enabled: !!id,
  });

  const { data: healthData } = useQuery({
    queryKey: queryKeys.healthChecks.list({ serverId: id, limit: '5' }),
    queryFn: () =>
      apiClient<HealthChecksResponse>(
        `/api/v1/monitor/health-checks?serverId=${id}&limit=5`,
      ),
    enabled: !!id,
  });

  const { data: commandsData } = useQuery({
    queryKey: ['commands', 'server', id],
    queryFn: () =>
      apiClient<RecentCommandsResponse>(
        `/api/v1/agent/commands?serverId=${id}&limit=10`,
      ),
    enabled: !!id,
  });

  const healthChecks = Array.isArray(healthData) ? healthData : [];
  const recentCommands = Array.isArray(commandsData) ? commandsData : [];

  // Mutations ------------------------------------------------------------
  const updateMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<ServerDetail>(`/api/v1/inventory/servers/${id}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.servers.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.servers.all });
      setIsEditing(false);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/inventory/servers/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.servers.all });
      router.push('/servers');
    },
  });

  const runHealthCheckMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/monitor/health-checks/${id}/run`, { method: 'POST' }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.healthChecks.list({ serverId: id, limit: '5' }),
      });
    },
  });

  // Helpers --------------------------------------------------------------
  const startEditing = useCallback(() => {
    if (!server) return;
    setForm({
      hostname: server.hostname,
      host: server.host,
      sshPort: server.sshPort,
      environment: server.environment,
      role: server.role ?? '',
      tags: (server.tags ?? []).join(', '),
      description: server.description ?? '',
    });
    setErrors({});
    setIsEditing(true);
  }, [server]);

  const cancelEditing = useCallback(() => {
    setIsEditing(false);
    setErrors({});
  }, []);

  const handleChange = useCallback(
    (field: keyof ServerFormData, value: string | number) => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    },
    [],
  );

  const validate = useCallback((): boolean => {
    const next: Partial<Record<keyof ServerFormData, string>> = {};
    if (!form.hostname.trim()) next.hostname = t('validation.hostnameRequired');
    if (!form.host.trim()) next.host = t('validation.hostRequired');
    setErrors(next);
    return Object.keys(next).length === 0;
  }, [form]);

  const handleSave = useCallback(() => {
    if (!validate()) return;
    const body: Record<string, unknown> = {
      hostname: form.hostname.trim(),
      host: form.host.trim(),
      sshPort: form.sshPort,
      environment: form.environment,
      role: form.role.trim(),
      tags: form.tags
        .split(',')
        .map((t) => t.trim())
        .filter(Boolean),
      description: form.description.trim(),
    };
    updateMutation.mutate(body);
  }, [form, validate, updateMutation]);

  // Render ---------------------------------------------------------------

  // Loading state
  if (isLoading) {
    return (
      <div>
        <button
          onClick={() => router.push('/servers')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToServers')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('detail.loading')}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/servers')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToServers')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('detail.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  if (!server) return null;

  const sshConnectionString = `ssh ${server.host} -p ${server.sshPort}`;

  return (
    <div>
      {/* Back link */}
      <button
        onClick={() => router.push('/servers')}
        className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="M19 12H5" />
          <path d="m12 19-7-7 7-7" />
        </svg>
        {t('detail.backToServers')}
      </button>

      {/* Page header */}
      <div className="flex items-center gap-3 mb-6">
        <h1 className="text-2xl font-bold">{server.hostname}</h1>
        <StatusBadge status={server.status} />
      </div>

      {/* Two-column layout */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Server Information Card */}
          <div className="bg-card border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.serverInformation')}</h2>
              {!isEditing && (
                <button
                  onClick={startEditing}
                  className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                >
                  {tc('edit')}
                </button>
              )}
            </div>

            {isEditing ? (
              /* ---------- Edit form ---------- */
              <div className="space-y-4">
                {/* hostname */}
                <div>
                  <label className="block text-sm font-medium mb-1">
                    {t('form.hostname')} <span className="text-destructive">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.hostname}
                    onChange={(e) => handleChange('hostname', e.target.value)}
                    className={cn(
                      'w-full px-3 py-2 rounded-md border bg-background text-sm',
                      errors.hostname ? 'border-destructive' : 'border-input',
                    )}
                    placeholder="web-server-01"
                  />
                  {errors.hostname && (
                    <p className="text-xs text-destructive mt-1">{errors.hostname}</p>
                  )}
                </div>

                {/* host */}
                <div>
                  <label className="block text-sm font-medium mb-1">
                    {t('form.hostIp')} <span className="text-destructive">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.host}
                    onChange={(e) => handleChange('host', e.target.value)}
                    className={cn(
                      'w-full px-3 py-2 rounded-md border bg-background text-sm',
                      errors.host ? 'border-destructive' : 'border-input',
                    )}
                    placeholder="192.168.1.100"
                  />
                  {errors.host && (
                    <p className="text-xs text-destructive mt-1">{errors.host}</p>
                  )}
                </div>

                {/* sshPort */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.sshPort')}</label>
                  <input
                    type="number"
                    value={form.sshPort}
                    onChange={(e) =>
                      handleChange('sshPort', parseInt(e.target.value, 10) || 22)
                    }
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                    min={1}
                    max={65535}
                  />
                </div>

                {/* environment */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.environment')}</label>
                  <select
                    value={form.environment}
                    onChange={(e) => handleChange('environment', e.target.value)}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                  >
                    <option value="dev">dev</option>
                    <option value="staging">staging</option>
                    <option value="prod">prod</option>
                  </select>
                </div>

                {/* role */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.role')}</label>
                  <input
                    type="text"
                    value={form.role}
                    onChange={(e) => handleChange('role', e.target.value)}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                    placeholder="web, db, cache..."
                  />
                </div>

                {/* tags */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.tags')}</label>
                  <input
                    type="text"
                    value={form.tags}
                    onChange={(e) => handleChange('tags', e.target.value)}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                    placeholder={t('form.tagsPlaceholder')}
                  />
                </div>

                {/* description */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.description')}</label>
                  <textarea
                    value={form.description}
                    onChange={(e) => handleChange('description', e.target.value)}
                    rows={3}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm resize-none"
                    placeholder={t('form.descriptionPlaceholder')}
                  />
                </div>

                {/* Update error */}
                {updateMutation.isError && (
                  <div className="p-3 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
                    {t('detail.loadError')} {(updateMutation.error as Error).message}
                  </div>
                )}

                {/* Save / Cancel */}
                <div className="flex justify-end gap-3 pt-2">
                  <button
                    type="button"
                    onClick={cancelEditing}
                    className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
                    disabled={updateMutation.isPending}
                  >
                    {tc('cancel')}
                  </button>
                  <button
                    type="button"
                    onClick={handleSave}
                    disabled={updateMutation.isPending}
                    className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
                  >
                    {updateMutation.isPending ? tc('saving') : t('detail.saveChanges')}
                  </button>
                </div>
              </div>
            ) : (
              /* ---------- Read-only info display ---------- */
              <dl className="divide-y">
                <InfoRow label={t('form.hostname')} value={server.hostname} />
                <InfoRow
                  label={t('form.hostIp')}
                  value={
                    <span className="font-mono text-xs">{server.host}</span>
                  }
                />
                <InfoRow label={t('form.sshPort')} value={String(server.sshPort)} />
                <InfoRow
                  label={t('form.environment')}
                  value={
                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-muted capitalize">
                      {server.environment}
                    </span>
                  }
                />
                <InfoRow label={t('form.role')} value={server.role} />
                <InfoRow label="OS" value={server.os} />
                {server.cpuCores != null && (
                  <InfoRow label="CPU Cores" value={String(server.cpuCores)} />
                )}
                {server.memoryGb != null && (
                  <InfoRow label="Memory" value={`${server.memoryGb} GB`} />
                )}
                {server.region && <InfoRow label="Region" value={server.region} />}
                {server.cloudProvider && (
                  <InfoRow label="Cloud Provider" value={server.cloudProvider} />
                )}
                <InfoRow
                  label={t('form.tags')}
                  value={
                    server.tags && server.tags.length > 0 ? (
                      <div className="flex flex-wrap gap-1.5">
                        {server.tags.map((tag) => (
                          <span
                            key={tag}
                            className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-muted"
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                    ) : null
                  }
                />
                <InfoRow label={t('form.description')} value={server.description} />
                <InfoRow label={tc('created')} value={formatDate(server.createdAt)} />
                <InfoRow label={tc('updated')} value={formatDate(server.updatedAt)} />
              </dl>
            )}
          </div>

          {/* Recent Health Checks */}
          <div className="bg-card border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.recentHealthChecks')}</h2>
              <button
                onClick={() => runHealthCheckMutation.mutate()}
                disabled={runHealthCheckMutation.isPending}
                className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors disabled:opacity-50"
              >
                {runHealthCheckMutation.isPending ? tc('running') : t('detail.runHealthCheck')}
              </button>
            </div>

            {runHealthCheckMutation.isError && (
              <div className="p-3 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
                Health check failed: {(runHealthCheckMutation.error as Error).message}
              </div>
            )}

            {runHealthCheckMutation.isSuccess && (
              <div className="p-3 mb-4 rounded-md border border-green-200 bg-green-50 text-green-800 dark:border-green-800 dark:bg-green-900/20 dark:text-green-400 text-sm">
                Health check initiated successfully.
              </div>
            )}

            {healthChecks.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">
                {t('detail.noHealthChecks')}
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="text-left px-3 py-2 font-medium">{t('detail.healthCheckTable.status')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.healthCheckTable.latency')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.healthCheckTable.message')}</th>
                      <th className="text-right px-3 py-2 font-medium">{t('detail.healthCheckTable.time')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {healthChecks.map((hc) => (
                      <tr
                        key={hc.id}
                        className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <td className="px-3 py-2">
                          <HealthStatusBadge status={hc.status} />
                        </td>
                        <td className="px-3 py-2 font-mono text-xs">
                          {hc.latencyMs}ms
                        </td>
                        <td className="px-3 py-2 text-muted-foreground truncate max-w-[200px]">
                          {hc.message || '--'}
                        </td>
                        <td className="px-3 py-2 text-right text-muted-foreground text-xs">
                          {formatRelative(hc.createdAt)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Recent Commands */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.recentCommands')}</h2>

            {recentCommands.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">
                {t('detail.noCommands')}
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="text-left px-3 py-2 font-medium">{t('detail.commandsTable.command')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.commandsTable.exitCode')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.commandsTable.risk')}</th>
                      <th className="text-right px-3 py-2 font-medium">{t('detail.commandsTable.time')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentCommands.map((cmd) => (
                      <tr
                        key={cmd.id}
                        className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <td className="px-3 py-2">
                          <code className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded max-w-[300px] truncate inline-block">
                            {cmd.command}
                          </code>
                        </td>
                        <td className="px-3 py-2">
                          <span
                            className={cn(
                              'font-mono text-xs',
                              cmd.exitCode === 0
                                ? 'text-green-600 dark:text-green-400'
                                : cmd.exitCode !== null
                                  ? 'text-red-600 dark:text-red-400'
                                  : 'text-muted-foreground',
                            )}
                          >
                            {cmd.exitCode !== null ? cmd.exitCode : '--'}
                          </span>
                        </td>
                        <td className="px-3 py-2">
                          <RiskBadge level={cmd.riskLevel} />
                        </td>
                        <td className="px-3 py-2 text-right text-muted-foreground text-xs">
                          {formatRelative(cmd.createdAt)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Quick Actions */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.quickActions')}</h2>
            <div className="space-y-2">
              <button
                onClick={() => router.push(`/terminal?serverId=${server.id}`)}
                className="w-full px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="4 17 10 11 4 5" />
                  <line x1="12" x2="20" y1="19" y2="19" />
                </svg>
                {t('detail.openTerminal')}
              </button>
              <button
                onClick={() => runHealthCheckMutation.mutate()}
                disabled={runHealthCheckMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors text-left flex items-center gap-2 disabled:opacity-50"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
                </svg>
                {runHealthCheckMutation.isPending ? tc('running') : t('detail.runHealthCheck')}
              </button>
              <button
                onClick={startEditing}
                className="w-full px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
                  <path d="m15 5 4 4" />
                </svg>
                {t('detail.editServer')}
              </button>
              <button
                onClick={() => setDeleteOpen(true)}
                className="w-full px-4 py-2 text-sm rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M3 6h18" />
                  <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
                  <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
                  <line x1="10" x2="10" y1="11" y2="17" />
                  <line x1="14" x2="14" y1="11" y2="17" />
                </svg>
                {t('detail.deleteServer')}
              </button>
            </div>
          </div>

          {/* Connection Info */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.connectionInfo')}</h2>
            <div className="space-y-3">
              <div>
                <p className="text-sm text-muted-foreground mb-1">SSH Connection</p>
                <div className="font-mono text-xs bg-muted p-2 rounded select-all">
                  {sshConnectionString}
                </div>
              </div>

              {server.jumpServerName && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Jump Server</p>
                  <p className="text-sm font-medium">{server.jumpServerName}</p>
                </div>
              )}

              {server.credentialName && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Credential</p>
                  <button
                    onClick={() =>
                      router.push(`/credentials?highlight=${server.credentialId}`)
                    }
                    className="text-sm font-medium text-primary hover:underline"
                  >
                    {server.credentialName}
                  </button>
                </div>
              )}

              {!server.jumpServerName && !server.credentialName && (
                <p className="text-sm text-muted-foreground">
                  No jump server or credential configured.
                </p>
              )}
            </div>
          </div>

          {/* Tags */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.tags')}</h2>
            {server.tags && server.tags.length > 0 ? (
              <div className="flex flex-wrap gap-2">
                {server.tags.map((tag) => (
                  <span
                    key={tag}
                    className="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-muted"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">{t('detail.noTags')}</p>
            )}
          </div>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={deleteOpen}
        hostname={server.hostname}
        deleting={deleteMutation.isPending}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate()}
      />
    </div>
  );
}
