import { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { apiClient } from '../lib/api';
import type { InvitationPreview } from '../types/api';
import { useAuthStore } from '../lib/auth';
import type { User } from '../types/api';

type Stage = 'loading' | 'error' | 'new-user' | 'existing-user' | 'ms-user' | 'already-member' | 'success';

export function AcceptInvite() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token') ?? '';

  const [stage, setStage] = useState<Stage>('loading');
  const [preview, setPreview] = useState<InvitationPreview | null>(null);
  const [errorMsg, setErrorMsg] = useState('');
  const [fullName, setFullName] = useState('');
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const setUser = useAuthStore((s) => s.setUser);

  useEffect(() => {
    if (!token) {
      setErrorMsg('Invalid invitation link.');
      setStage('error');
      return;
    }
    apiClient.previewInvitation(token)
      .then((data) => {
        setPreview(data);
        if (data.is_existing_member) {
          setStage('already-member');
        } else if (data.requires_microsoft_signin) {
          setStage('ms-user');
        } else if (data.requires_password_setup) {
          setStage('new-user');
        } else {
          setStage('existing-user');
        }
      })
      .catch((err) => {
        setErrorMsg(err?.response?.data?.detail ?? 'This invitation is no longer valid.');
        setStage('error');
      });
  }, [token]);

  async function submit() {
    setSubmitting(true);
    try {
      const result = await apiClient.acceptInvitation({ token, full_name: fullName || undefined, password: password || undefined });
      apiClient.setAccessToken(result.access_token);
      const user: User = {
        id: result.user_id,
        email: result.email,
        full_name: result.full_name,
        role: 'client',
        auth_provider: 'local',
        is_active: true,
        created_at: new Date().toISOString(),
      };
      setUser(user);
      setStage('success');
      setTimeout(() => navigate(result.redirect_to), 1500);
    } catch (err) {
      const e = err as { response?: { data?: { detail?: string } } };
      setErrorMsg(e?.response?.data?.detail ?? 'Failed to accept invitation.');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-xl shadow-lg max-w-md w-full p-8">
        <div className="text-center mb-6">
          <div className="w-12 h-12 bg-indigo-600 rounded-xl flex items-center justify-center mx-auto mb-4">
            <span className="text-white text-2xl font-bold">A</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Accessible Video Platform</h1>
        </div>

        {stage === 'loading' && (
          <div className="text-center text-gray-500 py-8">Verifying invitation…</div>
        )}

        {stage === 'error' && (
          <div className="text-center">
            <div className="text-red-600 text-lg font-medium mb-2">Invitation Invalid</div>
            <p className="text-gray-500 mb-4">{errorMsg}</p>
            <p className="text-sm text-gray-400">Contact your admin to request a new invitation.</p>
          </div>
        )}

        {stage === 'already-member' && preview && (
          <div className="text-center">
            <div className="text-green-600 text-lg font-medium mb-2">Already a Member</div>
            <p className="text-gray-500 mb-4">You already belong to <strong>{preview.org_name}</strong>.</p>
            <button onClick={() => navigate('/login')} className="btn-primary w-full">Go to Login</button>
          </div>
        )}

        {stage === 'success' && (
          <div className="text-center">
            <div className="text-green-600 text-2xl mb-2">✓</div>
            <div className="text-green-600 text-lg font-medium">Invitation Accepted</div>
            <p className="text-gray-500">Redirecting you to your dashboard…</p>
          </div>
        )}

        {(stage === 'new-user' || stage === 'existing-user') && preview && (
          <div>
            <h2 className="text-xl font-semibold text-gray-800 mb-1">
              Join <span className="text-indigo-600">{preview.org_name}</span>
            </h2>
            <p className="text-sm text-gray-500 mb-6">
              Invited by <strong>{preview.inviter_name}</strong> as <span className="capitalize">{preview.role_in_org}</span>
            </p>

            {errorMsg && (
              <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg p-3 mb-4">
                {errorMsg}
              </div>
            )}

            <div className="space-y-4">
              {stage === 'new-user' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Full name</label>
                  <input
                    type="text"
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    placeholder="Your name"
                  />
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {stage === 'new-user' ? 'Create password' : 'Confirm with your password'}
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  placeholder="••••••••"
                />
              </div>

              <button
                onClick={submit}
                disabled={submitting || (stage === 'new-user' && (!fullName || !password))}
                className="w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white font-medium py-2.5 rounded-lg transition-colors"
              >
                {submitting ? 'Accepting…' : 'Accept Invitation'}
              </button>
            </div>
          </div>
        )}

        {stage === 'ms-user' && preview && (
          <div className="text-center">
            <h2 className="text-xl font-semibold text-gray-800 mb-2">
              Join <span className="text-indigo-600">{preview.org_name}</span>
            </h2>
            <p className="text-sm text-gray-500 mb-6">Sign in with Microsoft to accept your invitation.</p>
            <button
              onClick={() => navigate('/login?invite_token=' + encodeURIComponent(token))}
              className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2.5 rounded-lg transition-colors"
            >
              Sign in with Microsoft
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
