import { useEffect, useState } from 'react';
import { useNavigate, Link, useSearchParams } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { authAPI } from '../services/api';

export default function Register() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token') || '';
  const [invitation, setInvitation] = useState(null);
  const [pageError, setPageError] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loadingInvitation, setLoadingInvitation] = useState(true);
  const navigate = useNavigate();
  const { register, loading, error, clearError } = useAuthStore();

  useEffect(() => {
    const loadInvitation = async () => {
      if (!token) {
        setPageError('Invitation link is required to create an account.');
        setLoadingInvitation(false);
        return;
      }

      try {
        const response = await authAPI.getInvitation(token);
        setInvitation(response);
      } catch (loadError) {
        setPageError(loadError.response?.data?.error || 'Invitation link is invalid or expired.');
      } finally {
        setLoadingInvitation(false);
      }
    };

    loadInvitation();
  }, [token]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    clearError();

    if (password !== confirmPassword) {
      setPageError('Passwords do not match.');
      return;
    }

    const success = await register(token, password);
    if (success) {
      navigate('/login');
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-r from-blue-600 to-blue-800 flex items-center justify-center px-4">
      <div className="bg-white rounded-lg shadow-xl p-8 w-full max-w-md">
        <h1 className="text-3xl font-bold text-center text-gray-800 mb-8">AWTF</h1>
        <h2 className="text-2xl font-bold text-center text-gray-800 mb-2">Join Member Portal</h2>
        <p className="text-center text-gray-600 mb-6">Create your password from the invitation link</p>

        {(pageError || error) && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {pageError || error}
          </div>
        )}

        {loadingInvitation && <p className="text-center text-gray-600">Loading invitation...</p>}

        {!loadingInvitation && invitation && (
          <form onSubmit={handleSubmit} className="space-y-4">
            <ReadOnlyField label="Full Name" value={invitation.member?.full_name || ''} />
            <ReadOnlyField label="Roll Number" value={invitation.member?.roll_no || ''} />
            <ReadOnlyField label="Email" value={invitation.email || ''} />
            <ReadOnlyField label="Phone" value={invitation.phone || ''} />

            <div>
              <label className="block text-gray-700 font-semibold mb-2">Password</label>
              <input
                type="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600"
                placeholder="Create password"
                required
              />
            </div>

            <div>
              <label className="block text-gray-700 font-semibold mb-2">Confirm Password</label>
              <input
                type="password"
                value={confirmPassword}
                onChange={(event) => setConfirmPassword(event.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600"
                placeholder="Confirm password"
                required
              />
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-blue-600 text-white font-bold py-2 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {loading ? 'Creating Account...' : 'Create Account'}
            </button>
          </form>
        )}

        <p className="text-center text-gray-600 mt-6">
          Already joined?{' '}
          <Link to="/login" className="text-blue-600 hover:underline font-semibold">
            Login here
          </Link>
        </p>
      </div>
    </div>
  );
}

function ReadOnlyField({ label, value }) {
  return (
    <div>
      <label className="block text-gray-700 font-semibold mb-2">{label}</label>
      <input
        type="text"
        value={value}
        readOnly
        className="w-full px-4 py-2 border border-gray-200 bg-gray-50 rounded-lg text-gray-700"
      />
    </div>
  );
}
