'use client';

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

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

interface StandingOrder {
  id: string;
  name: string;
  description: string;
  triggerType: 'cron' | 'event' | 'threshold';
  triggerConfig: {
    cronExpression?: string;
    eventType?: string;
    metric?: string;
    condition?: string;
    thresholdValue?: number;
  };
  agentInstruction: string;
  targetServers: string[];
  maxBudgetUsd: number;
  escalateOnFailure: boolean;
  status: 'active' | 'paused';
  lastExecutionAt?: string;
  nextRunAt?: string;
  createdAt: string;
  updatedAt: string;
}

interface StandingOrderExecution {
  id: string;
  standingOrderId: string;
  status: 'running' | 'completed' | 'failed';
  startedAt: string;
  endedAt?: string;
  durationMs?: number;
  commandCount: number;
  summary?: string;
}

interface StandingOrderStats {
  totalExecutions: number;
  successRate: number;
  avgDurationMs: number;
  lastFailureAt?: string;
}

type ExecutionsResponse = StandingOrderExecution[];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function formatDuration(ms: number): string {
  if (ms < 1000) return `${ms}ms`;
  const seconds = Math.floor(ms / 1000);
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}h ${remainingMinutes}m`;
}

function formatDate(dateStr: string): string {
  const date = new Date(dateStr);
  return date.toLocaleString();
}

function formatRelativeTime(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffSeconds = Math.floor(diffMs / 1000);

  if (diffSeconds < 0) {
    const absDiff = Math.abs(diffSeconds);
    if (absDiff < 60) return `in ${absDiff}s`;
    const minutes = Math.floor(absDiff / 60);
    if (minutes < 60) return `in ${minutes}m`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `in ${hours}h`;
    const days = Math.floor(hours / 24);
    return `in ${days}d`;
  }

  if (diffSeconds < 60) return `${diffSeconds}s ago`;
  const minutes = Math.floor(diffSeconds / 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`;
}

function describeCron(expression: string): string {
  const parts = expression.trim().split(/\s+/);
  if (parts.length < 5) return expression;

  const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;

  if (minute === '0' && hour !== '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
    const h = parseInt(hour, 10);
    const ampm = h >= 12 ? 'PM' : 'AM';
    const displayHour = h === 0 ? 12 : h > 12 ? h - 12 : h;
    return `Every day at ${displayHour}:00 ${ampm}`;
  }
  if (minute !== '*' && hour !== '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
    const h = parseInt(hour, 10);
    const m = parseInt(minute, 10);
    const ampm = h >= 12 ? 'PM' : 'AM';
    const displayHour = h === 0 ? 12 : h > 12 ? h - 12 : h;
    return `Every day at ${displayHour}:${m.toString().padStart(2, '0')} ${ampm}`;
  }
  if (minute === '*' && hour === '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
    return 'Every minute';
  }
  if (minute.startsWith('*/')) {
    const interval = minute.slice(2);
    return `Every ${interval} minutes`;
  }
  if (hour.startsWith('*/')) {
    const interval = hour.slice(2);
    return `Every ${interval} hours`;
  }
  if (dayOfWeek === '1-5' || dayOfWeek === 'MON-FRI') {
    const h = parseInt(hour, 10);
    const m = parseInt(minute, 10);
    if (!isNaN(h) && !isNaN(m)) {
      const ampm = h >= 12 ? 'PM' : 'AM';
      const displayHour = h === 0 ? 12 : h > 12 ? h - 12 : h;
      return `Weekdays at ${displayHour}:${m.toString().padStart(2, '0')} ${ampm}`;
    }
  }
  if (dayOfWeek === '0' || dayOfWeek === 'SUN') {
    return `Sundays at ${hour}:${minute.padStart(2, '0')}`;
  }

  return expression;
}

// ---------------------------------------------------------------------------
// Badge components
// ---------------------------------------------------------------------------

function StatusBadge({ status }: { status: StandingOrder['status'] }) {
  const styles: Record<StandingOrder['status'], string> = {
    active: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    paused: '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>
  );
}

