import React, { useState } from 'react';

const mockInvites = [
  { code: 'aethex123', channel: 'general', uses: 45, maxUses: 0, expiresAt: null, createdBy: 'Trevor', createdAt: '2025-01-10T10:00:00' },
  { code: 'devjoin', channel: 'api-discussion', uses: 12, maxUses: 50, expiresAt: '2026-02-15T00:00:00', createdBy: 'Sarah', createdAt: '2025-02-01T14:30:00' },
  { code: 'labsonly', channel: 'labs-chat', uses: 8, maxUses: 25, expiresAt: '2026-03-01T00:00:00', createdBy: 'DevUser_2847', createdAt: '2025-02-03T09:15:00' },
  { code: 'temp7day', channel: 'help', uses: 3, maxUses: 10, expiresAt: '2026-02-12T00:00:00', createdBy: 'Trevor', createdAt: '2025-02-05T16:45:00' },
];

export default function InviteManager({ onClose, onCreate }) {
  const [invites, setInvites] = useState(mockInvites);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [copiedCode, setCopiedCode] = useState(null);

  // Create invite form state
  const [selectedChannel, setSelectedChannel] = useState('general');
  const [maxUses, setMaxUses] = useState(0);
  const [expiresIn, setExpiresIn] = useState('never');

  const channels = ['general', 'api-discussion', 'help', 'announcements', 'labs-chat'];

  const formatDate = (dateStr) => {
    if (!dateStr) return 'Never';
    const date = new Date(dateStr);
    const now = new Date();
    const diff = date.getTime() - now.getTime();
    const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
    if (days < 0) return 'Expired';
    if (days === 0) return 'Today';
    if (days === 1) return 'Tomorrow';
    return `${days} days`;
  };

  const copyInvite = (code) => {
    navigator.clipboard.writeText(`https://aethex.gg/invite/${code}`);
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 2000);
  };

  const deleteInvite = (code) => {
    setInvites(prev => prev.filter(inv => inv.code !== code));
  };

  const createInvite = () => {
    const newCode = Math.random().toString(36).substring(2, 10);
    const expiresAt = expiresIn === 'never' ? null :
      new Date(Date.now() + parseInt(expiresIn) * 1000).toISOString();

    setInvites(prev => [{
      code: newCode,
      channel: selectedChannel,
      uses: 0,
      maxUses: maxUses,
      expiresAt,
      createdBy: 'You',
      createdAt: new Date().toISOString(),
    }, ...prev]);

    setShowCreateModal(false);
    copyInvite(newCode);
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="invite-manager-modal" onClick={(e) => e.stopPropagation()}>
        <div className="invite-manager-header">
          <h2>✉️ Server Invites</h2>
          <button className="invite-manager-close" onClick={onClose}>✕</button>
        </div>

        <div className="invite-manager-actions">
          <button className="create-invite-btn" onClick={() => setShowCreateModal(true)}>
            + Create Invite
          </button>
        </div>

        <div className="invite-list">
          {invites.length === 0 ? (
            <div className="no-invites">
              <p>No active invites</p>
              <span>Create an invite to share your server</span>
            </div>
          ) : (
            <>
              <div className="invite-list-header">
                <span className="col-code">Invite Code</span>
                <span className="col-channel">Channel</span>
                <span className="col-uses">Uses</span>
                <span className="col-expires">Expires</span>
                <span className="col-creator">Created By</span>
                <span className="col-actions"></span>
              </div>
              {invites.map(invite => (
                <div key={invite.code} className="invite-item">
                  <div className="invite-code">
                    <code>{invite.code}</code>
                    <button
                      className={`copy-btn ${copiedCode === invite.code ? 'copied' : ''}`}
                      onClick={() => copyInvite(invite.code)}
                    >
                      {copiedCode === invite.code ? '✓' : '📋'}
                    </button>
                  </div>
                  <div className="invite-channel">#{invite.channel}</div>
                  <div className="invite-uses">
                    {invite.uses}{invite.maxUses > 0 ? ` / ${invite.maxUses}` : ''}
                  </div>
                  <div className="invite-expires">{formatDate(invite.expiresAt)}</div>
                  <div className="invite-creator">{invite.createdBy}</div>
                  <div className="invite-actions">
                    <button
                      className="delete-invite-btn"
                      onClick={() => deleteInvite(invite.code)}
                      title="Delete invite"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
              ))}
            </>
          )}
        </div>

        <div className="invite-manager-footer">
          <span className="invite-hint">
            Invite links: aethex.gg/invite/CODE
          </span>
        </div>

        {showCreateModal && (
          <div className="create-invite-overlay" onClick={() => setShowCreateModal(false)}>
            <div className="create-invite-modal" onClick={(e) => e.stopPropagation()}>
              <h3>Create Invite Link</h3>

              <div className="create-field">
                <label>Invite to Channel</label>
                <select value={selectedChannel} onChange={(e) => setSelectedChannel(e.target.value)}>
                  {channels.map(ch => (
                    <option key={ch} value={ch}>#{ch}</option>
                  ))}
                </select>
              </div>

              <div className="create-field">
                <label>Expire After</label>
                <select value={expiresIn} onChange={(e) => setExpiresIn(e.target.value)}>
                  <option value="1800">30 minutes</option>
                  <option value="3600">1 hour</option>
                  <option value="21600">6 hours</option>
                  <option value="43200">12 hours</option>
                  <option value="86400">1 day</option>
                  <option value="604800">7 days</option>
                  <option value="never">Never</option>
                </select>
              </div>

              <div className="create-field">
                <label>Max Uses</label>
                <select value={maxUses} onChange={(e) => setMaxUses(parseInt(e.target.value))}>
                  <option value="0">No limit</option>
                  <option value="1">1 use</option>
                  <option value="5">5 uses</option>
                  <option value="10">10 uses</option>
                  <option value="25">25 uses</option>
                  <option value="50">50 uses</option>
                  <option value="100">100 uses</option>
                </select>
              </div>

              <div className="create-actions">
                <button className="cancel-btn" onClick={() => setShowCreateModal(false)}>
                  Cancel
                </button>
                <button className="generate-btn" onClick={createInvite}>
                  Generate Invite
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
