// SPDX-License-Identifier: GPL-3.0-or-later

import { useState } from 'react';
import { FolderOpen, Plus, X, AlertCircle, CheckCircle } from 'lucide-react';

interface PathSelectorProps {
  paths: Array<{ path: string; exists: boolean; access_error?: string }>;
  onAddPath: (path: string) => Promise<void>;
  onRemovePath: (path: string) => Promise<void>;
  disabled?: boolean;
}

export default function PathSelector({
  paths,
  onAddPath,
  onRemovePath,
  disabled = false,
}: PathSelectorProps) {
  const [newPath, setNewPath] = useState('');
  const [isAdding, setIsAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleAdd = async () => {
    if (!newPath.trim()) return;

    setIsAdding(true);
    setError(null);

    try {
      await onAddPath(newPath.trim());
      setNewPath('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to add path');
    } finally {
      setIsAdding(false);
    }
  };

  const handleRemove = async (path: string) => {
    try {
      await onRemovePath(path);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to remove path');
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isAdding && newPath.trim()) {
      handleAdd();
    }
  };

  return (
    <div className="space-y-4">
      {/* Error Message */}
      {error && (
        <div className="flex items-center text-sm text-red-600 dark:text-red-400">
          <AlertCircle className="w-4 h-4 mr-2" />
          {error}
          <button
            onClick={() => setError(null)}
            className="ml-auto text-red-400 hover:text-red-600"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Add Path Input */}
      <div className="flex items-center space-x-2">
        <div className="relative flex-1">
          <FolderOpen className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <input
            type="text"
            value={newPath}
            onChange={(e) => setNewPath(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="/path/to/backup"
            className="input pl-10"
            disabled={disabled || isAdding}
          />
        </div>
        <button
          onClick={handleAdd}
          disabled={disabled || isAdding || !newPath.trim()}
          className="btn-primary"
        >
          {isAdding ? (
            <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
          ) : (
            <Plus className="w-4 h-4" />
          )}
          <span className="ml-2">Add</span>
        </button>
      </div>

      {/* Path List */}
      {paths.length === 0 ? (
        <div className="text-center py-8 text-slate-500 dark:text-slate-400">
          <FolderOpen className="w-12 h-12 mx-auto mb-3 text-slate-300 dark:text-slate-600" />
          <p>No backup paths configured</p>
          <p className="text-sm mt-1">Add a directory to start backing up</p>
        </div>
      ) : (
        <ul className="divide-y divide-slate-200 dark:divide-slate-700">
          {paths.map((pathInfo) => (
            <li
              key={pathInfo.path}
              className="flex items-center justify-between py-3 group"
            >
              <div className="flex items-center space-x-3 min-w-0 flex-1">
                <FolderOpen
                  className={`w-5 h-5 flex-shrink-0 ${
                    pathInfo.exists
                      ? 'text-primary-600'
                      : 'text-slate-400'
                  }`}
                />
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium text-slate-900 dark:text-white truncate">
                    {pathInfo.path}
                  </p>
                  {pathInfo.access_error && (
                    <p className="text-xs text-red-500 truncate">
                      {pathInfo.access_error}
                    </p>
                  )}
                </div>
              </div>
              <div className="flex items-center space-x-3 ml-4">
                {pathInfo.exists ? (
                  <span className="flex items-center text-green-600 text-xs">
                    <CheckCircle className="w-3.5 h-3.5 mr-1" />
                    Ready
                  </span>
                ) : (
                  <span className="flex items-center text-red-500 text-xs">
                    <AlertCircle className="w-3.5 h-3.5 mr-1" />
                    Missing
                  </span>
                )}
                <button
                  onClick={() => handleRemove(pathInfo.path)}
                  disabled={disabled}
                  className="p-1 text-slate-400 hover:text-red-600 dark:hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
                  title="Remove path"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
