'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';
import { formatDistanceToNow } from 'date-fns';

/* ---------- Types ---------- */
type TriggerType = 'cron' | 'event' | 'threshold';

interface TriggerConfig {
  triggerType: TriggerType;
  cronExpression?: string;
  eventType?: string;
  metric?: string;
  threshold?: number;
}

interface StandingOrder {
  id: string;
  name: string;
  triggerConfig: TriggerConfig;
  targetServers: string[];
  agentInstruction: string;
  maxBudget: number;
  escalateOnFailure: boolean;
  status: 'active' | 'paused';
  lastExecutionAt: string | null;
  createdAt: string;
  updatedAt: string;
}

interface Execution {
  id: string;
  standingOrderId: string;
  status: 'success' | 'failure' | 'running' | 'cancelled';
  startedAt: string;
  completedAt: string | null;
  summary: string;
  cost: number;
}

interface StandingOrderFormData {
  name: string;
  triggerType: TriggerType;
  cronExpression: string;
  eventType: string;
  metric: string;
  threshold: string;
  targetServers: string;
  agentInstruction: string;
  maxBudget: string;
  escalateOnFailure: boolean;
}

const emptyForm: StandingOrderFormData = {
  name: '',
  triggerType: 'cron',
  cronExpression: '',
  eventType: '',
  metric: '',
  threshold: '',
  targetServers: '',
  agentInstruction: '',
  maxBudget: '',
  escalateOnFailure: false,
};

const EVENT_TYPE_OPTIONS = [
  'server.cpu_high',
  'server.disk_full',
  'server.unreachable',
  'deployment.failed',
  'alert.critical',
];

const STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-500/20 text-green-400',
  paused: 'bg-muted text-muted-foreground',
  success: 'bg-green-500/20 text-green-400',
  failure: 'bg-destructive/20 text-destructive-foreground',
  running: 'bg-primary/20 text-primary',
  cancelled: 'bg-muted text-muted-foreground',
};

