'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import ReviewForm from '@/components/reviews/ReviewForm';
import Link from 'next/link';
import Image from 'next/image';

interface ProjectDetails {
  id: string;
  title: string;
  description: string;
  status: string;
  freelancer: {
    id: string;
    name: string;
    avatar: string;
  };
}

export default function ClientProjectReviewPage() {
  const params = useParams();
  const router = useRouter();
  const { data: session, status } = useSession();
  const [project, setProject] = useState<ProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string>('');

  const projectId = params.projectId as string;
  const locale = params.locale as string;

  useEffect(() => {
    if (status === 'loading') return;
    
    if (!session) {
      router.push(`/${locale}/login`);
      return;
    }

    if (projectId) {
      fetchProjectDetails();
    }
  }, [session, status, projectId, locale, router]);

  const fetchProjectDetails = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/details`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch project details');
      }

      const data = await response.json();
      
      if (data.success) {
        setProject(data.data);
        
        // Check if project is completed
        if (data.data.status !== 'COMPLETED') {
          setError('You can only review completed projects');
        }
      } else {
        setError(data.error || 'Failed to load project details');
      }
    } catch (error) {
      setError('Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  const handleReviewSubmit = (reviewData: any) => {
    // Redirect back to my projects after successful submission
    router.push(`/${locale}/client/my-projects`);
  };

  const handleCancel = () => {
    router.push(`/${locale}/client/my-projects`);
  };

  if (status === 'loading' || isLoading) {
    return (
      <section className="profile-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="loading-container">
                <div className="spinner-border text-primary" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <p>Loading project details...</p>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  if (error || !project) {
    return (
      <section className="profile-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h3>Unable to Load Project</h3>
                <p>{error || 'The project you\'re looking for doesn\'t exist or you don\'t have access to it.'}</p>
                <Link href={`/${locale}/client/my-projects`} className="btn btn-primary">
                  Back to My Projects
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="profile-wrapper">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button mb-4">
              <Link href={`/${locale}/client/my-projects`} className="back-link">
                <Image 
                  src="/assets/image/back-arrow.svg" 
                  alt="back to dashboard"
                  width={16}
                  height={16}
                />
                Back to My Projects
              </Link>
            </div>
          </div>
          
          <div className="col-12">
            <ReviewForm
              projectId={projectId}
              freelancerId={project.freelancer.id}
              onSubmit={handleReviewSubmit}
              onCancel={handleCancel}
            />
          </div>
        </div>
      </div>

      <style jsx>{`
        .loading-container, .error-container {
          text-align: center;
          padding: 60px 20px;
        }

        .loading-container .spinner-border {
          margin-bottom: 20px;
        }

        .back-link {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          color: var(--color-primary);
          text-decoration: none;
          font-weight: 500;
        }

        .back-link:hover {
          color: var(--color-primary-dark);
        }

        .error-container {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 12px;
          padding: 40px;
          margin: 20px 0;
        }

        .error-container h3 {
          color: var(--typo-secondary);
          margin-bottom: 15px;
        }

        .error-container p {
          color: var(--text-color);
          margin-bottom: 25px;
        }

        .btn {
          padding: 12px 24px;
          font-size: var(--font-small);
          font-weight: 500;
          border-radius: 8px;
          text-decoration: none;
          display: inline-block;
        }

        .btn-primary {
          background-color: var(--color-primary);
          border-color: var(--color-primary);
          color: var(--color-white);
        }

        .btn-primary:hover {
          background-color: #e55a06;
          border-color: #e55a06;
          color: var(--color-white);
        }
      `}</style>
    </section>
  );
}