'use client';

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

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

type Severity = 'critical' | 'warning' | 'info';
type Condition = 'gt' | 'lt' | 'gte' | 'lte' | 'eq';
type Metric = 'cpu_usage' | 'memory_usage' | 'disk_usage' | 'network_latency' | 'http_error_rate' | 'custom';

interface AlertRule {
  id: string;
  name: string;
  description: string;
  metric: Metric;
  condition: Condition;
  threshold: number;
  duration: string;
  severity: Severity;
  enabled: boolean;
  targetServers: string[];
}

interface AlertRuleFormData {
  name: string;
  description: string;
  metric: Metric;
  condition: Condition;
  threshold: string;
  duration: string;
  severity: Severity;
  enabled: boolean;
  targetServers: string;
}

type AlertRulesResponse = AlertRule[];

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

const METRICS: { labelKey: string; value: Metric }[] = [
  { labelKey: 'alertRules.metrics.cpuUsage', value: 'cpu_usage' },
  { labelKey: 'alertRules.metrics.memoryUsage', value: 'memory_usage' },
  { labelKey: 'alertRules.metrics.diskUsage', value: 'disk_usage' },
  { labelKey: 'alertRules.metrics.networkLatency', value: 'network_latency' },
  { labelKey: 'alertRules.metrics.httpErrorRate', value: 'http_error_rate' },
  { labelKey: 'alertRules.metrics.custom', value: 'custom' },
];

const CONDITIONS: { labelKey: string; value: Condition }[] = [
  { labelKey: 'alertRules.conditions.greaterThan', value: 'gt' },
  { labelKey: 'alertRules.conditions.lessThan', value: 'lt' },
  { labelKey: 'alertRules.conditions.greaterOrEqual', value: 'gte' },
  { labelKey: 'alertRules.conditions.lessOrEqual', value: 'lte' },
  { labelKey: 'alertRules.conditions.equal', value: 'eq' },
];

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

const DURATIONS: { label: string; value: string }[] = [
  { label: '1 minute', value: '1m' },
  { label: '5 minutes', value: '5m' },
  { label: '10 minutes', value: '10m' },
  { label: '15 minutes', value: '15m' },
  { label: '30 minutes', value: '30m' },
  { label: '1 hour', value: '1h' },
];

const CONDITION_SYMBOLS: Record<Condition, string> = {
  gt: '>',
  lt: '<',
  gte: '>=',
  lte: '<=',
  eq: '=',
};

const METRIC_LABEL_KEYS: Record<Metric, string> = {
  cpu_usage: 'alertRules.metrics.cpuUsage',
  memory_usage: 'alertRules.metrics.memoryUsage',
  disk_usage: 'alertRules.metrics.diskUsage',
  network_latency: 'alertRules.metrics.networkLatency',
  http_error_rate: 'alertRules.metrics.httpErrorRate',
  custom: 'alertRules.metrics.custom',
};

const EMPTY_FORM: AlertRuleFormData = {
  name: '',
  description: '',
  metric: 'cpu_usage',
  condition: 'gt',
  threshold: '',
  duration: '5m',
  severity: 'warning',
  enabled: true,
  targetServers: '',
};

// ---------------------------------------------------------------------------
// Severity badge
// ---------------------------------------------------------------------------

function SeverityBadge({ severity }: { severity: Severity }) {
  const styles: Record<Severity, string> = {
    critical: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    warning: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    info: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  };

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

// ---------------------------------------------------------------------------
// Enabled toggle
// ---------------------------------------------------------------------------

function EnabledToggle({
  enabled,
  toggling,
  onToggle,
}: {
  enabled: boolean;
  toggling: boolean;
  onToggle: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onToggle}
      disabled={toggling}
      className={cn(
        'relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-50',
        enabled ? 'bg-primary' : 'bg-muted-foreground/30',
      )}
      role="switch"
      aria-checked={enabled}
    >
      <span
        className={cn(
          'pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
          enabled ? 'translate-x-4' : 'translate-x-0',
        )}
      />
    </button>
  );
}

// ---------------------------------------------------------------------------
// Alert rule form dialog
// ---------------------------------------------------------------------------

