'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import MessagesInterface from '@/components/messages/MessagesInterface';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import ErrorState from '@/components/ui/ErrorState';
import './messages.css';

export default function MessagesPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { data: session, status } = useSession();
  const contactId = searchParams.get('contactId');
  const projectId = searchParams.get('projectId');
  const projectStatus = searchParams.get('projectStatus');

  if (status === 'loading') {
    return (
      <div className="profile-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <LoadingSpinner size="lg" className="py-8" />
              <p className="text-center text-gray-600 mt-4">Loading messages...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return (
      <div className="profile-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <ErrorState 
                title="Access Denied"
                description="Please log in to view your messages."
                errorCode="401"
              />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="profile-wrapper chat-wrapper">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <button onClick={() => router.push('/freelancer/my-projects?status=recommended')} className="back-link">
                <img src="/assets/image/back-arrow.svg" alt="back to dashboard" />
                Back to Dashboard
              </button>
            </div>
            <div className="page-title">
              <h2>Message</h2>
            </div>
          </div>
          <div className="col-12">
            <MessagesInterface 
              preselectedContactId={contactId || undefined}
              projectId={projectId || undefined}
              projectStatus={projectStatus || undefined}
            />
          </div>
        </div>
      </div>
    </div>
  );
}