import { useState, useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { DataTable, Badge, MonoText, useToast } from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useAllApplicationConfigs, useUpdateApplicationConfig } from '../../api/queries/commands';
import type { ApplicationConfig } from '../../api/queries/commands';
import styles from './AppConfigPage.module.css';

type ConfigRow = ApplicationConfig & { id: string };

function timeAgo(iso?: string): string {
  if (!iso) return '\u2014';
  const diff = Date.now() - new Date(iso).getTime();
  const secs = Math.floor(diff / 1000);
  if (secs < 60) return `${secs}s ago`;
  const mins = Math.floor(secs / 60);
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.floor(hours / 24)}d ago`;
}

type BadgeColor = 'primary' | 'success' | 'warning' | 'error' | 'running' | 'auto';

function logLevelColor(level?: string): BadgeColor {
  switch (level?.toUpperCase()) {
    case 'ERROR': return 'error';
    case 'WARN': return 'warning';
    case 'DEBUG': return 'running';
    default: return 'success';
  }
}

function engineLevelColor(level?: string): BadgeColor {
  switch (level?.toUpperCase()) {
    case 'NONE': return 'error';
    case 'MINIMAL': return 'warning';
    case 'COMPLETE': return 'running';
    default: return 'success';
  }
}

function payloadColor(mode?: string): BadgeColor {
  switch (mode?.toUpperCase()) {
    case 'INPUT': case 'OUTPUT': return 'warning';
    case 'BOTH': return 'running';
    default: return 'auto';
  }
}

export default function AppConfigPage() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { data: configs } = useAllApplicationConfigs();
  const updateConfig = useUpdateApplicationConfig();
  const [editingApp, setEditingApp] = useState<string | null>(null);
  const [draft, setDraft] = useState<Partial<ApplicationConfig>>({});

  const startEditing = useCallback((row: ConfigRow) => {
    setEditingApp(row.application);
    setDraft({
      logForwardingLevel: row.logForwardingLevel ?? 'INFO',
      engineLevel: row.engineLevel ?? 'REGULAR',
      payloadCaptureMode: row.payloadCaptureMode ?? 'NONE',
      metricsEnabled: row.metricsEnabled,
    });
  }, []);

  const cancelEditing = useCallback(() => {
    setEditingApp(null);
    setDraft({});
  }, []);

  const saveEditing = useCallback((row: ConfigRow) => {
    const updated = { ...row, ...draft };
    updateConfig.mutate(updated, {
      onSuccess: (saved) => {
        setEditingApp(null);
        setDraft({});
        toast({ title: 'Config updated', description: `${row.application} (v${saved.version})`, variant: 'success' });
      },
      onError: () => {
        toast({ title: 'Config update failed', description: row.application, variant: 'error' });
      },
    });
  }, [draft, updateConfig, toast]);

  const columns: Column<ConfigRow>[] = useMemo(() => [
    {
      key: '_inspect',
      header: '',
      width: '36px',
      render: (_val, row) => (
        <button
          className={styles.inspectLink}
          title="Open agent page"
          onClick={(e) => {
            e.stopPropagation();
            navigate(`/agents/${row.application}`);
          }}
        >
          &#x2197;
        </button>
      ),
    },
    {
      key: '_edit',
      header: '',
      width: '36px',
      render: (_val, row) => {
        const isEditing = editingApp === row.application;
        return isEditing ? (
          <span className={styles.editActions}>
            <button
              className={styles.editBtn}
              title="Save"
              onClick={(e) => { e.stopPropagation(); saveEditing(row); }}
              disabled={updateConfig.isPending}
            >
              &#x2713;
            </button>
            <button
              className={styles.editBtn}
              title="Cancel"
              onClick={(e) => { e.stopPropagation(); cancelEditing(); }}
            >
              &#x2715;
            </button>
          </span>
        ) : (
          <button
            className={styles.editBtn}
            title="Edit config"
            onClick={(e) => { e.stopPropagation(); startEditing(row); }}
          >
            &#x270E;
          </button>
        );
      },
    },
    {
      key: 'application',
      header: 'Application',
      sortable: true,
      render: (_val, row) => <MonoText size="sm">{row.application}</MonoText>,
    },
    {
      key: 'logForwardingLevel',
      header: 'Log Level',
      render: (_val, row) => {
        const val = row.logForwardingLevel ?? 'INFO';
        if (editingApp === row.application) {
          return (
            <select
              className={styles.inlineSelect}
              value={draft.logForwardingLevel ?? val}
              onChange={(e) => { e.stopPropagation(); setDraft(d => ({ ...d, logForwardingLevel: e.target.value })); }}
            >
              <option value="ERROR">ERROR</option>
              <option value="WARN">WARN</option>
              <option value="INFO">INFO</option>
              <option value="DEBUG">DEBUG</option>
            </select>
          );
        }
        return <Badge label={val} color={logLevelColor(val)} variant="filled" />;
      },
    },
    {
      key: 'engineLevel',
      header: 'Engine Level',
      render: (_val, row) => {
        const val = row.engineLevel ?? 'REGULAR';
        if (editingApp === row.application) {
          return (
            <select
              className={styles.inlineSelect}
              value={draft.engineLevel ?? val}
              onChange={(e) => { e.stopPropagation(); setDraft(d => ({ ...d, engineLevel: e.target.value })); }}
            >
              <option value="NONE">None</option>
              <option value="MINIMAL">Minimal</option>
              <option value="REGULAR">Regular</option>
              <option value="COMPLETE">Complete</option>
            </select>
          );
        }
        return <Badge label={val} color={engineLevelColor(val)} variant="filled" />;
      },
    },
    {
      key: 'payloadCaptureMode',
      header: 'Payload Capture',
      render: (_val, row) => {
        const val = row.payloadCaptureMode ?? 'NONE';
        if (editingApp === row.application) {
          return (
            <select
              className={styles.inlineSelect}
              value={draft.payloadCaptureMode ?? val}
              onChange={(e) => { e.stopPropagation(); setDraft(d => ({ ...d, payloadCaptureMode: e.target.value })); }}
            >
              <option value="NONE">None</option>
              <option value="INPUT">Input</option>
              <option value="OUTPUT">Output</option>
              <option value="BOTH">Both</option>
            </select>
          );
        }
        return <Badge label={val} color={payloadColor(val)} variant="filled" />;
      },
    },
    {
      key: 'metricsEnabled',
      header: 'Metrics',
      width: '80px',
      render: (_val, row) => {
        if (editingApp === row.application) {
          return (
            <label className={styles.inlineToggle} onClick={(e) => e.stopPropagation()}>
              <input
                type="checkbox"
                checked={draft.metricsEnabled ?? row.metricsEnabled}
                onChange={(e) => setDraft(d => ({ ...d, metricsEnabled: e.target.checked }))}
              />
              <span>{(draft.metricsEnabled ?? row.metricsEnabled) ? 'On' : 'Off'}</span>
            </label>
          );
        }
        return <Badge label={row.metricsEnabled ? 'On' : 'Off'} color={row.metricsEnabled ? 'success' : 'error'} variant="filled" />;
      },
    },
    {
      key: 'tracedProcessors',
      header: 'Traced',
      width: '70px',
      render: (_val, row) => {
        const count = row.tracedProcessors ? Object.keys(row.tracedProcessors).length : 0;
        return count > 0
          ? <Badge label={`${count}`} color="running" variant="filled" />
          : <MonoText size="xs">0</MonoText>;
      },
    },
    {
      key: 'version',
      header: 'v',
      width: '40px',
      render: (_val, row) => <MonoText size="xs">{row.version}</MonoText>,
    },
    {
      key: 'updatedAt',
      header: 'Updated',
      render: (_val, row) => <MonoText size="xs">{timeAgo(row.updatedAt)}</MonoText>,
    },
  ], [navigate, editingApp, draft, startEditing, cancelEditing, saveEditing, updateConfig.isPending]);

  return (
    <div>
      <DataTable<ConfigRow>
        columns={columns}
        data={(configs ?? []).map(c => ({ ...c, id: c.application }))}
        pageSize={50}
      />
    </div>
  );
}
