"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import DatasetCrud from "./DatasetCrud";
import { useNotifications } from "./NotificationContext";

interface DatasetConfig {
  [path: string]: any;
}

interface DatasetsSettings {
  [datasetName: string]: DatasetConfig;
}

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

export default function DatasetsSettingsEditor({
  value,
  onChange
}: DatasetsSettingsEditorProps) {
  const [settings, setSettings] = useState<DatasetsSettings>({});
  const [isDatasetFormOpen, setIsDatasetFormOpen] = useState(false);
  const [editingDataset, setEditingDataset] = useState<string | null>(null);
  const [isJsonMode, setIsJsonMode] = useState(false);
  const { addNotification } = useNotifications();

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

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

  const handleAddDataset = () => {
    setEditingDataset(null);
    setIsDatasetFormOpen(true);
  };

  const handleEditDataset = (datasetName: string) => {
    setEditingDataset(datasetName);
    setIsDatasetFormOpen(true);
  };

  const handleSaveDataset = (name: string, config: DatasetConfig) => {
    const newSettings = { ...settings };

    // If editing and name changed, remove old key
    if (editingDataset && editingDataset !== name) {
      delete newSettings[editingDataset];
    }

    newSettings[name] = config;
    updateSettings(newSettings);
    setIsDatasetFormOpen(false);
    setEditingDataset(null);
  };

  const handleCloseDatasetForm = () => {
    setIsDatasetFormOpen(false);
    setEditingDataset(null);
  };

  const removeDataset = (datasetName: string) => {
    const newSettings = { ...settings };
    delete newSettings[datasetName];
    updateSettings(newSettings);
  };

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

  const handleEnabledChange = useCallback(
    (datasetName: string, enabled: boolean) => {
      const newSettings = { ...settings };
      const dataset = newSettings[datasetName];
      newSettings[datasetName] = {
        ...dataset,
        enabled
      };
      updateSettings(newSettings);

      // Show toast notification
      toast.success(
        `Dataset "${datasetName}" ${enabled ? "enabled" : "disabled"} successfully`
      );
      addNotification({
        type: "success",
        title: "Dataset Updated",
        message: `Dataset "${datasetName}" has been ${enabled ? "enabled" : "disabled"} successfully.`
      });
    },
    [settings, addNotification]
  );

  const datasetConfig = useMemo(() => {
    return editingDataset ? settings[editingDataset] || {} : {};
  }, [editingDataset, settings]);

  const onEnabledChange = useMemo(() => {
    return editingDataset
      ? (enabled: boolean) => handleEnabledChange(editingDataset, enabled)
      : undefined;
  }, [editingDataset, handleEnabledChange]);

  const toggleDatasetEnabled = (datasetName: string) => {
    const dataset = settings[datasetName];
    const currentEnabled =
      dataset?.enabled !== undefined ? dataset.enabled : true;
    handleEnabledChange(datasetName, !currentEnabled);
  };

  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">
            Datasets Configuration
          </h4>
          <p className="text-xs text-gray-500 mb-4">
            Configure dataset paths and their settings. Each dataset can have
            multiple watch paths with individual configurations.
          </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={15}
            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='{"dataset1": {"path": "/path", "enabled": true, ...}, ...}'
          />
        </div>
      ) : (
        <div>
          {/* Add Dataset Button */}
          <div className="flex justify-end">
            <button
              type="button"
              onClick={handleAddDataset}
              className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
            >
              <svg
                className="h-4 w-4 mr-2"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 4v16m8-8H4"
                />
              </svg>
              Add Dataset
            </button>
          </div>

          {/* Existing datasets */}
          {Object.entries(settings).length > 0 ? (
            <div className="space-y-4">
              {Object.entries(settings).map(([datasetName, paths]) => (
                <div
                  key={datasetName}
                  className={`border rounded-lg p-4 ${
                    paths.enabled === false
                      ? "bg-gray-100 dark:bg-gray-800 border-gray-300 dark:border-gray-600"
                      : "bg-gray-50 dark:bg-gray-800"
                  }`}
                >
                  <div className="flex items-center justify-between mb-3">
                    <div>
                      <div className="flex items-center gap-2">
                        <h5 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                          {datasetName}
                        </h5>
                        <span
                          className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                            paths.enabled === false
                              ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
                              : "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
                          }`}
                        >
                          {paths.enabled === false ? "Disabled" : "Enabled"}
                        </span>
                      </div>
                      <p className="text-xs text-gray-500">
                        {
                          Object.keys(paths).filter((key) => key !== "enabled")
                            .length
                        }{" "}
                        path
                        {Object.keys(paths).filter((key) => key !== "enabled")
                          .length !== 1
                          ? "s"
                          : ""}{" "}
                        configured
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => toggleDatasetEnabled(datasetName)}
                        className={`inline-flex items-center rounded-md px-3 py-1 text-xs font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 ${
                          paths.enabled === false
                            ? "bg-gray-600 hover:bg-gray-700 focus:ring-gray-500"
                            : "bg-green-600 hover:bg-green-700 focus:ring-green-500"
                        }`}
                      >
                        {paths.enabled === false ? "Disabled" : "Enabled"}
                      </button>
                      <button
                        type="button"
                        onClick={() => handleEditDataset(datasetName)}
                        className="inline-flex items-center rounded-md bg-blue-600 px-3 py-1 text-xs font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        onClick={() => removeDataset(datasetName)}
                        className="inline-flex items-center rounded-md bg-red-600 px-3 py-1 text-xs font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                      >
                        Remove
                      </button>
                    </div>
                  </div>

                  {/* Path summary */}
                  {Object.keys(paths).filter((key) => key !== "enabled")
                    .length > 0 && (
                    <div className="text-xs text-gray-600 dark:text-gray-400">
                      <div className="flex flex-wrap gap-1">
                        {Object.keys(paths)
                          .filter((key) => key !== "enabled")
                          .map((path) => (
                            <span
                              key={path}
                              className="inline-block bg-gray-200 dark:bg-gray-700 px-2 py-1 rounded font-mono"
                            >
                              {path}
                            </span>
                          ))}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <svg
                className="mx-auto h-12 w-12 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
                />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900 dark:text-gray-100">
                No datasets configured
              </h3>
              <p className="mt-1 text-sm text-gray-500">
                Get started by adding your first dataset.
              </p>
            </div>
          )}
        </div>
      )}

      {/* Dataset CRUD Form */}
      <DatasetCrud
        datasetName={editingDataset || ""}
        datasetConfig={datasetConfig}
        onSave={handleSaveDataset}
        onClose={handleCloseDatasetForm}
        onEnabledChange={onEnabledChange}
        isOpen={isDatasetFormOpen}
      />
    </div>
  );
}
