/**
 * NoteForm Component — shadcn/ui styled
 *
 * Clean, minimal note form. Always visible.
 * Uses Memos access token for API calls.
 */

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

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 [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('Chưa nhập nội dung ghi chú');
      return;
    }

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

    try {
      const token = await getToken();
      if (!token) {
        setError('Chưa đồng bộ. Mở Canifa Note trên trình duyệt và đăng nhập.');
        setLoading(false);
        return;
      }

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

      await createMemoWithToken(token, {
        content,
        tags,
        visibility,
      });

      setLoading(false);
      setSaved(true);
      setText('');
      setTags([]);
      setError(null);
      setTimeout(() => setSaved(false), 3000);
      if (onSave) onSave();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Lưu thất bại');
      setLoading(false);
    }
  };

  return (
    <div className="note-form">
      <div className="content">
        {/* Success */}
        {saved && (
          <div className="success" style={{ textAlign: 'center', animation: 'fadeIn 0.2s ease' }}>
            ✓ Đã lưu vào Canifa Note
          </div>
        )}

        {/* Textarea */}
        <textarea
          className="note-textarea"
          placeholder="Ghi chú..."
          value={text}
          onChange={(e) => setText(e.target.value)}
          rows={4}
          autoFocus
        />

        {/* Source */}
        {initialUrl && initialUrl !== 'about:blank' && (
          <div className="source-info">
            <svg className="source-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
              <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
            </svg>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {initialTitle || initialUrl}
            </span>
          </div>
        )}

        {/* Tags */}
        <div style={{ marginTop: '10px' }}>
          <TagSelector selectedTags={tags} onChange={setTags} />
        </div>

        {/* 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={`Toggle: ${visibility}`}
          >
            {visibility === 'PRIVATE' ? (
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
            ) : (
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="10" />
                <line x1="2" y1="12" x2="22" y2="12" />
                <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
              </svg>
            )}
            {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" style={{ width: 12, height: 12 }} /> Saving...
              </>
            ) : (
              'Save'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
