import { Component, Show, createSignal, For } from 'solid-js';
import { Portal } from 'solid-js/web';
import { showSuccess, showError } from '@/utils/toast';
import { NodesAPI } from '@/api/nodes';
import type { NodeConfig } from '@/types/nodes';
import { SectionHeader } from '@/components/shared/SectionHeader';
import { formField, labelClass, controlClass, formHelpText } from '@/components/shared/Form';

interface DiscoveredServer {
  ip: string;
  port: number;
  type: 'pve' | 'pbs';
  version: string;
  hostname?: string;
  release?: string;
}

interface BatchCredentialModalProps {
  isOpen: boolean;
  onClose: () => void;
  servers: DiscoveredServer[];
  onComplete: () => void;
}

export const BatchCredentialModal: Component<BatchCredentialModalProps> = (props) => {
  const [authType, setAuthType] = createSignal<'password' | 'token'>('token');
  const [username, setUsername] = createSignal('');
  const [password, setPassword] = createSignal('');
  const [tokenName, setTokenName] = createSignal('');
  const [tokenValue, setTokenValue] = createSignal('');
  const [isAdding, setIsAdding] = createSignal(false);
  const [progress, setProgress] = createSignal<{
    current: number;
    total: number;
    currentServer?: string;
  }>({ current: 0, total: 0 });

  const handleBatchAdd = async () => {
    // Validate inputs
    if (authType() === 'password') {
      if (!username() || !password()) {
        showError('Username and password are required');
        return;
      }
    } else {
      if (!tokenName() || !tokenValue()) {
        showError('Token ID and value are required');
        return;
      }
    }

    setIsAdding(true);
    const total = props.servers.length;
    setProgress({ current: 0, total });

    let successCount = 0;
    let failedServers: string[] = [];

    for (let i = 0; i < props.servers.length; i++) {
      const server = props.servers[i];
      setProgress({ current: i + 1, total, currentServer: server.hostname || server.ip });

      try {
        const nodeData: NodeConfig = {
          id: '', // Will be generated by backend
          type: server.type,
          name: server.hostname || server.ip,
          host: `https://${server.ip}:${server.port}`,
          verifySSL: false,
          ...(authType() === 'password'
            ? { user: username(), password: password() }
            : { tokenName: tokenName(), tokenValue: tokenValue() }),
          // Add default monitoring options based on type
          ...(server.type === 'pve'
            ? {
                monitorVMs: true,
                monitorContainers: true,
                monitorStorage: true,
                monitorBackups: true,
                monitorPhysicalDisks: false,
              }
            : {
                monitorDatastores: true,
                monitorSyncJobs: true,
                monitorVerifyJobs: true,
                monitorPruneJobs: true,
                monitorGarbageJobs: false,
              }),
        } as NodeConfig;

        await NodesAPI.addNode(nodeData);
        successCount++;
      } catch (error) {
        console.error(`Failed to add ${server.hostname || server.ip}:`, error);
        failedServers.push(server.hostname || server.ip);
      }
    }

    setIsAdding(false);

    if (successCount === total) {
      showSuccess(`Successfully added all ${total} servers`);
      props.onComplete();
      props.onClose();
    } else if (successCount > 0) {
      showError(`Added ${successCount} of ${total} servers. Failed: ${failedServers.join(', ')}`);
      props.onComplete();
    } else {
      showError('Failed to add any servers. Check your credentials.');
    }
  };

  return (
    <Portal>
      <Show when={props.isOpen}>
        <div class="fixed inset-0 z-50 overflow-y-auto">
          <div class="flex min-h-screen items-center justify-center p-4">
            {/* Backdrop */}
            <div
              class="fixed inset-0 bg-black/50 transition-opacity"
              onClick={!isAdding() ? props.onClose : undefined}
            />

            {/* Modal */}
            <div class="relative w-full max-w-2xl bg-white dark:bg-gray-800 rounded-lg shadow-xl">
              {/* Header */}
              <div class="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
                <SectionHeader
                  title={`Add ${props.servers.length} discovered servers`}
                  size="md"
                  class="flex-1"
                />
                <Show when={!isAdding()}>
                  <button
                    type="button"
                    onClick={props.onClose}
                    class="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
                  >
                    <svg
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <line x1="18" y1="6" x2="6" y2="18"></line>
                      <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                  </button>
                </Show>
              </div>

              {/* Body */}
              <div class="p-6 space-y-6">
                {/* Server List */}
                <div>
                  <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    Servers to Add
                  </h4>
                  <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3 max-h-32 overflow-y-auto">
                    <div class="flex flex-wrap gap-2">
                      <For each={props.servers}>
                        {(server) => (
                          <span class="inline-flex items-center gap-1 px-2 py-1 text-xs bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded">
                            <span
                              class={`w-2 h-2 rounded-full ${server.type === 'pve' ? 'bg-orange-500' : 'bg-green-500'}`}
                            ></span>
                            {server.hostname || server.ip}
                          </span>
                        )}
                      </For>
                    </div>
                  </div>
                </div>

                {/* Shared Credentials */}
                <div>
                  <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    Shared Credentials
                    <span class="text-xs text-gray-500 dark:text-gray-400 ml-2">
                      (Same credentials will be used for all servers)
                    </span>
                  </h4>

                  {/* Auth Type Selector */}
                  <div class="mb-4">
                    <div class="flex gap-4">
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="batchAuthType"
                          value="token"
                          checked={authType() === 'token'}
                          onChange={() => setAuthType('token')}
                          disabled={isAdding()}
                          class="mr-2"
                        />
                        <span class="text-sm text-gray-700 dark:text-gray-300">
                          API Token (Recommended)
                        </span>
                      </label>
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="batchAuthType"
                          value="password"
                          checked={authType() === 'password'}
                          onChange={() => setAuthType('password')}
                          disabled={isAdding()}
                          class="mr-2"
                        />
                        <span class="text-sm text-gray-700 dark:text-gray-300">
                          Username & Password
                        </span>
                      </label>
                    </div>
                  </div>

                  {/* Token Auth Fields */}
                  <Show when={authType() === 'token'}>
                    <div class="space-y-4">
                      <div class={formField}>
                        <label class={labelClass()}>
                          Token ID <span class="text-red-500">*</span>
                        </label>
                        <input
                          type="text"
                          value={tokenName()}
                          onInput={(e) => setTokenName(e.currentTarget.value)}
                          placeholder="user@realm!tokenname"
                          disabled={isAdding()}
                          class={controlClass('font-mono')}
                        />
                        <p class={`${formHelpText} mt-1`}>
                          Example: pulse-monitor@pam!pulse-token or pulse-monitor@pbs!pulse-token
                        </p>
                      </div>

                      <div class={formField}>
                        <label class={labelClass()}>
                          Token Value <span class="text-red-500">*</span>
                        </label>
                        <input
                          type="password"
                          value={tokenValue()}
                          onInput={(e) => setTokenValue(e.currentTarget.value)}
                          placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                          disabled={isAdding()}
                          class={controlClass('font-mono')}
                        />
                      </div>
                    </div>
                  </Show>

                  {/* Password Auth Fields */}
                  <Show when={authType() === 'password'}>
                    <div class="space-y-4">
                      <div class={formField}>
                        <label class={labelClass()}>
                          Username <span class="text-red-500">*</span>
                        </label>
                        <input
                          type="text"
                          value={username()}
                          onInput={(e) => setUsername(e.currentTarget.value)}
                          placeholder="root@pam or admin@pbs"
                          disabled={isAdding()}
                          class={controlClass()}
                        />
                      </div>

                      <div class={formField}>
                        <label class={labelClass()}>
                          Password <span class="text-red-500">*</span>
                        </label>
                        <input
                          type="password"
                          value={password()}
                          onInput={(e) => setPassword(e.currentTarget.value)}
                          placeholder="Password"
                          disabled={isAdding()}
                          class={controlClass()}
                        />
                      </div>
                    </div>
                  </Show>
                </div>

                {/* Progress */}
                <Show when={isAdding()}>
                  <div class="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                    <div class="flex items-center gap-3 mb-2">
                      <svg
                        class="animate-spin h-5 w-5 text-blue-600 dark:text-blue-400"
                        viewBox="0 0 24 24"
                        fill="none"
                      >
                        <circle
                          class="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          stroke-width="4"
                        ></circle>
                        <path
                          class="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        ></path>
                      </svg>
                      <div>
                        <p class="text-sm font-medium text-blue-800 dark:text-blue-200">
                          Adding servers... ({progress().current}/{progress().total})
                        </p>
                        <Show when={progress().currentServer}>
                          <p class="text-xs text-blue-700 dark:text-blue-300">
                            Currently adding: {progress().currentServer}
                          </p>
                        </Show>
                      </div>
                    </div>
                    <div class="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-2">
                      <div
                        class="bg-blue-600 dark:bg-blue-400 h-2 rounded-full transition-all"
                        style={`width: ${(progress().current / progress().total) * 100}%`}
                      ></div>
                    </div>
                  </div>
                </Show>
              </div>

              {/* Footer */}
              <div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
                <button
                  type="button"
                  onClick={props.onClose}
                  disabled={isAdding()}
                  class="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleBatchAdd}
                  disabled={isAdding()}
                  class="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isAdding() ? 'Adding...' : `Add ${props.servers.length} Servers`}
                </button>
              </div>
            </div>
          </div>
        </div>
      </Show>
    </Portal>
  );
};
