import { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { CheckCircle2, AlertTriangle, Loader2, LogIn } from 'lucide-react';
import { invitationService } from '@/services/invitationService';
import { base44 } from '@/api/base44Client';

export default function InvitationAccept() {
  const { token } = useParams();
  const nav = useNavigate();
  const [inv, setInv] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    invitationService.getByToken(token).then(i => {
      setInv(i);
      if (!i) setError('Invalid invitation link.');
      else if (i.status !== 'pending') setError(`This invitation is ${i.status}.`);
      else if (new Date(i.expiry_date) < new Date()) setError('This invitation has expired.');
      setLoading(false);
    });
  }, [token]);

  const accept = async () => {
    setError('');
    try {
      const me = await base44.auth.me();
      if (!me) { base44.auth.redirectToLogin(window.location.href); return; }
      // Role assignment happens entirely server-side; the client sends only the
      // opaque token and cannot influence the granted role.
      const res = await base44.functions.invoke('acceptInvitation', { token });
      if (res.data?.error) { setError(res.data.error); return; }
      window.location.href = res.data?.redirect || '/portal';
    } catch (e) { setError(e?.message || 'Unable to accept invitation.'); }
  };

  if (loading) return <div className="flex min-h-screen items-center justify-center text-slate-400"><Loader2 className="h-6 w-6 animate-spin" /></div>;

  return (
    <div className="flex min-h-screen items-center justify-center bg-workshop p-6">
      <div className="panel w-full max-w-md p-8 text-center">
        <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-shire-purple/15"><LogIn className="h-7 w-7 text-shire-purple-bright" /></div>
        <h1 className="text-xl font-semibold text-white">SHiRE Workshop Invitation</h1>
        {error ? (
          <div className="mt-4 flex items-center gap-2 rounded-lg border border-red-400/30 bg-red-400/10 p-3 text-sm text-red-300"><AlertTriangle className="h-4 w-4" />{error}</div>
        ) : (
          <>
            <p className="mt-2 text-sm text-shire-text-secondary">You have been invited as <strong className="text-violet-300">{inv.intended_role}</strong>{inv.email ? ` for ${inv.email}` : ''}.</p>
            <p className="mt-2 text-xs text-shire-text-muted">Accepting links this account to your SHiRE profile and grants the assigned permissions.</p>
            <button className="btn-primary mt-6 w-full" onClick={accept}><CheckCircle2 />Accept Invitation</button>
            <p className="mt-3 text-xs text-shire-text-muted">You must be signed in to accept. You will be redirected to log in if needed.</p>
          </>
        )}
        <Link to="/login" className="mt-4 block text-xs text-slate-500 hover:text-violet-300">Back to login</Link>
      </div>
    </div>
  );
}