'use client';

import { useState, useEffect, use } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import { useToast } from '@/components/ui/ToastContext';
import StarRating from '@/components/reviews/StarRating';
import './review.css';

interface ReviewPageProps {
  params: Promise<{
    locale: string;
  }>;
}

interface Freelancer {
  id: string;
  name: string;
  profileImage: string;
  rating: number;
  reviewCount: number;
}

interface Project {
  id: string;
  title: string;
  description: string;
  budget: number;
  completedAt: string;
  category: {
    name: string;
    icon?: string;
  };
  freelancer: Freelancer;
}

export default function ReviewPage({ params }: ReviewPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const searchParams = useSearchParams();
  const projectId = searchParams.get('projectId');
  const freelancerId = searchParams.get('freelancerId');
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [project, setProject] = useState<Project | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [rating, setRating] = useState(0);
  const [reviewText, setReviewText] = useState('');
  const [isSharing, setIsSharing] = useState(false);

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

    if (!projectId || !freelancerId) {
      showError('Project ID and Freelancer ID are required');
      router.push(`/${locale}/client/my-projects`);
      return;
    }

    fetchProjectDetails();
  }, [session, status, projectId, freelancerId, locale, router, showError]);

  const fetchProjectDetails = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/review-details?freelancerId=${freelancerId}`);
      if (!response.ok) {
        throw new Error('Failed to fetch project details');
      }
      const data = await response.json();
      setProject(data.project);
    } catch (error) {
      showError('Failed to load project details');
      router.push(`/${locale}/client/my-projects`);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!rating) {
      showError('Please select a rating');
      return;
    }
    
    if (!reviewText.trim()) {
      showError('Please write a review');
      return;
    }

    setIsSubmitting(true);
    try {
      const response = await fetch('/api/reviews', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          projectId,
          freelancerId,
          rating,
          review: reviewText.trim(),
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to submit review');
      }

      showSuccess('Review submitted successfully!');
      router.push(`/${locale}/client/my-projects`);
    } catch (error: any) {
      showError(error.message || 'Failed to submit review');
    } finally {
      setIsSubmitting(false);
    }
  };


  const handleShare = async () => {
    if (!project) return;

    setIsSharing(true);
    try {
      if (navigator.share) {
        await navigator.share({
          title: project.title,
          text: `Check out this completed project: ${project.title}`,
          url: window.location.href,
        });
      } else {
        await navigator.clipboard.writeText(window.location.href);
        showSuccess('Project link copied to clipboard!');
      }
    } catch (error: any) {
      if (error.name !== 'AbortError') {
        showError('Failed to share project');
      }
    } finally {
      setIsSharing(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="error-container">
        <h2>Project not found</h2>
        <p>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="custom-btn primary-fill">
          Back to My Projects
        </Link>
      </div>
    );
  }

  return (
    <section className="project-detail-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <Link href={`/${locale}/client/my-projects`} className="back-link">
                <Image src="/assets/image/back-arrow.svg" alt="back" width={20} height={20} />
                Back to My Projects
              </Link>
            </div>
            <div className="page-title">
              <h2>Write Review</h2>
            </div>
          </div>
        </div>

        <div className="row">
          {/* Freelancer Profile Sidebar */}
          <div className="col-md-12 col-lg-3">
            <div className="profile-edit-block">
              <div className="profile-edit-top">
                <div className="profile-img">
                  <Image
                    src={project.freelancer.profileImage}
                    alt={project.freelancer.name}
                    width={90}
                    height={90}
                    className="profile-update-img"
                  />
                </div>
                <h5>{project.freelancer.name}</h5>
                <span className="profile-reviews">
                  <svg width="13" height="12" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10.2062 12L6.5 9.96162L2.79241 12L3.50213 7.67959L0.5 4.62053L4.64478 3.99059L6.5 0L8.35522 3.99059L12.5 4.62053L9.49787 7.68107L10.2062 12Z" fill="#FB6107"/>
                  </svg>
                  {project.freelancer.rating} ({project.freelancer.reviewCount}+ Reviews)
                </span>
                <div className="d-flex profile-chat justify-content-center">
                  <Link href={`/${locale}/client/message?userId=${project.freelancer.id}`} className="custom-btn secondary-light">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M8 1.75H16C18.1262 1.75 19.6671 2.30971 20.6787 3.32129C21.6903 4.33287 22.25 5.87378 22.25 8V13C22.25 15.1262 21.6903 16.6671 20.6787 17.6787C19.6671 18.6903 18.1262 19.25 16 19.25H15.5C15.2432 19.25 15.0412 19.3801 14.916 19.5303L14.9072 19.54L14.9004 19.5498L13.4004 21.5488C13.0216 22.051 12.5123 22.3096 12 22.3096C11.4877 22.3096 10.9774 22.0511 10.5986 21.5488L9.09961 19.5498C9.03781 19.4675 8.96398 19.418 8.93359 19.3984C8.89322 19.3725 8.85262 19.3515 8.81934 19.3359C8.76061 19.3084 8.67731 19.2757 8.59766 19.2598L8.5498 19.25H8C5.93334 19.25 4.40523 18.9633 3.38379 18.1006C2.38209 17.2546 1.75 15.7482 1.75 13V8C1.75 5.87378 2.30971 4.33287 3.32129 3.32129C4.33287 2.30971 5.87378 1.75 8 1.75ZM8 2.25C6.14167 2.25 4.67481 2.68261 3.67871 3.67871C2.68261 4.67481 2.25 6.14167 2.25 8V13C2.25 15.282 2.63316 16.7946 3.65723 17.6953C4.664 18.5807 6.16081 18.75 8 18.75H8.5C8.85167 18.75 9.28449 18.965 9.50098 19.251L11 21.25L11.002 21.2529C11.2454 21.5728 11.5927 21.7949 12 21.7949C12.4073 21.7949 12.7546 21.5728 12.998 21.2529L13 21.25L14.5 19.25C14.7356 18.9359 15.1074 18.75 15.5 18.75H16C17.8583 18.75 19.3252 18.3174 20.3213 17.3213C21.3174 16.3252 21.75 14.8583 21.75 13V8C21.75 6.14167 21.3174 4.67481 20.3213 3.67871C19.3252 2.68261 17.8583 2.25 16 2.25H8Z" fill="#0E9493" stroke="#0E9493"/>
                      <path d="M12 10.5C12.2739 10.5 12.5 10.7261 12.5 11C12.5 11.2771 12.2806 11.5 12 11.5C11.7194 11.5 11.5 11.2771 11.5 11C11.5 10.7261 11.7261 10.5 12 10.5Z" fill="#0E9493" stroke="#0E9493"/>
                      <path d="M16 12C15.44 12 15 11.55 15 11C15 10.45 15.45 10 16 10C16.55 10 17 10.45 17 11C17 11.55 16.56 12 16 12Z" fill="#0E9493"/>
                      <path d="M8 12C7.44 12 7 11.55 7 11C7 10.45 7.45 10 8 10C8.55 10 9 10.45 9 11C9 11.55 8.56 12 8 12Z" fill="#0E9493"/>
                    </svg>
                    Chat
                  </Link>
                </div>
              </div>
              <Link href={`/${locale}/freelancer/profile?id=${project.freelancer.id}`} className="chat-btn">
                View Freelancer Profile
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12.0251 4.81836C12.0609 4.81839 12.0915 4.83201 12.113 4.85352L17.1716 9.91113C17.1932 9.93266 17.2058 9.96415 17.2058 10C17.2057 10.0357 17.1931 10.0664 17.1716 10.0879L12.113 15.1465C12.0985 15.1609 12.0847 15.1696 12.072 15.1748C12.0587 15.1802 12.0428 15.1826 12.0251 15.1826C12.0075 15.1826 11.9916 15.1802 11.9783 15.1748C11.9655 15.1697 11.9518 15.1609 11.9373 15.1465C11.9157 15.125 11.9021 15.0935 11.9021 15.0576C11.9022 15.0219 11.9158 14.9912 11.9373 14.9697L16.907 10L16.5535 9.64648L11.9373 5.0293C11.9158 5.0078 11.9021 4.9772 11.9021 4.94141C11.9021 4.90556 11.9157 4.87504 11.9373 4.85352C11.9588 4.83199 11.9893 4.81836 12.0251 4.81836Z" fill="#EF7310" stroke="#EF7310"/>
                  <path d="M16.9417 10.625H2.91669C2.57502 10.625 2.29169 10.3417 2.29169 10C2.29169 9.65833 2.57502 9.375 2.91669 9.375H16.9417C17.2834 9.375 17.5667 9.65833 17.5667 10C17.5667 10.3417 17.2834 10.625 16.9417 10.625Z" fill="#EF7310"/>
                </svg>
              </Link>
            </div>
          </div>

          {/* Main Content */}
          <div className="col-md-12 col-lg-9">
            <div className="review-content">
              {/* Project Tags */}
              <div className="pd-tag">
                <ul className="pd-tag0list">
                  <li className="bg-light-sec">
                    <Image 
                      src={project.category.icon || "/assets/image/cabinetmaking.svg"}
                      alt="category"
                      width={20}
                      height={20}
                    />
                    <span>{project.category.name}</span>
                  </li>
                  <li>
                    <Image src="/assets/image/calendar.svg" alt="calendar" width={20} height={20} />
                    <span>{formatDate(project.completedAt)}</span>
                  </li>
                </ul>
                <div className="pd-bid">
                  <button 
                    onClick={handleShare}
                    disabled={isSharing}
                    className="share-profile"
                  >
                    <svg width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M15.5 13.8993C14.8667 13.8993 14.3 14.1494 13.8667 14.541L7.925 11.0827C7.96667 10.891 8 10.6993 8 10.4993C8 10.2993 7.96667 10.1077 7.925 9.91602L13.8 6.49102C14.25 6.90768 14.8417 7.16602 15.5 7.16602C16.8833 7.16602 18 6.04935 18 4.66602C18 3.28268 16.8833 2.16602 15.5 2.16602C14.1167 2.16602 13 3.28268 13 4.66602C13 4.86602 13.0333 5.05768 13.075 5.24935L7.2 8.67435C6.75 8.25768 6.15833 7.99935 5.5 7.99935C4.11667 7.99935 3 9.11602 3 10.4993C3 11.8827 4.11667 12.9993 5.5 12.9993C6.15833 12.9993 6.75 12.741 7.2 12.3243L13.1333 15.791C13.0917 15.966 13.0667 16.1493 13.0667 16.3327C13.0667 17.6743 14.1583 18.766 15.5 18.766C16.8417 18.766 17.9333 17.6743 17.9333 16.3327C17.9333 14.991 16.8417 13.8993 15.5 13.8993Z" fill="#EF7310"/>
                    </svg>
                    {isSharing ? 'Sharing...' : 'Share'}
                  </button>
                </div>
              </div>

              {/* Project Header */}
              <div className="pd-head">
                <div className="pd-head-titile">
                  <h2>{project.title}</h2>
                  <div className="completed-time">
                    <span>Completed on</span>
                    <div className="pd-time">
                      <Image src="/assets/image/tick-circle.svg" alt="tick-circle" width={20} height={20} />
                      {formatDate(project.completedAt)}
                    </div>
                  </div>
                </div>
                <div className="pd-price">
                  € {project.budget}
                </div>
              </div>

              {/* Project Description and Review Form */}
              <div className="pd-discription">
                <h3>About this project</h3>
                <div dangerouslySetInnerHTML={{ __html: project.description }} />

                <h3>Write review for freelancer</h3>
                <form onSubmit={handleSubmitReview}>
                  <div className="form-wrap mb-3">
                    <label className="form-label">Add Rating</label>
                    <StarRating
                      rating={rating}
                      onRatingChange={setRating}
                      size="lg"
                      showText={true}
                    />
                  </div>

                  <div className="form-wrap mb-3">
                    <label htmlFor="review" className="form-label">Write A Review</label>
                    <textarea 
                      id="review" 
                      rows={5} 
                      placeholder="Write your review here..."
                      value={reviewText}
                      onChange={(e) => setReviewText(e.target.value)}
                      required
                    />
                  </div>

                  <button 
                    type="submit" 
                    className="custom-btn secondary-btn"
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? 'Submitting...' : 'Submit'}
                  </button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}