import React, { useState, useRef } from 'react';

const existingEmojis = [
  { id: 1, name: 'pepehype', image: '🐸', animated: false },
  { id: 2, name: 'monkaS', image: '😰', animated: false },
  { id: 3, name: 'KEKW', image: '🤣', animated: false },
  { id: 4, name: 'Pog', image: '😮', animated: true },
  { id: 5, name: 'catJAM', image: '🐱', animated: true },
  { id: 6, name: 'aethex_logo', image: '🔺', animated: false },
];

const existingStickers = [
  { id: 1, name: 'Wave', emoji: '👋', description: 'A friendly wave' },
  { id: 2, name: 'Love', emoji: '❤️', description: 'Show some love' },
  { id: 3, name: 'Party', emoji: '🎉', description: 'Party time!' },
];

export default function EmojiUpload({ type = 'emoji', onUpload, onClose }) {
  const [activeTab, setActiveTab] = useState(type);
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [emojiName, setEmojiName] = useState('');
  const [stickerDescription, setStickerDescription] = useState('');
  const [relatedEmoji, setRelatedEmoji] = useState('');
  const fileInputRef = useRef(null);

  const handleFileSelect = (e) => {
    const files = Array.from(e.target.files);
    const newFiles = files.map(file => ({
      id: Date.now() + Math.random(),
      file,
      name: file.name.split('.')[0],
      preview: URL.createObjectURL(file),
      size: (file.size / 1024).toFixed(1) + ' KB',
      animated: file.type === 'image/gif',
    }));
    setUploadedFiles(prev => [...prev, ...newFiles]);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    const files = Array.from(e.dataTransfer.files);
    const newFiles = files.map(file => ({
      id: Date.now() + Math.random(),
      file,
      name: file.name.split('.')[0],
      preview: URL.createObjectURL(file),
      size: (file.size / 1024).toFixed(1) + ' KB',
      animated: file.type === 'image/gif',
    }));
    setUploadedFiles(prev => [...prev, ...newFiles]);
  };

  const removeFile = (fileId) => {
    setUploadedFiles(prev => prev.filter(f => f.id !== fileId));
  };

  const updateFileName = (fileId, name) => {
    setUploadedFiles(prev => prev.map(f => 
      f.id === fileId ? { ...f, name } : f
    ));
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="emoji-upload-modal" onClick={(e) => e.stopPropagation()}>
        <div className="emoji-upload-header">
          <h2>Upload {activeTab === 'emoji' ? 'Emoji' : 'Sticker'}</h2>
          <button className="close-btn" onClick={onClose}>✕</button>
        </div>

        <div className="emoji-upload-tabs">
          <button
            className={`upload-tab ${activeTab === 'emoji' ? 'active' : ''}`}
            onClick={() => setActiveTab('emoji')}
          >
            😀 Emoji
          </button>
          <button
            className={`upload-tab ${activeTab === 'sticker' ? 'active' : ''}`}
            onClick={() => setActiveTab('sticker')}
          >
            🎨 Sticker
          </button>
        </div>

        <div className="emoji-upload-content">
          {/* Existing items */}
          <div className="existing-items">
            <h3>{activeTab === 'emoji' ? 'Server Emoji' : 'Server Stickers'}</h3>
            <div className="items-grid">
              {activeTab === 'emoji' ? (
                existingEmojis.map(emoji => (
                  <div key={emoji.id} className="item-card">
                    <div className="item-preview">{emoji.image}</div>
                    <span className="item-name">:{emoji.name}:</span>
                    {emoji.animated && <span className="animated-badge">GIF</span>}
                  </div>
                ))
              ) : (
                existingStickers.map(sticker => (
                  <div key={sticker.id} className="item-card sticker">
                    <div className="item-preview">{sticker.emoji}</div>
                    <span className="item-name">{sticker.name}</span>
                  </div>
                ))
              )}
            </div>
            <div className="slots-info">
              {activeTab === 'emoji' ? (
                <span>6/50 slots used ({existingEmojis.filter(e => e.animated).length}/50 animated)</span>
              ) : (
                <span>3/15 sticker slots used</span>
              )}
            </div>
          </div>

          {/* Upload zone */}
          <div 
            className="upload-zone"
            onDragOver={(e) => e.preventDefault()}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept={activeTab === 'emoji' ? 'image/png,image/gif' : 'image/png,image/apng'}
              multiple
              onChange={handleFileSelect}
              hidden
            />
            <div className="upload-icon">📤</div>
            <p>Drag and drop or click to upload</p>
            <span className="upload-hint">
              {activeTab === 'emoji' 
                ? 'PNG or GIF, 256KB max, 128x128 recommended'
                : 'PNG or APNG, 512KB max, 320x320 size'
              }
            </span>
          </div>

          {/* Pending uploads */}
          {uploadedFiles.length > 0 && (
            <div className="pending-uploads">
              <h3>Ready to Upload</h3>
              {uploadedFiles.map(file => (
                <div key={file.id} className="pending-file">
                  <img src={file.preview} alt="" className="pending-preview" />
                  <div className="pending-info">
                    <input
                      type="text"
                      value={file.name}
                      onChange={(e) => updateFileName(file.id, e.target.value)}
                      placeholder="Name"
                      className="pending-name-input"
                    />
                    <span className="pending-size">{file.size}</span>
                    {file.animated && <span className="animated-badge">GIF</span>}
                  </div>
                  <button 
                    className="pending-remove"
                    onClick={() => removeFile(file.id)}
                  >
                    ✕
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="emoji-upload-footer">
          <button className="cancel-btn" onClick={onClose}>Cancel</button>
          <button 
            className="upload-btn"
            disabled={uploadedFiles.length === 0}
            onClick={() => onUpload?.(uploadedFiles)}
          >
            Upload {uploadedFiles.length > 0 ? `(${uploadedFiles.length})` : ''}
          </button>
        </div>
      </div>
    </div>
  );
}
