import { useState } from 'react';
import { api } from '../lib/api.ts';

interface InviteModalProps {
  serverId: string;
  serverName: string;
  onClose: () => void;
}

interface InviteResult {
  code: string;
  server_name: string;
  max_uses: number | null;
  use_count: number;
  expires_at: string | null;
}

export function InviteModal({ serverId, serverName, onClose }: InviteModalProps) {
  const [expiresHours, setExpiresHours] = useState(24);
  const [maxUses, setMaxUses] = useState<number | ''>('');
  const [invite, setInvite] = useState<InviteResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const createInvite = async () => {
    setLoading(true);
    setError(null);
    try {
      const payload: Record<string, unknown> = {
        expires_hours: expiresHours,
      };
      if (maxUses !== '') {
        payload.max_uses = maxUses;
      }
      const result = await api.post<InviteResult>(`/servers/${serverId}/invites`, payload);
      setInvite(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create invite');
    } finally {
      setLoading(false);
    }
  };

  const inviteUrl = invite ? `${window.location.origin}/invites/${invite.code}` : '';

  const copyLink = () => {
    if (inviteUrl) {
      navigator.clipboard.writeText(inviteUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-gb-bg border border-gb-bg-t p-4 min-w-[350px] font-mono" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-3">
          <span className="text-sm text-gb-orange">INVITE TO {serverName.toUpperCase()}</span>
          <button onClick={onClose} className="text-xs text-gb-red">[x]</button>
        </div>

        {!invite ? (
          <div className="space-y-3">
            <div>
              <label className="text-xs text-gb-fg-f block mb-1">EXPIRES IN:</label>
              <select
                value={expiresHours}
                onChange={(e) => setExpiresHours(Number(e.target.value))}
                className="w-full px-2 py-1 bg-gb-bg-s text-gb-fg text-xs border-none outline-none"
              >
                <option value={1}>1 hour</option>
                <option value={6}>6 hours</option>
                <option value={12}>12 hours</option>
                <option value={24}>24 hours</option>
                <option value={168}>7 days</option>
                <option value={0}>Never</option>
              </select>
            </div>
            <div>
              <label className="text-xs text-gb-fg-f block mb-1">MAX USES:</label>
              <input
                type="number"
                value={maxUses}
                onChange={(e) => setMaxUses(e.target.value === '' ? '' : Number(e.target.value))}
                placeholder="unlimited"
                min={1}
                className="w-full px-2 py-1 bg-gb-bg-s text-gb-fg text-xs border-none outline-none"
              />
            </div>
            {error && (
              <div className="text-xs text-gb-red">{error}</div>
            )}
            <button
              onClick={createInvite}
              disabled={loading}
              className="w-full px-3 py-1.5 bg-gb-orange text-gb-bg text-xs font-mono hover:bg-gb-yellow transition-colors disabled:opacity-50"
            >
              {loading ? 'CREATING...' : '[GENERATE LINK]'}
            </button>
          </div>
        ) : (
          <div className="space-y-3">
            <div className="text-xs text-gb-fg-f">Share this link:</div>
            <div className="flex gap-2">
              <input
                type="text"
                value={inviteUrl}
                readOnly
                className="flex-1 px-2 py-1 bg-gb-bg-s text-gb-fg text-xs border-none outline-none"
              />
              <button
                onClick={copyLink}
                className="px-3 py-1 bg-gb-bg-t text-gb-fg text-xs font-mono hover:bg-gb-bg-s transition-colors"
              >
                {copied ? '[COPIED!]' : '[COPY]'}
              </button>
            </div>
            {invite.expires_at && (
              <div className="text-xs text-gb-fg-f">
                Expires: {new Date(invite.expires_at).toLocaleString()}
              </div>
            )}
            {invite.max_uses && (
              <div className="text-xs text-gb-fg-f">
                Max uses: {invite.max_uses}
              </div>
            )}
            <button
              onClick={() => setInvite(null)}
              className="text-xs text-gb-aqua hover:text-gb-orange transition-colors"
            >
              [CREATE ANOTHER]
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