function TriggerBadge({ triggerType }: { triggerType: StandingOrder['triggerType'] }) {
  const styles: Record<StandingOrder['triggerType'], string> = {
    cron: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
    event: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    threshold: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
  };

  const labels: Record<StandingOrder['triggerType'], string> = {
    cron: 'Cron Schedule',
    event: 'Event Trigger',
    threshold: 'Threshold',
  };

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

function ExecutionStatusBadge({ status }: { status: StandingOrderExecution['status'] }) {
  const styles: Record<StandingOrderExecution['status'], string> = {
    running: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    failed: '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.5 py-0.5 rounded-full text-xs font-medium capitalize',
        styles[status],
      )}
    >
      {status}
    </span>
  );
}

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

function DeleteDialog({
  open,
  name,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  name: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('standing-orders');
  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('deleteDialog.title')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {t('deleteDialog.message')}
        </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>
  );
}

// ---------------------------------------------------------------------------
// Edit dialog
// ---------------------------------------------------------------------------

interface EditFormData {
  name: string;
  description: string;
  agentInstruction: string;
  targetServers: string;
  maxBudgetUsd: string;
  escalateOnFailure: boolean;
}

function EditDialog({
  open,
  order,
  saving,
  onClose,
  onSubmit,
}: {
  open: boolean;
  order: StandingOrder | null;
  saving: boolean;
  onClose: () => void;
  onSubmit: (data: EditFormData) => void;
}) {
  const { t } = useTranslation('standing-orders');
  const { t: tc } = useTranslation('common');

  const [form, setForm] = useState<EditFormData>({
    name: '',
    description: '',
    agentInstruction: '',
    targetServers: '',
    maxBudgetUsd: '',
    escalateOnFailure: false,
  });

  const [initialized, setInitialized] = useState<string | null>(null);

  // Reset form when dialog opens with a different order
  if (open && order && initialized !== order.id) {
    setForm({
      name: order.name,
      description: order.description,
      agentInstruction: order.agentInstruction,
      targetServers: order.targetServers.join(', '),
      maxBudgetUsd: order.maxBudgetUsd.toString(),
      escalateOnFailure: order.escalateOnFailure,
    });
    setInitialized(order.id);
  }

  if (!open && initialized !== null) {
    setInitialized(null);
  }

  if (!open || !order) 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-lg bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-4">{t('detail.editStandingOrder')}</h2>

        <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-1">
          {/* Name */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('form.name')}</label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
            />
          </div>

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

          {/* Agent Instruction */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('form.agentInstruction')}</label>
            <textarea
              value={form.agentInstruction}
              onChange={(e) => setForm((prev) => ({ ...prev, agentInstruction: e.target.value }))}
              rows={5}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm font-mono resize-y"
            />
          </div>

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

          {/* Max Budget */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('form.maxBudget')}</label>
            <input
              type="number"
              min="0"
              step="0.01"
              value={form.maxBudgetUsd}
              onChange={(e) => setForm((prev) => ({ ...prev, maxBudgetUsd: e.target.value }))}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
            />
          </div>

          {/* Escalate On Failure */}
          <div>
            <label className="flex items-center gap-2 text-sm cursor-pointer">
              <input
                type="checkbox"
                checked={form.escalateOnFailure}
                onChange={(e) =>
                  setForm((prev) => ({ ...prev, escalateOnFailure: e.target.checked }))
                }
                className="accent-primary h-4 w-4"
              />
              {t('form.escalateOnFailure')}
            </label>
          </div>
        </div>

        <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={saving}
          >
            {tc('cancel')}
          </button>
          <button
            type="button"
            onClick={() => onSubmit(form)}
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
          >
            {saving ? tc('saving') : tc('save')}
          </button>
        </div>
      </div>
    </div>
  );
}

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

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

  // State -----------------------------------------------------------------
  const [executionPage, setExecutionPage] = useState(0);
  const [expandedExecutionId, setExpandedExecutionId] = useState<string | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);

  const PAGE_SIZE = 10;

  // Queries ---------------------------------------------------------------
  const {
    data: order,
    isLoading,
    error,
  } = useQuery<StandingOrder>({
    queryKey: queryKeys.standingOrders.detail(id),
    queryFn: () => apiClient<StandingOrder>(`/api/v1/ops/standing-orders/${id}`),
    enabled: !!id,
  });

  const {
    data: executionsData,
    isLoading: executionsLoading,
    error: executionsError,
  } = useQuery<ExecutionsResponse>({
    queryKey: [...queryKeys.standingOrders.executions(id), executionPage],
    queryFn: () =>
      apiClient<ExecutionsResponse>(
        `/api/v1/ops/standing-orders/${id}/executions?page=${executionPage}&limit=${PAGE_SIZE}`,
      ),
    enabled: !!id,
  });

  const executions = Array.isArray(executionsData) ? executionsData : [];
  const totalExecutions = executions.length;
  const totalPages = Math.ceil(totalExecutions / PAGE_SIZE);

  // Compute stats from executions data
  const stats: StandingOrderStats = (() => {
    if (!executionsData || executions.length === 0) {
      return { totalExecutions: 0, successRate: 0, avgDurationMs: 0 };
    }
    const allExecs = executions;
    const total = executions.length;
    const completed = allExecs.filter((e) => e.status === 'completed').length;
    const rate = total > 0 ? (completed / total) * 100 : 0;
    const durations = allExecs.filter((e) => e.durationMs != null).map((e) => e.durationMs!);
    const avgDur =
      durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0;
    const failures = allExecs
      .filter((e) => e.status === 'failed' && e.endedAt)
      .sort((a, b) => new Date(b.endedAt!).getTime() - new Date(a.endedAt!).getTime());
    return {
      totalExecutions: total,
      successRate: rate,
      avgDurationMs: avgDur,
      lastFailureAt: failures[0]?.endedAt,
    };
  })();

  // Mutations -------------------------------------------------------------
  const toggleStatusMutation = useMutation({
    mutationFn: (newStatus: 'active' | 'paused') =>
      apiClient<StandingOrder>(`/api/v1/ops/standing-orders/${id}`, {
        method: 'PATCH',
        body: { status: newStatus },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.all });
    },
  });

  const updateMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<StandingOrder>(`/api/v1/ops/standing-orders/${id}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.all });
      setEditOpen(false);
    },
  });

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

  const executeNowMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/ops/standing-orders/${id}/execute`, { method: 'POST' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.executions(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.detail(id) });
    },
  });

  const toggleEscalateMutation = useMutation({
    mutationFn: (escalateOnFailure: boolean) =>
      apiClient<StandingOrder>(`/api/v1/ops/standing-orders/${id}`, {
        method: 'PATCH',
        body: { escalateOnFailure },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.detail(id) });
    },
  });

  // Handlers --------------------------------------------------------------
  const handleToggleStatus = useCallback(() => {
    if (!order) return;
    toggleStatusMutation.mutate(order.status === 'active' ? 'paused' : 'active');
  }, [order, toggleStatusMutation]);

  const handleEditSubmit = useCallback(
    (data: EditFormData) => {
      updateMutation.mutate({
        name: data.name.trim(),
        description: data.description.trim(),
        agentInstruction: data.agentInstruction.trim(),
        targetServers: data.targetServers
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean),
        maxBudgetUsd: parseFloat(data.maxBudgetUsd) || 0,
        escalateOnFailure: data.escalateOnFailure,
      });
    },
    [updateMutation],
  );

  const handleExecuteNow = useCallback(() => {
    executeNowMutation.mutate();
  }, [executeNowMutation]);

  const handleDelete = useCallback(() => {
    deleteMutation.mutate();
  }, [deleteMutation]);

  const handleToggleEscalate = useCallback(() => {
    if (!order) return;
    toggleEscalateMutation.mutate(!order.escalateOnFailure);
  }, [order, toggleEscalateMutation]);

  // Render: Loading -------------------------------------------------------
  if (isLoading) {
    return (
      <div className="text-sm text-muted-foreground py-12 text-center">
        {t('detail.loading')}
      </div>
    );
  }

  // Render: Error ---------------------------------------------------------
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/standing-orders')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('detail.backToStandingOrders')}
        </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 (!order) {
    return (
      <div>
        <button
          onClick={() => router.push('/standing-orders')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('detail.backToStandingOrders')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('detail.notFound')}
        </div>
      </div>
    );
  }

  // Render: Detail --------------------------------------------------------
  return (
    <div>
      {/* Header */}
      <div className="mb-6">
        <button
          onClick={() => router.push('/standing-orders')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1 transition-colors"
        >
          &larr; {t('detail.backToStandingOrders')}
        </button>

        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold">{order.name}</h1>
            <StatusBadge status={order.status} />
            <TriggerBadge triggerType={order.triggerType} />
          </div>

          <button
            onClick={handleToggleStatus}
            disabled={toggleStatusMutation.isPending}
            className={cn(
              'px-4 py-2 text-sm rounded-md font-medium transition-colors disabled:opacity-50 whitespace-nowrap',
              order.status === 'active'
                ? 'border border-yellow-500/50 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/10'
                : 'bg-green-600 text-white hover:bg-green-600/90',
            )}
          >
            {toggleStatusMutation.isPending
              ? tc('loading')
              : order.status === 'active'
                ? t('detail.pauseOrder')
                : t('detail.activateOrder')}
          </button>
        </div>

        {order.description && (
          <p className="text-sm text-muted-foreground mt-2">{order.description}</p>
        )}
      </div>

      {/* Two-column layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left column (col-span-2) */}
        <div className="lg:col-span-2 space-y-6">
          {/* Overview card */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('detail.overview')}</h2>
            </div>
            <div className="px-6 py-4 space-y-5">
              {/* Trigger configuration */}
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-2">
                  {t('detail.triggerConfiguration')}
                </h3>
                <div className="bg-muted/50 rounded-md p-3 space-y-1">
                  {order.triggerType === 'cron' && (
                    <>
                      <div className="flex items-center gap-2 text-sm">
                        <span className="text-muted-foreground">{t('detail.expression')}</span>
                        <code className="font-mono text-xs bg-background px-2 py-0.5 rounded border">
                          {order.triggerConfig.cronExpression ?? '--'}
                        </code>
                      </div>
                      {order.triggerConfig.cronExpression && (
                        <div className="text-sm text-muted-foreground">
                          {describeCron(order.triggerConfig.cronExpression)}
                        </div>
                      )}
                    </>
                  )}
                  {order.triggerType === 'event' && (
                    <div className="flex items-center gap-2 text-sm">
                      <span className="text-muted-foreground">{t('detail.eventType')}</span>
                      <code className="font-mono text-xs bg-background px-2 py-0.5 rounded border">
                        {order.triggerConfig.eventType ?? '--'}
                      </code>
                    </div>
                  )}
                  {order.triggerType === 'threshold' && (
                    <>
                      <div className="flex items-center gap-2 text-sm">
                        <span className="text-muted-foreground">{t('form.metric')}:</span>
                        <span className="font-medium">{order.triggerConfig.metric ?? '--'}</span>
                      </div>
                      <div className="flex items-center gap-2 text-sm">
                        <span className="text-muted-foreground">{t('form.condition')}:</span>
                        <span className="font-medium">
                          {order.triggerConfig.condition ?? '>='}{' '}
                          {order.triggerConfig.thresholdValue ?? '--'}
                        </span>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* Agent instruction */}
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-2">
                  {t('detail.agentInstruction')}
                </h3>
                <div className="bg-gray-950 text-gray-200 font-mono text-sm p-4 rounded-md whitespace-pre-wrap">
                  {order.agentInstruction}
                </div>
              </div>

              {/* Target servers */}
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-2">{t('detail.targetServers')}</h3>
                {order.targetServers.length === 0 ? (
                  <p className="text-sm text-muted-foreground">{t('detail.noTargetServers')}</p>
                ) : (
                  <div className="flex flex-wrap gap-2">
                    {order.targetServers.map((server) => (
                      <span
                        key={server}
                        className="inline-flex items-center px-2.5 py-1 rounded-md bg-muted text-sm font-mono"
                      >
                        {server}
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* Max budget */}
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">{t('detail.maxBudget')}</h3>
                <p className="text-sm font-medium">${order.maxBudgetUsd.toFixed(2)} USD</p>
              </div>
            </div>
          </div>

          {/* Execution History */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('executionHistory.title')}</h2>
            </div>

            {executionsLoading && (
              <div className="text-sm text-muted-foreground py-12 text-center">
                {t('executionHistory.loading')}
              </div>
            )}

            {executionsError && (
              <div className="p-4 mx-6 my-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
                {t('executionHistory.loadError')} {(executionsError as Error).message}
              </div>
            )}

            {!executionsLoading && !executionsError && (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b bg-muted/50">
                        <th className="w-8 px-4 py-3" />
                        <th className="text-left px-4 py-3 font-medium">{t('executionHistory.table.date')}</th>
                        <th className="text-left px-4 py-3 font-medium">{t('executionHistory.table.status')}</th>
                        <th className="text-left px-4 py-3 font-medium">{t('executionHistory.table.duration')}</th>
                        <th className="text-right px-4 py-3 font-medium">{t('executionHistory.table.commands')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {executions.length === 0 ? (
                        <tr>
                          <td colSpan={5} className="text-center text-muted-foreground py-12">
                            {t('executionHistory.empty')}
                          </td>
                        </tr>
                      ) : (
                        executions.map((exec) => (
                          <>
                            <tr
                              key={exec.id}
                              className={cn(
                                'border-b hover:bg-muted/30 transition-colors cursor-pointer',
                                expandedExecutionId === exec.id && 'bg-muted/20',
                              )}
                              onClick={() =>
                                setExpandedExecutionId(
                                  expandedExecutionId === exec.id ? null : exec.id,
                                )
                              }
                            >
                              <td className="px-4 py-3 text-muted-foreground">
                                <span
                                  className={cn(
                                    'inline-block transition-transform text-xs',
                                    expandedExecutionId === exec.id && 'rotate-90',
                                  )}
                                >
                                  &#9654;
                                </span>
                              </td>
                              <td className="px-4 py-3">
                                <div className="text-sm">{formatDate(exec.startedAt)}</div>
                                <div className="text-xs text-muted-foreground">
                                  {formatRelativeTime(exec.startedAt)}
                                </div>
                              </td>
                              <td className="px-4 py-3">
                                <ExecutionStatusBadge status={exec.status} />
                              </td>
                              <td className="px-4 py-3 text-muted-foreground">
                                {exec.durationMs != null
                                  ? formatDuration(exec.durationMs)
                                  : exec.status === 'running'
                                    ? t('executionHistory.inProgress')
                                    : '--'}
                              </td>
                              <td className="px-4 py-3 text-right tabular-nums">
                                {exec.commandCount}
                              </td>
                            </tr>

                            {/* Expanded details */}
                            {expandedExecutionId === exec.id && (
                              <tr key={`${exec.id}-details`}>
                                <td colSpan={5} className="bg-muted/10 border-b px-6 py-4">
                                  <div>
                                    <h4 className="text-xs font-semibold uppercase text-muted-foreground mb-2">
                                      {t('executionHistory.executionSummary')}
                                    </h4>
                                    {exec.summary ? (
                                      <p className="text-sm text-foreground whitespace-pre-wrap">
                                        {exec.summary}
                                      </p>
                                    ) : (
                                      <p className="text-sm text-muted-foreground italic">
                                        {t('executionHistory.noSummary')}
                                      </p>
                                    )}
                                    <div className="mt-3 flex gap-4 text-xs text-muted-foreground">
                                      <span>{t('executionHistory.started')} {formatDate(exec.startedAt)}</span>
                                      {exec.endedAt && (
                                        <span>{t('executionHistory.ended')} {formatDate(exec.endedAt)}</span>
                                      )}
                                    </div>
                                  </div>
                                </td>
                              </tr>
                            )}
                          </>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                  <div className="flex items-center justify-between px-6 py-3 border-t">
                    <div className="text-xs text-muted-foreground">
                      {t('detail.pagination.showing', { from: executionPage * PAGE_SIZE + 1, to: Math.min((executionPage + 1) * PAGE_SIZE, totalExecutions), total: totalExecutions })}
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => setExecutionPage((p) => Math.max(0, p - 1))}
                        disabled={executionPage === 0}
                        className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {t('detail.pagination.previous')}
                      </button>
                      <span className="text-xs text-muted-foreground">
                        {t('detail.pagination.pageOf', { current: executionPage + 1, total: totalPages })}
                      </span>
                      <button
                        onClick={() => setExecutionPage((p) => Math.min(totalPages - 1, p + 1))}
                        disabled={executionPage >= totalPages - 1}
                        className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {t('detail.pagination.next')}
                      </button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* Right column (col-span-1) */}
        <div className="space-y-6">
          {/* Status & Controls card */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('detail.statusAndControls')}</h2>
            </div>
            <div className="px-6 py-4 space-y-4">
              {/* Status toggle */}
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('status')}</span>
                <div className="flex items-center gap-2">
                  <StatusBadge status={order.status} />
                  <button
                    onClick={handleToggleStatus}
                    disabled={toggleStatusMutation.isPending}
                    className={cn(
                      'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
                      order.status === 'active' ? 'bg-green-500' : 'bg-muted',
                    )}
                    title={
                      order.status === 'active'
                        ? 'Active (click to pause)'
                        : 'Paused (click to activate)'
                    }
                  >
                    <span
                      className={cn(
                        'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
                        order.status === 'active'
                          ? 'translate-x-[18px]'
                          : 'translate-x-[3px]',
                      )}
                    />
                  </button>
                </div>
              </div>

              {/* Escalate on Failure toggle */}
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.escalateOnFailure')}</span>
                <button
                  onClick={handleToggleEscalate}
                  disabled={toggleEscalateMutation.isPending}
                  className={cn(
                    'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
                    order.escalateOnFailure ? 'bg-green-500' : 'bg-muted',
                  )}
                  title={
                    order.escalateOnFailure
                      ? 'Enabled (click to disable)'
                      : 'Disabled (click to enable)'
                  }
                >
                  <span
                    className={cn(
                      'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
                      order.escalateOnFailure
                        ? 'translate-x-[18px]'
                        : 'translate-x-[3px]',
                    )}
                  />
                </button>
              </div>

              {/* Last execution */}
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.lastExecution')}</span>
                <span className="text-sm">
                  {order.lastExecutionAt ? formatRelativeTime(order.lastExecutionAt) : tc('never')}
                </span>
              </div>

              {/* Next scheduled run */}
              {order.triggerType === 'cron' && (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">{t('detail.nextRun')}</span>
                  <span className="text-sm">
                    {order.nextRunAt ? formatRelativeTime(order.nextRunAt) : '--'}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Quick Actions card */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('detail.quickActions')}</h2>
            </div>
            <div className="px-6 py-4 space-y-2">
              <button
                onClick={handleExecuteNow}
                disabled={executeNowMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
              >
                {executeNowMutation.isPending ? t('detail.triggering') : t('detail.executeNow')}
              </button>

              {executeNowMutation.isSuccess && (
                <p className="text-xs text-green-600 dark:text-green-400">
                  {t('detail.executionTriggered')}
                </p>
              )}

              {executeNowMutation.error && (
                <p className="text-xs text-destructive">
                  {(executeNowMutation.error as Error).message}
                </p>
              )}

              <button
                onClick={() => setEditOpen(true)}
                className="w-full px-4 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors"
              >
                {t('detail.edit')}
              </button>

              <button
                onClick={() => router.push(`/audit/logs?standingOrderId=${id}`)}
                className="w-full px-4 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors"
              >
                {t('detail.viewLogs')}
              </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"
              >
                {t('detail.delete')}
              </button>
            </div>
          </div>

          {/* Statistics card */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('detail.statistics')}</h2>
            </div>
            <div className="px-6 py-4 space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.stats.totalExecutions')}</span>
                <span className="text-sm font-medium tabular-nums">{stats.totalExecutions}</span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.stats.successRate')}</span>
                <span
                  className={cn(
                    'text-sm font-medium tabular-nums',
                    stats.successRate >= 90
                      ? 'text-green-600 dark:text-green-400'
                      : stats.successRate >= 50
                        ? 'text-yellow-600 dark:text-yellow-400'
                        : 'text-red-600 dark:text-red-400',
                  )}
                >
                  {stats.successRate.toFixed(1)}%
                </span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.stats.avgDuration')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {stats.avgDurationMs > 0 ? formatDuration(stats.avgDurationMs) : '--'}
                </span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.stats.lastFailure')}</span>
                <span className="text-sm">
                  {stats.lastFailureAt ? formatRelativeTime(stats.lastFailureAt) : tc('none')}
                </span>
              </div>
            </div>
          </div>

          {/* Metadata */}
          <div className="border rounded-lg">
            <div className="px-6 py-4 border-b">
              <h2 className="text-base font-semibold">{t('detail.metadata')}</h2>
            </div>
            <div className="px-6 py-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('created')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(order.createdAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('updated')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(order.updatedAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('id')}</span>
                <code className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
                  {order.id}
                </code>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Edit dialog */}
      <EditDialog
        open={editOpen}
        order={order}
        saving={updateMutation.isPending}
        onClose={() => setEditOpen(false)}
        onSubmit={handleEditSubmit}
      />

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