import React, { useState } from 'react';
import Modal from '@/shared/components/ui/Modal';
import { apiClient } from '@/shared/services/apiClient';
import { useToast } from '@/shared/components/ui/Toast';

export default function InviteMembersModal({ isOpen, onClose, projectId = 1 }) {
  const [email, setEmail] = useState('');
  const [generatedUrl, setGeneratedUrl] = useState('');
  const [isInviting, setIsInviting] = useState(false);
  const [copied, setCopied] = useState(false);

  const { addToast } = useToast() || {};

  const handleGenerateInvite = async (e) => {
    e?.preventDefault();
    if (!email.trim()) return;

    try {
      setIsInviting(true);
      const res = await apiClient('/invitations/invite.php', {
        method: 'POST',
        body: {
          project_id: parseInt(projectId, 10),
          email: email.trim(),
        },
      });

      if (res?.invite_url) {
        setGeneratedUrl(res.invite_url);
        addToast?.('Invitation link generated!', 'success');
      }
    } catch (err) {
      console.error('Invite error:', err);
      addToast?.(err.message || 'Failed to generate invitation.', 'error');
    } finally {
      setIsInviting(false);
    }
  };

  const handleCopy = async () => {
    if (!generatedUrl) return;

    try {
      // 1. Try modern Clipboard API (Works on HTTPS or Localhost)
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(generatedUrl);
        setCopied(true);
        addToast?.('Invite link copied to clipboard!', 'success');
        setTimeout(() => setCopied(false), 2000);
        return;
      }

      // 2. Fallback for HTTP / Non-Secure IP Contexts
      const textArea = document.createElement('textarea');
      textArea.value = generatedUrl;
      
      // Make element invisible
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      
      textArea.focus();
      textArea.select();

      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);

      if (successful) {
        setCopied(true);
        addToast?.('Invite link copied to clipboard!', 'success');
        setTimeout(() => setCopied(false), 2000);
      } else {
        throw new Error('Copy command returned false');
      }
    } catch (err) {
      console.error('Failed to copy link: ', err);
      addToast?.('Failed to copy link. Please copy manually.', 'error');
    }
  };

  const handleReset = () => {
    setEmail('');
    setGeneratedUrl('');
    setCopied(false);
    onClose();
  };

  return (
    <Modal isOpen={isOpen} onClose={handleReset} title="Invite Teammates to Project">
      <div className="space-y-5 text-slate-200">
        <p className="text-xs text-slate-400">
          Invite team members by email to collaborate on this project board.
        </p>

        {!generatedUrl ? (
          <form onSubmit={handleGenerateInvite} className="space-y-4">
            <div className="space-y-1">
              <label className="text-xs font-semibold text-slate-300">Teammate Email</label>
              <input
                type="email"
                required
                placeholder="colleague@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-xs text-slate-100 outline-none focus:border-sky-500"
              />
            </div>

            <div className="flex justify-end gap-2 pt-2">
              <button
                type="button"
                onClick={handleReset}
                className="px-4 py-2 text-xs font-medium text-slate-400 hover:text-slate-200"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={isInviting || !email.trim()}
                className="px-4 py-2 bg-sky-600 hover:bg-sky-500 disabled:opacity-50 text-xs font-medium text-white rounded-xl transition-all"
              >
                {isInviting ? 'Generating...' : 'Generate Invite Link'}
              </button>
            </div>
          </form>
        ) : (
          <div className="space-y-4">
            <div className="p-3 bg-emerald-500/10 border border-emerald-500/30 rounded-xl text-xs text-emerald-300 flex items-center gap-2">
              <span>🎉</span>
              <span>Invite link generated for <strong>{email}</strong>!</span>
            </div>

            <div className="space-y-1">
              <label className="text-xs font-semibold text-slate-300">Shareable Join Link</label>
              <div className="flex gap-2">
                <input
                  type="text"
                  readOnly
                  value={generatedUrl}
                  onClick={(e) => e.target.select()}
                  className="flex-1 bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-xs text-sky-400 outline-none font-mono selection:bg-sky-500/30 cursor-pointer"
                />
                <button
                  type="button"
                  onClick={handleCopy}
                  className="px-4 py-2 bg-sky-600 hover:bg-sky-500 text-xs font-medium text-white rounded-xl transition-all shrink-0"
                >
                  {copied ? 'Copied! ✓' : 'Copy Link'}
                </button>
              </div>
            </div>

            <div className="flex justify-end pt-2">
              <button
                type="button"
                onClick={handleReset}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-xs font-medium text-slate-200 rounded-xl"
              >
                Done
              </button>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}