function AlertRuleDialog({
  open,
  title,
  form,
  errors,
  saving,
  onClose,
  onChange,
  onSubmit,
}: {
  open: boolean;
  title: string;
  form: AlertRuleFormData;
  errors: Partial<Record<keyof AlertRuleFormData, string>>;
  saving: boolean;
  onClose: () => void;
  onChange: (field: keyof AlertRuleFormData, value: string | number | boolean) => void;
  onSubmit: () => 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">
      {/* backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      {/* dialog */}
      <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">{title}</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('alertRules.form.name')} <span className="text-destructive">*</span>
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => onChange('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 Alert"
            />
            {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) => onChange('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')}</label>
            <select
              value={form.metric}
              onChange={(e) => onChange('metric', e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
            >
              {METRICS.map((m) => (
                <option key={m.value} value={m.value}>
                  {t(m.labelKey)}
                </option>
              ))}
            </select>
          </div>

          {/* condition and threshold row */}
          <div className="grid grid-cols-2 gap-4">
            {/* condition */}
            <div>
              <label className="block text-sm font-medium mb-1">{t('alertRules.form.condition')}</label>
              <select
                value={form.condition}
                onChange={(e) => onChange('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>

            {/* threshold */}
            <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) => onChange('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>

          {/* duration and severity row */}
          <div className="grid grid-cols-2 gap-4">
            {/* duration */}
            <div>
              <label className="block text-sm font-medium mb-1">Duration</label>
              <select
                value={form.duration}
                onChange={(e) => onChange('duration', e.target.value)}
                className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
              >
                {DURATIONS.map((d) => (
                  <option key={d.value} value={d.value}>
                    {d.label}
                  </option>
                ))}
              </select>
            </div>

            {/* severity */}
            <div>
              <label className="block text-sm font-medium mb-1">{t('alertRules.form.severity')}</label>
              <select
                value={form.severity}
                onChange={(e) => onChange('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>
          </div>

          {/* target servers */}
          <div>
            <label className="block text-sm font-medium mb-1">Target Servers</label>
            <input
              type="text"
              value={form.targetServers}
              onChange={(e) => onChange('targetServers', e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
              placeholder="web-01, web-02, db-01 (comma-separated)"
            />
            <p className="text-xs text-muted-foreground mt-1">
              Leave empty to apply to all servers.
            </p>
          </div>

          {/* enabled toggle */}
          <div className="flex items-center justify-between">
            <label className="text-sm font-medium">{t('alertRules.form.enabled')}</label>
            <button
              type="button"
              onClick={() => onChange('enabled', !form.enabled)}
              className={cn(
                'relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none',
                form.enabled ? 'bg-primary' : 'bg-muted-foreground/30',
              )}
              role="switch"
              aria-checked={form.enabled}
            >
              <span
                className={cn(
                  'pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
                  form.enabled ? 'translate-x-4' : 'translate-x-0',
                )}
              />
            </button>
          </div>
        </div>

        {/* actions */}
        <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}
            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>
  );
}

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

function DeleteDialog({
  open,
  ruleName,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  ruleName: 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>{ruleName}</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>
  );
}

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

export default function AlertRulesPage() {
  const { t } = useTranslation('monitoring');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  // State ----------------------------------------------------------------
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingRule, setEditingRule] = useState<AlertRule | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<AlertRule | null>(null);
  const [form, setForm] = useState<AlertRuleFormData>({ ...EMPTY_FORM });
  const [errors, setErrors] = useState<Partial<Record<keyof AlertRuleFormData, string>>>({});

  // Queries --------------------------------------------------------------
  const { data, isLoading, error } = useQuery({
    queryKey: queryKeys.alerts.rules(),
    queryFn: () => apiClient<AlertRulesResponse>('/api/v1/monitor/alerts/rules'),
  });

  const rules = Array.isArray(data) ? data : [];

  // Mutations ------------------------------------------------------------
  const createMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<AlertRule>('/api/v1/monitor/alerts/rules', { method: 'POST', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.alerts.rules() });
      closeDialog();
    },
  });

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

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

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

  // Helpers --------------------------------------------------------------
  const validate = useCallback((): boolean => {
    const next: Partial<Record<keyof AlertRuleFormData, string>> = {};
    if (!form.name.trim()) next.name = 'Name is required';
    if (!form.threshold.trim()) {
      next.threshold = 'Threshold is required';
    } else if (isNaN(Number(form.threshold))) {
      next.threshold = 'Threshold must be a number';
    }
    setErrors(next);
    return Object.keys(next).length === 0;
  }, [form]);

  const closeDialog = useCallback(() => {
    setDialogOpen(false);
    setEditingRule(null);
    setForm({ ...EMPTY_FORM });
    setErrors({});
  }, []);

  const openAdd = useCallback(() => {
    setEditingRule(null);
    setForm({ ...EMPTY_FORM });
    setErrors({});
    setDialogOpen(true);
  }, []);

  const openEdit = useCallback((rule: AlertRule) => {
    setEditingRule(rule);
    setForm({
      name: rule.name,
      description: rule.description ?? '',
      metric: rule.metric,
      condition: rule.condition,
      threshold: String(rule.threshold),
      duration: rule.duration,
      severity: rule.severity,
      enabled: rule.enabled,
      targetServers: (rule.targetServers ?? []).join(', '),
    });
    setErrors({});
    setDialogOpen(true);
  }, []);

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

  const handleSubmit = useCallback(() => {
    if (!validate()) return;
    const body: Record<string, unknown> = {
      name: form.name.trim(),
      description: form.description.trim(),
      metric: form.metric,
      condition: form.condition,
      threshold: Number(form.threshold),
      duration: form.duration,
      severity: form.severity,
      enabled: form.enabled,
      targetServers: form.targetServers
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
    };

    if (editingRule) {
      updateMutation.mutate({ id: editingRule.id, body });
    } else {
      createMutation.mutate(body);
    }
  }, [form, editingRule, validate, createMutation, updateMutation]);

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

  // Render ---------------------------------------------------------------
  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold">{t('alertRules.title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('alertRules.subtitle')}
          </p>
        </div>
        <button
          onClick={openAdd}
          className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 whitespace-nowrap"
        >
          {t('alertRules.addRule')}
        </button>
      </div>

      {/* Error state */}
      {error && (
        <div className="p-4 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('alertRules.loadError')} {(error as Error).message}
        </div>
      )}

      {/* Loading state */}
      {isLoading && (
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('alertRules.loading')}
        </div>
      )}

      {/* Data table */}
      {!isLoading && !error && (
        <div className="border rounded-lg overflow-hidden">
          <div className="overflow-x-auto">
            <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('alertRules.table.name')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('alertRules.table.metric')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('alertRules.table.condition')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('alertRules.table.threshold')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('alertRules.table.severity')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('alertRules.table.enabled')}</th>
                  <th className="text-right px-4 py-3 font-medium">{t('alertRules.table.actions')}</th>
                </tr>
              </thead>
              <tbody>
                {rules.length === 0 ? (
                  <tr>
                    <td
                      colSpan={7}
                      className="text-center text-muted-foreground py-12"
                    >
                      {t('alertRules.empty')}
                    </td>
                  </tr>
                ) : (
                  rules.map((rule) => (
                    <tr
                      key={rule.id}
                      className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                    >
                      <td className="px-4 py-3">
                        <div className="font-medium">{rule.name}</div>
                        {rule.description && (
                          <div className="text-xs text-muted-foreground mt-0.5 truncate max-w-[200px]">
                            {rule.description}
                          </div>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-muted">
                          {t(METRIC_LABEL_KEYS[rule.metric]) ?? rule.metric}
                        </span>
                      </td>
                      <td className="px-4 py-3 font-mono text-xs">
                        {CONDITION_SYMBOLS[rule.condition] ?? rule.condition}
                      </td>
                      <td className="px-4 py-3 font-mono text-xs">
                        {rule.threshold}
                        {rule.duration && (
                          <span className="text-muted-foreground ml-1">
                            for {rule.duration}
                          </span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <SeverityBadge severity={rule.severity} />
                      </td>
                      <td className="px-4 py-3">
                        <EnabledToggle
                          enabled={rule.enabled}
                          toggling={toggleMutation.isPending}
                          onToggle={() =>
                            toggleMutation.mutate({
                              id: rule.id,
                              enabled: !rule.enabled,
                            })
                          }
                        />
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => openEdit(rule)}
                            className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                          >
                            {tc('edit')}
                          </button>
                          <button
                            onClick={() => setDeleteTarget(rule)}
                            className="px-3 py-1 text-xs rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 transition-colors"
                          >
                            {tc('delete')}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Add / Edit dialog */}
      <AlertRuleDialog
        open={dialogOpen}
        title={editingRule ? t('alertRules.editRule') : t('alertRules.addRule')}
        form={form}
        errors={errors}
        saving={isSaving}
        onClose={closeDialog}
        onChange={handleChange}
        onSubmit={handleSubmit}
      />

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={!!deleteTarget}
        ruleName={deleteTarget?.name ?? ''}
        deleting={deleteMutation.isPending}
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
        }}
      />
    </div>
  );
}
