'use client';

import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
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
// ---------------------------------------------------------------------------

type Severity = 'info' | 'warning' | 'critical' | 'fatal';
type Condition = '>' | '<' | '==' | '>=' | '<=';

interface AlertRuleDetail {
  id: string;
  name: string;
  description: string;
  metric: string;
  condition: Condition;
  threshold: number;
  severity: Severity;
  enabled: boolean;
  notifyChannels: string[];
  cooldownMinutes: number;
  createdAt: string;
  updatedAt: string;
}

interface AlertEvent {
  id: string;
  ruleId: string;
  ruleName: string;
  severity: Severity;
  metric: string;
  value: number;
  threshold: number;
  message: string;
  triggeredAt: string;
  resolvedAt?: string;
}

type AlertEventsResponse = AlertEvent[];

interface AlertRuleFormData {
  name: string;
  description: string;
  metric: string;
  condition: Condition;
  threshold: string;
  severity: Severity;
  notifyChannels: string;
  cooldownMinutes: string;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const SEVERITY_STYLES: Record<Severity, string> = {
  info: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  warning: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
  critical: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
  fatal: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

const CONDITIONS: { labelKey: string; value: Condition }[] = [
  { labelKey: 'alertRules.conditions.greaterThan', value: '>' },
  { labelKey: 'alertRules.conditions.lessThan', value: '<' },
  { labelKey: 'alertRules.conditions.equal', value: '==' },
  { labelKey: 'alertRules.conditions.greaterOrEqual', value: '>=' },
  { labelKey: 'alertRules.conditions.lessOrEqual', value: '<=' },
];

const SEVERITIES: { labelKey: string; value: Severity }[] = [
  { labelKey: 'alertRules.severities.info', value: 'info' },
  { labelKey: 'alertRules.severities.warning', value: 'warning' },
  { labelKey: 'alertRules.severities.critical', value: 'critical' },
  { labelKey: 'alertRules.severities.fatal', value: 'fatal' },
];

const COMMON_METRICS = [
  'cpu_usage',
  'memory_usage',
  'disk_usage',
  'network_latency',
  'http_error_rate',
  'response_time_p99',
  'active_connections',
  'queue_depth',
];

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

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

// ---------------------------------------------------------------------------
// Toggle switch
// ---------------------------------------------------------------------------

function ToggleSwitch({
  checked,
  disabled,
  onChange,
  label,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: (value: boolean) => void;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      disabled={disabled}
      className="flex items-center gap-2"
      title={label}
    >
      <span
        className={cn(
          'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
          checked ? 'bg-primary' : 'bg-muted',
          disabled && 'opacity-50 cursor-not-allowed',
        )}
      >
        <span
          className={cn(
            'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
            checked ? 'translate-x-[18px]' : 'translate-x-[3px]',
          )}
        />
      </span>
      <span className="text-sm">{label}</span>
    </button>
  );
}

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

function DeleteDialog({
  open,
  name,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  name: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('monitoring');
  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('alertRules.deleteRule')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {t('alertRules.deleteConfirm')} <strong>{name}</strong>
        </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-40 shrink-0">{label}</dt>
      <dd className="text-sm font-medium">{value || '--'}</dd>
    </div>
  );
}

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

export default function AlertRuleDetailPage() {
  const { t } = useTranslation('monitoring');
  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 [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [form, setForm] = useState<AlertRuleFormData>({
    name: '',
    description: '',
    metric: '',
    condition: '>',
    threshold: '',
    severity: 'warning',
    notifyChannels: '',
    cooldownMinutes: '5',
  });
  const [errors, setErrors] = useState<Partial<Record<keyof AlertRuleFormData, string>>>({});

  // Queries --------------------------------------------------------------
  const {
    data: rule,
    isLoading,
    error,
  } = useQuery<AlertRuleDetail>({
    queryKey: [...queryKeys.alerts.rules(), id],
    queryFn: () => apiClient<AlertRuleDetail>(`/api/v1/monitor/alerts/rules/${id}`),
    enabled: !!id,
  });

  const { data: eventsData } = useQuery<AlertEventsResponse>({
    queryKey: [...queryKeys.alerts.rules(), id, 'events'],
    queryFn: () =>
      apiClient<AlertEventsResponse>(
        `/api/v1/monitor/alerts/rules/${id}/events?limit=20`,
      ),
    enabled: !!id,
  });

  const alertEvents = Array.isArray(eventsData) ? eventsData : [];

  // Mutations ------------------------------------------------------------
  const updateMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<AlertRuleDetail>(`/api/v1/monitor/alerts/rules/${id}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [...queryKeys.alerts.rules(), id] });
      queryClient.invalidateQueries({ queryKey: queryKeys.alerts.rules() });
      setIsEditing(false);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/monitor/alerts/rules/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.alerts.rules() });
      router.push('/monitoring/alert-rules');
    },
  });

  const toggleMutation = useMutation({
    mutationFn: (enabled: boolean) =>
      apiClient<AlertRuleDetail>(`/api/v1/monitor/alerts/rules/${id}`, {
        method: 'PATCH',
        body: { enabled },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [...queryKeys.alerts.rules(), id] });
      queryClient.invalidateQueries({ queryKey: queryKeys.alerts.rules() });
    },
  });

  // Helpers --------------------------------------------------------------
  const startEditing = useCallback(() => {
    if (!rule) return;
    setForm({
      name: rule.name,
      description: rule.description,
      metric: rule.metric,
      condition: rule.condition,
      threshold: String(rule.threshold),
      severity: rule.severity,
      notifyChannels: rule.notifyChannels.join(', '),
      cooldownMinutes: String(rule.cooldownMinutes),
    });
    setErrors({});
    setIsEditing(true);
  }, [rule]);

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

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

  const validate = useCallback((): boolean => {
    const next: Partial<Record<keyof AlertRuleFormData, string>> = {};
    if (!form.name.trim()) next.name = 'Name is required';
    if (!form.metric.trim()) next.metric = 'Metric is required';
    if (!form.threshold.trim() || isNaN(Number(form.threshold))) {
      next.threshold = 'Valid threshold is required';
    }
    if (!form.cooldownMinutes.trim() || isNaN(Number(form.cooldownMinutes))) {
      next.cooldownMinutes = 'Valid cooldown is required';
    }
    setErrors(next);
    return Object.keys(next).length === 0;
  }, [form]);

  const handleSave = useCallback(() => {
    if (!validate()) return;
    const body: Record<string, unknown> = {
      name: form.name.trim(),
      description: form.description.trim(),
      metric: form.metric.trim(),
      condition: form.condition,
      threshold: parseFloat(form.threshold),
      severity: form.severity,
      notifyChannels: form.notifyChannels
        .split(',')
        .map((c) => c.trim())
        .filter(Boolean),
      cooldownMinutes: parseInt(form.cooldownMinutes, 10),
    };
    updateMutation.mutate(body);
  }, [form, validate, updateMutation]);

  const handleToggleEnabled = useCallback(
    (value: boolean) => {
      toggleMutation.mutate(value);
    },
    [toggleMutation],
  );

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

  // Loading state
  if (isLoading) {
    return (
      <div>
        <button
          onClick={() => router.push('/monitoring/alert-rules')}
          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('alertRules.detail.backToAlertRules')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('alertRules.detail.loading')}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/monitoring/alert-rules')}
          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('alertRules.detail.backToAlertRules')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('alertRules.detail.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  if (!rule) return null;

  return (
    <div>
      {/* Back link */}
      <button
        onClick={() => router.push('/monitoring/alert-rules')}
        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('alertRules.detail.backToAlertRules')}
      </button>

      {/* Page header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold">{rule.name}</h1>
          <SeverityBadge severity={rule.severity} />
          <span
            className={cn(
              'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
              rule.enabled
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
            )}
          >
            {rule.enabled ? tc('enabled') : tc('disabled')}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <ToggleSwitch
            checked={rule.enabled}
            disabled={toggleMutation.isPending}
            onChange={handleToggleEnabled}
            label={rule.enabled ? 'Enabled' : 'Disabled'}
          />
        </div>
      </div>

      {/* Mutation error banner */}
      {(updateMutation.error || toggleMutation.error) && (
        <div className="p-4 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {((updateMutation.error || toggleMutation.error) as Error).message}
        </div>
      )}

      {/* Two-column layout */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Alert Rule 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('alertRules.detail.ruleConfiguration')}</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">
                {/* name */}
                <div>
                  <label className="block text-sm font-medium mb-1">
                    {t('alertRules.form.name')} <span className="text-destructive">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    className={cn(
                      'w-full px-3 py-2 rounded-md border bg-background text-sm',
                      errors.name ? 'border-destructive' : 'border-input',
                    )}
                    placeholder="High CPU Usage"
                  />
                  {errors.name && (
                    <p className="text-xs text-destructive mt-1">{errors.name}</p>
                  )}
                </div>

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

                {/* metric */}
                <div>
                  <label className="block text-sm font-medium mb-1">
                    {t('alertRules.form.metric')} <span className="text-destructive">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.metric}
                    onChange={(e) => handleChange('metric', e.target.value)}
                    className={cn(
                      'w-full px-3 py-2 rounded-md border bg-background text-sm',
                      errors.metric ? 'border-destructive' : 'border-input',
                    )}
                    placeholder="cpu_usage"
                    list="metric-suggestions"
                  />
                  <datalist id="metric-suggestions">
                    {COMMON_METRICS.map((m) => (
                      <option key={m} value={m} />
                    ))}
                  </datalist>
                  {errors.metric && (
                    <p className="text-xs text-destructive mt-1">{errors.metric}</p>
                  )}
                </div>

                {/* condition + threshold */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium mb-1">{t('alertRules.form.condition')}</label>
                    <select
                      value={form.condition}
                      onChange={(e) => handleChange('condition', e.target.value)}
                      className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                    >
                      {CONDITIONS.map((c) => (
                        <option key={c.value} value={c.value}>
                          {t(c.labelKey)}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">
                      {t('alertRules.form.threshold')} <span className="text-destructive">*</span>
                    </label>
                    <input
                      type="number"
                      value={form.threshold}
                      onChange={(e) => handleChange('threshold', e.target.value)}
                      className={cn(
                        'w-full px-3 py-2 rounded-md border bg-background text-sm',
                        errors.threshold ? 'border-destructive' : 'border-input',
                      )}
                      placeholder="90"
                      step="any"
                    />
                    {errors.threshold && (
                      <p className="text-xs text-destructive mt-1">{errors.threshold}</p>
                    )}
                  </div>
                </div>

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

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

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

                {/* Update error */}
                {updateMutation.isError && (
                  <div className="p-3 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
                    {t('alertRules.detail.failedToUpdate')} {(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') : tc('save')}
                  </button>
                </div>
              </div>
            ) : (
              /* ---------- Read-only info display ---------- */
              <dl className="divide-y">
                <InfoRow label={t('alertRules.form.name')} value={rule.name} />
                <InfoRow
                  label={t('alertRules.form.description')}
                  value={rule.description || t('alertRules.detail.noDescription')}
                />
                <InfoRow
                  label={t('alertRules.form.metric')}
                  value={
                    <code className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">
                      {rule.metric}
                    </code>
                  }
                />
                <InfoRow
                  label={t('alertRules.form.condition')}
                  value={
                    <span className="font-mono text-sm">
                      {rule.metric} {rule.condition} {rule.threshold}
                    </span>
                  }
                />
                <InfoRow
                  label={t('alertRules.form.threshold')}
                  value={
                    <span className="tabular-nums">{rule.threshold}</span>
                  }
                />
                <InfoRow
                  label={tc('severity')}
                  value={<SeverityBadge severity={rule.severity} />}
                />
                <InfoRow
                  label={tc('status')}
                  value={
                    <span
                      className={cn(
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
                        rule.enabled
                          ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                          : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
                      )}
                    >
                      {rule.enabled ? tc('enabled') : tc('disabled')}
                    </span>
                  }
                />
                <InfoRow
                  label={t('alertRules.detail.notifyChannels')}
                  value={
                    rule.notifyChannels.length > 0 ? (
                      <div className="flex flex-wrap gap-1.5">
                        {rule.notifyChannels.map((ch) => (
                          <span
                            key={ch}
                            className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-muted"
                          >
                            {ch}
                          </span>
                        ))}
                      </div>
                    ) : (
                      t('alertRules.detail.noneConfigured')
                    )
                  }
                />
                <InfoRow
                  label={t('alertRules.detail.cooldown')}
                  value={`${rule.cooldownMinutes} minute${rule.cooldownMinutes !== 1 ? 's' : ''}`}
                />
                <InfoRow label={tc('created')} value={formatDate(rule.createdAt)} />
                <InfoRow label={tc('updated')} value={formatDate(rule.updatedAt)} />
              </dl>
            )}
          </div>

          {/* Recent Alert Events */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">
              {t('alertRules.detail.recentAlertEvents')}
              <span className="text-sm font-normal text-muted-foreground ml-2">
                ({alertEvents.length})
              </span>
            </h2>

            {alertEvents.length === 0 ? (
              <p className="text-sm text-muted-foreground py-8 text-center">
                {t('alertRules.detail.noAlertEvents')}
              </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('alertRules.detail.eventTable.severity')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('alertRules.detail.eventTable.metric')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('alertRules.detail.eventTable.value')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('alertRules.detail.eventTable.threshold')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('alertRules.detail.eventTable.message')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('alertRules.detail.eventTable.status')}</th>
                      <th className="text-right px-3 py-2 font-medium">{t('alertRules.detail.eventTable.triggered')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {alertEvents.map((event) => (
                      <tr
                        key={event.id}
                        className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <td className="px-3 py-2">
                          <SeverityBadge severity={event.severity} />
                        </td>
                        <td className="px-3 py-2">
                          <code className="font-mono text-xs">{event.metric}</code>
                        </td>
                        <td className="px-3 py-2 font-mono text-xs tabular-nums">
                          {event.value}
                        </td>
                        <td className="px-3 py-2 font-mono text-xs tabular-nums">
                          {event.threshold}
                        </td>
                        <td className="px-3 py-2 text-muted-foreground truncate max-w-[200px]">
                          {event.message || '--'}
                        </td>
                        <td className="px-3 py-2">
                          {event.resolvedAt ? (
                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                              {t('alertRules.detail.eventStatus.resolved')}
                            </span>
                          ) : (
                            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400">
                              {t('alertRules.detail.eventStatus.active')}
                            </span>
                          )}
                        </td>
                        <td className="px-3 py-2 text-right text-muted-foreground text-xs">
                          {formatRelative(event.triggeredAt)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Rule Summary */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('alertRules.detail.ruleSummary')}</h2>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('severity')}</span>
                <SeverityBadge severity={rule.severity} />
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('status')}</span>
                <span
                  className={cn(
                    'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
                    rule.enabled
                      ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                      : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
                  )}
                >
                  {rule.enabled ? tc('enabled') : tc('disabled')}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('alertRules.detail.cooldown')}</span>
                <span className="text-sm font-medium">{rule.cooldownMinutes}m</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('alertRules.detail.totalEvents')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {alertEvents.length}
                </span>
              </div>
            </div>

            {/* Rule expression display */}
            <div className="mt-4 p-3 bg-muted/50 rounded-md">
              <p className="text-xs text-muted-foreground mb-1">{t('alertRules.detail.ruleExpression')}</p>
              <p className="text-sm font-mono">
                {rule.metric} {rule.condition} {rule.threshold}
              </p>
            </div>
          </div>

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

          {/* Quick Actions card */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('alertRules.detail.quickActions')}</h2>
            <div className="space-y-3">
              {/* Toggle enabled */}
              <button
                onClick={() => handleToggleEnabled(!rule.enabled)}
                disabled={toggleMutation.isPending}
                className={cn(
                  'w-full px-4 py-2 text-sm rounded-md font-medium transition-colors disabled:opacity-50',
                  rule.enabled
                    ? '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',
                )}
              >
                {toggleMutation.isPending
                  ? t('alertRules.detail.updating')
                  : rule.enabled
                    ? t('alertRules.detail.disableRule')
                    : t('alertRules.detail.enableRule')}
              </button>

              {/* Edit */}
              <button
                onClick={startEditing}
                className="w-full px-4 py-2 text-sm rounded-md border border-input hover:bg-accent font-medium transition-colors"
              >
                {t('alertRules.detail.editRule')}
              </button>

              {/* Delete */}
              <button
                onClick={() => setShowDeleteDialog(true)}
                disabled={deleteMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 font-medium transition-colors disabled:opacity-50"
              >
                {t('alertRules.detail.deleteRule')}
              </button>
            </div>
          </div>

          {/* Metadata */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('alertRules.detail.metadata')}</h2>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('alertRules.detail.ruleId')}</span>
                <code className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
                  {rule.id}
                </code>
              </div>
              <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(rule.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(rule.updatedAt)}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={showDeleteDialog}
        name={rule.name}
        deleting={deleteMutation.isPending}
        onClose={() => setShowDeleteDialog(false)}
        onConfirm={() => deleteMutation.mutate()}
      />
    </div>
  );
}
