'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';

/* ---------- Types ---------- */
interface Runbook {
  id: string;
  name: string;
  description: string;
  triggerType: 'manual' | 'alert' | 'scheduled';
  promptTemplate: string;
  allowedTools: string[];
  maxRiskLevel: number;
  autoApprove: boolean;
  createdAt: string;
  updatedAt: string;
}

interface RunbookFormData {
  name: string;
  description: string;
  triggerType: 'manual' | 'alert' | 'scheduled';
  promptTemplate: string;
  allowedTools: string;
  maxRiskLevel: number;
  autoApprove: boolean;
}

const emptyForm: RunbookFormData = {
  name: '',
  description: '',
  triggerType: 'manual',
  promptTemplate: '',
  allowedTools: '',
  maxRiskLevel: 1,
  autoApprove: false,
};

/* ---------- Component ---------- */
export default function RunbooksPage() {
  const { t } = useTranslation('runbooks');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const TRIGGER_OPTIONS: { value: RunbookFormData['triggerType']; label: string }[] = [
    { value: 'manual', label: t('triggerTypes.manual') },
    { value: 'alert', label: t('triggerTypes.alert') },
    { value: 'scheduled', label: t('triggerTypes.scheduled') },
  ];

  const RISK_LEVELS = [
    { value: 0, label: t('riskLevels.0') },
    { value: 1, label: t('riskLevels.1') },
    { value: 2, label: t('riskLevels.2') },
    { value: 3, label: t('riskLevels.3') },
  ];

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

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

  /* ---------- Mutations ---------- */
  const createMutation = useMutation({
    mutationFn: (data: Omit<Runbook, 'id' | 'createdAt' | 'updatedAt'>) =>
      apiClient<Runbook>('/api/v1/ops/runbooks', { method: 'POST', body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
      closeDialog();
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, ...data }: { id: string } & Partial<Runbook>) =>
      apiClient<Runbook>(`/api/v1/ops/runbooks/${id}`, { method: 'PUT', body: data }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
      closeDialog();
    },
  });

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

  const toggleAutoApproveMutation = useMutation({
    mutationFn: ({ id, autoApprove }: { id: string; autoApprove: boolean }) =>
      apiClient<Runbook>(`/api/v1/ops/runbooks/${id}`, {
        method: 'PUT',
        body: { autoApprove },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
    },
  });

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

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

  function openEdit(rb: Runbook) {
    setForm({
      name: rb.name,
      description: rb.description,
      triggerType: rb.triggerType,
      promptTemplate: rb.promptTemplate,
      allowedTools: rb.allowedTools.join(', '),
      maxRiskLevel: rb.maxRiskLevel,
      autoApprove: rb.autoApprove,
    });
    setEditingId(rb.id);
    setDialogOpen(true);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const payload = {
      name: form.name,
      description: form.description,
      triggerType: form.triggerType,
      promptTemplate: form.promptTemplate,
      allowedTools: form.allowedTools
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
      maxRiskLevel: form.maxRiskLevel,
      autoApprove: form.autoApprove,
    };

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

  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('newRunbook')}
        </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="text-left px-4 py-3 font-medium">{t('table.name')}</th>
                <th className="text-left px-4 py-3 font-medium">{t('table.description')}</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.maxRisk')}</th>
                <th className="text-center px-4 py-3 font-medium">{t('table.autoApprove')}</th>
                <th className="text-right px-4 py-3 font-medium">{t('table.actions')}</th>
              </tr>
            </thead>
            <tbody>
              {runbooks.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center text-muted-foreground">
                    {t('empty')}
                  </td>
                </tr>
              ) : (
                runbooks.map((rb) => (
                  <tr key={rb.id} className="border-b last:border-0 hover:bg-muted/30 transition-colors">
                    <td className="px-4 py-3 font-medium">{rb.name}</td>
                    <td className="px-4 py-3 text-muted-foreground max-w-xs truncate">
                      {rb.description}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={cn(
                          'inline-block px-2 py-0.5 rounded text-xs font-medium',
                          rb.triggerType === 'manual' && 'bg-secondary text-secondary-foreground',
                          rb.triggerType === 'alert' && 'bg-destructive/20 text-destructive-foreground',
                          rb.triggerType === 'scheduled' && 'bg-primary/20 text-primary',
                        )}
                      >
                        {rb.triggerType}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">{rb.maxRiskLevel}</td>
                    <td className="px-4 py-3 text-center">
                      <button
                        onClick={() =>
                          toggleAutoApproveMutation.mutate({
                            id: rb.id,
                            autoApprove: !rb.autoApprove,
                          })
                        }
                        className={cn(
                          'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
                          rb.autoApprove ? 'bg-primary' : 'bg-muted',
                        )}
                        title={rb.autoApprove ? t('form.autoApprove') + ' ' + tc('enabled').toLowerCase() : t('form.autoApprove') + ' ' + tc('disabled').toLowerCase()}
                      >
                        <span
                          className={cn(
                            'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
                            rb.autoApprove ? 'translate-x-[18px]' : 'translate-x-[3px]',
                          )}
                        />
                      </button>
                    </td>
                    <td className="px-4 py-3 text-right space-x-2">
                      <button
                        onClick={() => openEdit(rb)}
                        className="text-xs text-primary hover:underline"
                      >
                        {tc('edit')}
                      </button>
                      {deleteConfirmId === rb.id ? (
                        <>
                          <button
                            onClick={() => deleteMutation.mutate(rb.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={() => setDeleteConfirmId(null)}
                            className="text-xs text-muted-foreground hover:underline"
                          >
                            {tc('cancel')}
                          </button>
                        </>
                      ) : (
                        <button
                          onClick={() => setDeleteConfirmId(rb.id)}
                          className="text-xs text-destructive-foreground hover:underline"
                        >
                          {tc('delete')}
                        </button>
                      )}
                    </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 ? tc('edit') : t('newRunbook')}
              </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. Disk Cleanup"
                />
              </div>

              {/* Description */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.description')}</label>
                <textarea
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  rows={2}
                  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="Brief description of what this runbook does"
                />
              </div>

              {/* Trigger Type */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.triggerType')}</label>
                <select
                  value={form.triggerType}
                  onChange={(e) =>
                    setForm({ ...form, triggerType: e.target.value as RunbookFormData['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_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* Prompt Template */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.promptTemplate')}</label>
                <textarea
                  value={form.promptTemplate}
                  onChange={(e) => setForm({ ...form, promptTemplate: e.target.value })}
                  rows={8}
                  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 resize-y"
                  placeholder="Enter the runbook template instructions..."
                />
              </div>

              {/* Allowed Tools */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.allowedTools')}</label>
                <input
                  type="text"
                  value={form.allowedTools}
                  onChange={(e) => setForm({ ...form, allowedTools: 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="ssh, kubectl, docker (comma-separated)"
                />
                <p className="text-xs text-muted-foreground mt-1">Comma-separated list of tools the agent may use.</p>
              </div>

              {/* Max Risk Level */}
              <div>
                <label className="block text-sm font-medium mb-1">{t('form.maxRiskLevel')}</label>
                <div className="flex gap-4">
                  {RISK_LEVELS.map((rl) => (
                    <label key={rl.value} className="flex items-center gap-1.5 text-sm cursor-pointer">
                      <input
                        type="radio"
                        name="maxRiskLevel"
                        checked={form.maxRiskLevel === rl.value}
                        onChange={() => setForm({ ...form, maxRiskLevel: rl.value })}
                        className="accent-primary"
                      />
                      {rl.label}
                    </label>
                  ))}
                </div>
              </div>

              {/* Auto-Approve */}
              <div>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.autoApprove}
                    onChange={(e) => setForm({ ...form, autoApprove: e.target.checked })}
                    className="accent-primary h-4 w-4"
                  />
                  {t('form.autoApprove')}
                </label>
              </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 ? tc('save') : tc('create')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
