"use client";
import { useEffect, useState } from "react";

interface QueueSettings {
  batchSize?: number;
  concurrent?: number;
  maxRetries?: number;
  retryDelay?: number;
}

interface QueueSettingsEditorProps {
  value: string;
  onChange: (value: string) => void;
}

export default function QueueSettingsEditor({
  value,
  onChange
}: QueueSettingsEditorProps) {
  const [settings, setSettings] = useState<QueueSettings>({});
  const [isJsonMode, setIsJsonMode] = useState(false);

  useEffect(() => {
    try {
      const parsed = JSON.parse(value);
      setSettings(parsed);
    } catch {
      setSettings({});
    }
  }, [value]);

  const updateSettings = (newSettings: QueueSettings) => {
    setSettings(newSettings);
    onChange(JSON.stringify(newSettings, null, 2));
  };

  const updateField = (field: keyof QueueSettings, fieldValue: any) => {
    updateSettings({ ...settings, [field]: fieldValue });
  };

  const handleJsonChange = (jsonValue: string) => {
    onChange(jsonValue);
    try {
      const parsed = JSON.parse(jsonValue);
      setSettings(parsed);
    } catch {
      // Keep current settings if JSON is invalid
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h4 className="text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">
            Processing Queue Configuration
          </h4>
          <p className="text-xs text-gray-500 mb-4">
            Configure how files are processed in the queue system.
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-xs text-gray-500">JSON Mode</span>
          <button
            type="button"
            onClick={() => setIsJsonMode(!isJsonMode)}
            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
              isJsonMode ? "bg-indigo-600" : "bg-gray-200 dark:bg-gray-700"
            }`}
          >
            <span
              className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                isJsonMode ? "translate-x-6" : "translate-x-1"
              }`}
            />
          </button>
        </div>
      </div>

      {isJsonMode ? (
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Raw JSON Configuration
          </label>
          <textarea
            value={value}
            onChange={(e) => handleJsonChange(e.target.value)}
            rows={8}
            className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 font-mono"
            placeholder='{"batchSize": 10, "concurrent": 3, ...}'
          />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                Batch Size
              </label>
              <input
                type="number"
                value={settings.batchSize || 1}
                onChange={(e) =>
                  updateField("batchSize", parseInt(e.target.value))
                }
                min="1"
                max="100"
                className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              />
              <p className="mt-1 text-xs text-gray-500">
                Number of files to process together
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                Concurrent Jobs
              </label>
              <input
                type="number"
                value={settings.concurrent || 1}
                onChange={(e) =>
                  updateField("concurrent", parseInt(e.target.value))
                }
                min="1"
                max="10"
                className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              />
              <p className="mt-1 text-xs text-gray-500">
                Maximum number of simultaneous processing jobs
              </p>
            </div>
          </div>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                Max Retries
              </label>
              <input
                type="number"
                value={settings.maxRetries || 3}
                onChange={(e) =>
                  updateField("maxRetries", parseInt(e.target.value))
                }
                min="0"
                max="10"
                className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              />
              <p className="mt-1 text-xs text-gray-500">
                Maximum number of retry attempts for failed jobs
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                Retry Delay (ms)
              </label>
              <input
                type="number"
                value={settings.retryDelay || 1000}
                onChange={(e) =>
                  updateField("retryDelay", parseInt(e.target.value))
                }
                min="100"
                max="30000"
                className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              />
              <p className="mt-1 text-xs text-gray-500">
                Delay between retry attempts
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