/* ---------- Execution History Sub-component ---------- */
function ExecutionHistory({ orderId }: { orderId: string }) {
  const { t } = useTranslation('standing-orders');

  const { data: executions = [], isLoading, error } = useQuery<Execution[]>({
    queryKey: queryKeys.standingOrders.executions(orderId),
    queryFn: () =>
      apiClient<Execution[]>(`/api/v1/ops/standing-orders/${orderId}/executions`),
  });

  if (isLoading) {
    return (
      <div className="px-4 py-3 text-sm text-muted-foreground">{t('executionHistory.loading')}</div>
    );
  }
  if (error) {
    return (
      <div className="px-4 py-3 text-sm text-destructive-foreground">
        {t('executionHistory.loadError')} {(error as Error).message}
      </div>
    );
  }
  if (executions.length === 0) {
    return (
      <div className="px-4 py-3 text-sm text-muted-foreground">{t('executionHistory.empty')}</div>
    );
  }

  return (
    <div className="px-4 py-3">
      <h4 className="text-xs font-semibold uppercase text-muted-foreground mb-2">
        {t('executionHistory.title')}
      </h4>
      <table className="w-full text-xs">
        <thead>
          <tr className="border-b">
            <th className="text-left py-1.5 pr-4 font-medium">{t('executionHistory.table.status')}</th>
            <th className="text-left py-1.5 pr-4 font-medium">{t('executionHistory.started')}</th>
            <th className="text-left py-1.5 pr-4 font-medium">{t('executionHistory.ended')}</th>
            <th className="text-left py-1.5 pr-4 font-medium">{t('executionHistory.table.summary')}</th>
            <th className="text-right py-1.5 font-medium">{t('executionHistory.table.cost')}</th>
          </tr>
        </thead>
        <tbody>
          {executions.map((exec) => (
            <tr key={exec.id} className="border-b last:border-0">
              <td className="py-1.5 pr-4">
                <span
                  className={cn(
                    'inline-block px-1.5 py-0.5 rounded text-xs font-medium',
                    STATUS_COLORS[exec.status] ?? 'bg-muted text-muted-foreground',
                  )}
                >
                  {exec.status}
                </span>
              </td>
              <td className="py-1.5 pr-4 text-muted-foreground">
                {formatDistanceToNow(new Date(exec.startedAt), { addSuffix: true })}
              </td>
              <td className="py-1.5 pr-4 text-muted-foreground">
                {exec.completedAt
                  ? formatDistanceToNow(new Date(exec.completedAt), { addSuffix: true })
                  : '--'}
              </td>
              <td className="py-1.5 pr-4 max-w-xs truncate">{exec.summary}</td>
              <td className="py-1.5 text-right">${exec.cost.toFixed(2)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Main Component ---------- */
export default function StandingOrdersPage() {
  const { t } = useTranslation('standing-orders');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const TRIGGER_TYPE_OPTIONS: { value: TriggerType; label: string }[] = [
    { value: 'cron', label: t('triggerTypes.cron') },
    { value: 'event', label: t('triggerTypes.event') },
    { value: 'threshold', label: t('triggerTypes.threshold') },
  ];

  /* Dialog state */
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<StandingOrderFormData>(emptyForm);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  /* ---------- Queries ---------- */
  const {
    data: orders = [],
    isLoading,
    error,
  } = useQuery<StandingOrder[]>({
    queryKey: queryKeys.standingOrders.list(),
    queryFn: () => apiClient<StandingOrder[]>('/api/v1/ops/standing-orders'),
  });

  /* ---------- Mutations ---------- */
  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      apiClient<StandingOrder>('/api/v1/ops/standing-orders', { method: 'POST', body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.standingOrders.all });
      closeDialog();
    },
  });

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

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

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

  /* ---------- Helpers ---------- */
  function closeDialog() {
    setDialogOpen(false);
    setEditingId(null);
    setForm(emptyForm);
  }

  function openCreate() {
    setForm(emptyForm);
    setEditingId(null);
    setDialogOpen(true);
  }

  function openEdit(order: StandingOrder) {
    setForm({
      name: order.name,
      triggerType: order.triggerConfig.triggerType,
      cronExpression: order.triggerConfig.cronExpression ?? '',
      eventType: order.triggerConfig.eventType ?? '',
      metric: order.triggerConfig.metric ?? '',
      threshold: order.triggerConfig.threshold?.toString() ?? '',
      targetServers: order.targetServers.join(', '),
      agentInstruction: order.agentInstruction,
      maxBudget: order.maxBudget.toString(),
      escalateOnFailure: order.escalateOnFailure,
    });
    setEditingId(order.id);
    setDialogOpen(true);
  }

  function buildTriggerConfig(): TriggerConfig {
    const config: TriggerConfig = { triggerType: form.triggerType };
    if (form.triggerType === 'cron') {
      config.cronExpression = form.cronExpression;
    } else if (form.triggerType === 'event') {
      config.eventType = form.eventType;
    } else if (form.triggerType === 'threshold') {
      config.metric = form.metric;
      config.threshold = parseFloat(form.threshold) || 0;
    }
    return config;
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const payload = {
      name: form.name,
      triggerConfig: buildTriggerConfig(),
      targetServers: form.targetServers
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
      agentInstruction: form.agentInstruction,
      maxBudget: parseFloat(form.maxBudget) || 0,
      escalateOnFailure: form.escalateOnFailure,
    };

    if (editingId) {
      updateMutation.mutate({ id: editingId, ...payload });
    } else {
      createMutation.mutate(payload);
    }
  }

  function triggerLabel(config: TriggerConfig): string {
    switch (config.triggerType) {
      case 'cron':
        return `Cron: ${config.cronExpression || '(not set)'}`;
      case 'event':
        return `Event: ${config.eventType || '(not set)'}`;
      case 'threshold':
        return `${config.metric || 'metric'} >= ${config.threshold ?? '?'}`;
      default:
        return config.triggerType;
    }
  }

  const isSaving = createMutation.isPending || updateMutation.isPending;

  /* ---------- Render ---------- */
  return (
    <div>
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">{t('title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('subtitle')}
          </p>
        </div>
        <button
          onClick={openCreate}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90 transition-colors"
        >
          {t('newOrder')}
        </button>
      </div>

      {/* Loading / Error */}
      {isLoading && (
        <div className="text-muted-foreground text-sm py-12 text-center">
          {t('loading')}
        </div>
      )}
      {error && (
        <div className="text-destructive text-sm py-4">
          {t('loadError')} {(error as Error).message}
        </div>
      )}

      {/* Table */}
      {!isLoading && !error && (
        <div className="border rounded-lg overflow-hidden">
          <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('table.name')}</th>
                <th className="text-left px-4 py-3 font-medium">{t('table.trigger')}</th>
                <th className="text-center px-4 py-3 font-medium">{t('table.status')}</th>
                <th className="text-left px-4 py-3 font-medium">{t('table.lastExecution')}</th>
                <th className="text-right px-4 py-3 font-medium">{t('table.actions')}</th>
              </tr>
            </thead>
            {orders.length === 0 ? (
              <tbody>
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center text-muted-foreground">
                    {t('empty')}
                  </td>
                </tr>
              </tbody>
            ) : (
              orders.map((order) => (
                <tbody key={order.id}>
                  <tr
                      className={cn(
                        'border-b hover:bg-muted/30 transition-colors cursor-pointer',
                        expandedId === order.id && 'bg-muted/20',
                      )}
                      onClick={() =>
                        setExpandedId(expandedId === order.id ? null : order.id)
                      }
                    >
                      {/* Expand chevron */}
                      <td className="px-4 py-3 text-muted-foreground">
                        <span
                          className={cn(
                            'inline-block transition-transform text-xs',
                            expandedId === order.id && 'rotate-90',
                          )}
                        >
                          &#9654;
                        </span>
                      </td>

                      <td className="px-4 py-3 font-medium">{order.name}</td>

                      <td className="px-4 py-3 text-muted-foreground text-xs">
                        <span
                          className={cn(
                            'inline-block px-2 py-0.5 rounded font-medium',
                            order.triggerConfig.triggerType === 'cron' &&
                              'bg-primary/20 text-primary',
                            order.triggerConfig.triggerType === 'event' &&
                              'bg-destructive/20 text-destructive-foreground',
                            order.triggerConfig.triggerType === 'threshold' &&
                              'bg-secondary text-secondary-foreground',
                          )}
                        >
                          {triggerLabel(order.triggerConfig)}
                        </span>
                      </td>

                      {/* Status toggle */}
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            toggleStatusMutation.mutate({
                              id: order.id,
                              status: order.status === 'active' ? 'paused' : 'active',
                            });
                          }}
                          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>
                        <span className="block text-[10px] mt-0.5 text-muted-foreground">
                          {order.status}
                        </span>
                      </td>

                      <td className="px-4 py-3 text-muted-foreground text-xs">
                        {order.lastExecutionAt
                          ? formatDistanceToNow(new Date(order.lastExecutionAt), {
                              addSuffix: true,
                            })
                          : tc('never')}
                      </td>

                      <td className="px-4 py-3 text-right space-x-2">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            openEdit(order);
                          }}
                          className="text-xs text-primary hover:underline"
                        >
                          {tc('edit')}
                        </button>
                        {deleteConfirmId === order.id ? (
                          <>
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                deleteMutation.mutate(order.id);
                              }}
                              className="text-xs text-destructive-foreground bg-destructive px-2 py-0.5 rounded hover:bg-destructive/80"
                              disabled={deleteMutation.isPending}
                            >
                              {tc('confirm')}
                            </button>
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                setDeleteConfirmId(null);
                              }}
                              className="text-xs text-muted-foreground hover:underline"
                            >
                              {tc('cancel')}
                            </button>
                          </>
                        ) : (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setDeleteConfirmId(order.id);
                            }}
                            className="text-xs text-destructive-foreground hover:underline"
                          >
                            {tc('delete')}
                          </button>
                        )}
                      </td>
                    </tr>

                    {/* Expanded execution history */}
                    {expandedId === order.id && (
                      <tr>
                        <td colSpan={6} className="bg-muted/10 border-b">
                          <ExecutionHistory orderId={order.id} />
                        </td>
                      </tr>
                    )}
                </tbody>
              ))
            )}
          </table>
        </div>
      )}

      {/* Dialog Overlay */}
      {dialogOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* Backdrop */}
          <div className="absolute inset-0 bg-black/60" onClick={closeDialog} />

          {/* Panel */}
          <div className="relative z-10 w-full max-w-2xl max-h-[90vh] overflow-y-auto bg-card border rounded-lg shadow-xl mx-4">
            <div className="flex items-center justify-between px-6 pt-6 pb-2">
              <h2 className="text-lg font-semibold">
                {editingId ? t('detail.editStandingOrder') : t('newOrder')}
              </h2>
              <button
                onClick={closeDialog}
                className="text-muted-foreground hover:text-foreground text-xl leading-none"
              >
                &times;
              </button>
            </div>

            <form onSubmit={handleSubmit} className="px-6 pb-6 space-y-4">
              {/* Name */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.name')}</label>
                <input
                  type="text"
                  required
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  placeholder="e.g. Nightly Log Rotation"
                />
              </div>

              {/* Trigger Config Section */}
              <fieldset className="border rounded-md p-4 space-y-3">
                <legend className="text-sm font-medium px-1">{t('form.triggerConfiguration')}</legend>

                {/* Trigger Type */}
                <div>
                  <label className="block text-xs font-medium mb-1 text-muted-foreground">
                    {t('form.triggerType')}
                  </label>
                  <select
                    value={form.triggerType}
                    onChange={(e) =>
                      setForm({ ...form, triggerType: e.target.value as TriggerType })
                    }
                    className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  >
                    {TRIGGER_TYPE_OPTIONS.map((opt) => (
                      <option key={opt.value} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Cron Expression */}
                {form.triggerType === 'cron' && (
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground">
                      {t('form.cronExpression')}
                    </label>
                    <input
                      type="text"
                      required
                      value={form.cronExpression}
                      onChange={(e) => setForm({ ...form, cronExpression: e.target.value })}
                      className="w-full px-3 py-2 rounded-md bg-background border text-sm font-mono focus:outline-none focus:ring-2 focus:ring-ring"
                      placeholder="0 2 * * *"
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      Standard cron syntax (minute hour day month weekday).
                    </p>
                  </div>
                )}

                {/* Event Type */}
                {form.triggerType === 'event' && (
                  <div>
                    <label className="block text-xs font-medium mb-1 text-muted-foreground">
                      {t('form.eventType')}
                    </label>
                    <select
                      value={form.eventType}
                      onChange={(e) => setForm({ ...form, eventType: e.target.value })}
                      className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                    >
                      <option value="">Select an event type...</option>
                      {EVENT_TYPE_OPTIONS.map((evt) => (
                        <option key={evt} value={evt}>
                          {evt}
                        </option>
                      ))}
                    </select>
                  </div>
                )}

                {/* Threshold */}
                {form.triggerType === 'threshold' && (
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-medium mb-1 text-muted-foreground">
                        {t('form.metric')}
                      </label>
                      <input
                        type="text"
                        required
                        value={form.metric}
                        onChange={(e) => setForm({ ...form, metric: e.target.value })}
                        className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                        placeholder="e.g. cpu_percent"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-medium mb-1 text-muted-foreground">
                        {t('form.thresholdValue')}
                      </label>
                      <input
                        type="number"
                        required
                        step="any"
                        value={form.threshold}
                        onChange={(e) => setForm({ ...form, threshold: e.target.value })}
                        className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                        placeholder="90"
                      />
                    </div>
                  </div>
                )}
              </fieldset>

              {/* 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({ ...form, targetServers: e.target.value })}
                  className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  placeholder={t('form.targetServersPlaceholder')}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Comma-separated server IDs this order applies to.
                </p>
              </div>

              {/* Agent Instruction */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.agentInstruction')}</label>
                <textarea
                  value={form.agentInstruction}
                  onChange={(e) => setForm({ ...form, agentInstruction: e.target.value })}
                  rows={5}
                  className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-y"
                  placeholder="Describe what the agent should do when this order triggers..."
                />
              </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.maxBudget}
                  onChange={(e) => setForm({ ...form, maxBudget: e.target.value })}
                  className="w-full px-3 py-2 rounded-md bg-background border text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  placeholder="10.00"
                />
              </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({ ...form, escalateOnFailure: e.target.checked })
                    }
                    className="accent-primary h-4 w-4"
                  />
                  {t('form.escalateOnFailure')}
                </label>
                <p className="text-xs text-muted-foreground mt-1 ml-6">
                  Notify administrators when an execution fails.
                </p>
              </div>

              {/* Error */}
              {(createMutation.error || updateMutation.error) && (
                <p className="text-sm text-destructive-foreground">
                  {((createMutation.error || updateMutation.error) as Error).message}
                </p>
              )}

              {/* Actions */}
              <div className="flex justify-end gap-3 pt-2">
                <button
                  type="button"
                  onClick={closeDialog}
                  className="px-4 py-2 rounded-md border text-sm hover:bg-muted transition-colors"
                >
                  {tc('cancel')}
                </button>
                <button
                  type="submit"
                  disabled={isSaving}
                  className="px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
                >
                  {isSaving
                    ? tc('saving')
                    : editingId
                      ? t('detail.editStandingOrder')
                      : t('newOrder')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
