/**
 * NoteForm Component
 * 
 * The main note-taking form. Accepts a getToken prop from Clerk
 * to get fresh JWTs for API calls. Does NOT close the popup after save.
 */

import { useState } from 'react';
import { createMemoWithToken } from '../shared/api-client';
import { TagSelector } from './TagSelector';
import { WorkspaceSelector } from './WorkspaceSelector';

interface NoteFormProps {
  initialText?: string;
  initialUrl?: string;
  initialTitle?: string;
  getToken: () => Promise<string | null>;
  onSave?: () => void;
  onCancel?: () => void;
}

export function NoteForm({
  initialText = '',
  initialUrl = '',
  initialTitle = '',
  getToken,
  onSave,
  onCancel,
}: NoteFormProps) {
  const [text, setText] = useState(initialText);
  const [tags, setTags] = useState<string[]>([]);
  const [workspace, setWorkspace] = useState('');
  const [visibility, setVisibility] = useState<'PRIVATE' | 'PUBLIC'>('PRIVATE');
  const [loading, setLoading] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSave = async () => {
    if (!text.trim()) {
      setError('Note cannot be empty');
      return;
    }

    setLoading(true);
    setError(null);
    setSaved(false);

    try {
      // Get FRESH token from Clerk
      const token = await getToken();
      if (!token) {
        setError('Not authenticated. Please sign in again.');
        setLoading(false);
        return;
      }

      // Build content with source info
      let content = text;
      if (initialUrl && initialUrl !== 'about:blank') {
        content += `\n\n---\nSource: [${initialTitle || initialUrl}](${initialUrl})`;
      }

      // Call API with fresh token
      await createMemoWithToken(token, {
        content,
        tags,
        visibility,
      });

      // Success! Show message but KEEP popup open
      setLoading(false);
      setSaved(true);

      // Clear form for next note
      setText('');
      setTags([]);
      setError(null);

      // Auto-hide success after 3s
      setTimeout(() => setSaved(false), 3000);

      if (onSave) onSave();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save note');
      setLoading(false);
    }
  };

  return (
    <div className="note-form">
      <div className="content">
        {/* Success Banner */}
        {saved && (
          <div className="badge badge-success" style={{
            textAlign: 'center',
            padding: '10px',
            fontSize: '14px',
            marginBottom: '8px',
            animation: 'fadeIn 0.3s ease'
          }}>
            ✅ Saved to CuCu Note!
          </div>
        )}

        {/* Text Area */}
        <textarea
          className="note-textarea"
          placeholder="Any thoughts..."
          value={text}
          onChange={(e) => setText(e.target.value)}
          rows={4}
          autoFocus
        />

        {/* Source Info */}
        {initialUrl && initialUrl !== 'about:blank' && (
          <div className="source-info" style={{
            fontSize: '12px',
            color: 'var(--text-secondary)',
            padding: '6px 10px',
            backgroundColor: 'var(--surface)',
            borderRadius: '8px',
            marginTop: '6px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}>
            🔗 {initialTitle || initialUrl}
          </div>
        )}

        {/* Tag Selector */}
        <div style={{ marginTop: '12px' }}>
          <TagSelector selectedTags={tags} onChange={setTags} />
        </div>

        {/* Workspace Selector */}
        <WorkspaceSelector value={workspace} onChange={setWorkspace} />

        {/* Error */}
        {error && <div className="error">{error}</div>}
      </div>

      {/* Action Bar */}
      <div className="action-bar">
        <div className="action-bar-left">
          <button
            className="visibility-selector"
            onClick={() =>
              setVisibility(visibility === 'PRIVATE' ? 'PUBLIC' : 'PRIVATE')
            }
            title={`Click to toggle: ${visibility}`}
          >
            {visibility === 'PRIVATE' ? '🔒' : '🌐'}{' '}
            {visibility === 'PRIVATE' ? 'Private' : 'Public'}
          </button>
        </div>
        <div className="action-bar-right">
          <button
            className="btn btn-ghost btn-sm"
            onClick={onCancel || (() => window.close())}
            disabled={loading}
          >
            Cancel
          </button>
          <button
            className="btn btn-primary btn-sm"
            onClick={handleSave}
            disabled={loading || !text.trim()}
          >
            {saved ? (
              '✅ Saved!'
            ) : loading ? (
              <>
                <span className="spinner" /> Saving...
              </>
            ) : (
              'Save'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
