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

interface WatcherSettings {
  ignored?: string;
  ignoreInitial?: boolean;
  persistent?: boolean;
  usePolling?: boolean;
  interval?: number;
}

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

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

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

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

  const updateField = (field: keyof WatcherSettings, 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">
            File Watcher Configuration
          </h4>
          <p className="text-xs text-gray-500 mb-4">
            Configure how the file watcher monitors for changes.
          </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={12}
            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='{"ignored": "...", "ignoreInitial": false, ...}'
          />
        </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">
                Ignored Pattern (Regex)
              </label>
              <input
                type="text"
                value={settings.ignored || ""}
                onChange={(e) => updateField("ignored", e.target.value)}
                placeholder="e.g., \.tmp$|\.log$"
                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">
                Files matching this regex pattern will be ignored
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                Polling Interval (ms)
              </label>
              <input
                type="number"
                value={settings.interval || 100}
                onChange={(e) =>
                  updateField("interval", parseInt(e.target.value))
                }
                min="50"
                max="5000"
                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">
                How often to check for changes when using polling
              </p>
            </div>
          </div>

          <div className="space-y-4">
            <div className="space-y-3">
              <div className="flex items-center">
                <input
                  id="ignoreInitial"
                  type="checkbox"
                  checked={settings.ignoreInitial || false}
                  onChange={(e) =>
                    updateField("ignoreInitial", e.target.checked)
                  }
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label
                  htmlFor="ignoreInitial"
                  className="ml-2 block text-sm text-gray-700 dark:text-gray-200"
                >
                  Ignore Initial Files
                </label>
              </div>
              <p className="text-xs text-gray-500 ml-6">
                Don&apos;t trigger events for files that exist when watching
                starts
              </p>
            </div>

            <div className="space-y-3">
              <div className="flex items-center">
                <input
                  id="persistent"
                  type="checkbox"
                  checked={settings.persistent || true}
                  onChange={(e) => updateField("persistent", e.target.checked)}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label
                  htmlFor="persistent"
                  className="ml-2 block text-sm text-gray-700 dark:text-gray-200"
                >
                  Persistent Watching
                </label>
              </div>
              <p className="text-xs text-gray-500 ml-6">
                Keep the process running after initial scan
              </p>
            </div>

            <div className="space-y-3">
              <div className="flex items-center">
                <input
                  id="usePolling"
                  type="checkbox"
                  checked={settings.usePolling || false}
                  onChange={(e) => updateField("usePolling", e.target.checked)}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label
                  htmlFor="usePolling"
                  className="ml-2 block text-sm text-gray-700 dark:text-gray-200"
                >
                  Use Polling
                </label>
              </div>
              <p className="text-xs text-gray-500 ml-6">
                Use polling instead of native file watching (slower but more
                reliable)
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
