import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';


import api from '../../api';
import { useAuthToken } from '../../auth/Hooks/use-auth-token';

function RegisterSummary() {
    const navigate = useNavigate();
    const location = useLocation();
    const user = location.state?.user;
    const organisation = location.state?.organisation;
    const pricing = location.state?.price;

    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitSuccess, setSubmitSuccess] = useState(false);
    const [submitError, setSubmitError] = useState<string | null>(null);

    const [responseMessageUser, setResponseMessageUser] = useState<string | null>(null);
    const [responseMessageOrganisation, setResponseMessageOrganisation] = useState<string | null>(null);

    const { getToken } = useAuthToken();

    const handleSubmit = async () => {
        setIsSubmitting(true);
        setSubmitError(null);
        setResponseMessageUser(null);
        setResponseMessageOrganisation(null);

        const payload = {
          organisation: {
            name: organisation.organisationName,
            size: organisation.organisationSize,
            country: organisation.country,
            tenant_id: organisation.tenantID
          },
          user: {
            name: user.userName,
            email: user.userEmail,
            azure_id: user.userAzureID,
            position: user.userPosition,
            phone: user.phoneNumber,
            role: "admin"
          }
        };
    
        try {
          const token = await getToken();
          const response = await api.post(
            'http://localhost:8000/api/organisation/register',
            payload,
            {
              headers: {
                Authorization: `Bearer ${token}`,
              },
            }
          );
    
        const message = response.data[0]?.message;
        setResponseMessageOrganisation(message);
    
          setSubmitSuccess(true);
        } catch (error: any) {
          const detailMessage = error?.response?.data?.detail;
          setSubmitError(detailMessage || 'Something went wrong');
        } finally {
          setIsSubmitting(false);
        };
      };

    useEffect(() => {
      if (submitSuccess) {
        setTimeout(() => {
          navigate('/');
        }, 2000); // 2-second delay
      }
    }, [submitSuccess]);
    
    return (
        <div>
          <h1>Summary of Your Registration</h1>
          <h2>Your Information</h2>
          <ul>
            <li>Name: {user.userName}</li>
            <li>Email: {user.userEmail}</li>
            <li>Your Position: {user.userPosition}</li>
            <li>Phone Number: {user.phoneNumber}</li>
          </ul>

          {/* Display Organisation Data */}
          <h2>Organisation Information</h2>
          <ul>
            <li>Tenant ID: {organisation.tenantID}</li>
            <li>Organisation Name: {organisation.organisationName}</li>
            <li>Organisation Size: {organisation.organisationSize}</li>
            <li>Country: {organisation.country}</li>
          </ul>
    
          {/* Display Pricing Data */}
          <h2>Pricing Information</h2>
          <ul>
            <li>Price: {pricing}</li>
          </ul>

            <button onClick={handleSubmit} disabled={isSubmitting}>
                {isSubmitting ? 'Submitting...' : 'Submit Registration'}
            </button>

            {submitSuccess && <div><p style={{ color: 'green' }}>{responseMessageUser}</p><p style={{ color: 'green' }}>{responseMessageOrganisation}</p></div>}
            {submitError && <p style={{ color: 'red' }}>Error: {submitError}</p>}
            
          
        </div>
      );
  }
  
  export default RegisterSummary;