'use client';

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

interface ProjectDetails {
  id: string;
  title: string;
  description: string;
  budget: number;
  endDate: string;
  client: {
    id: string;
    name: string;
    avatar: string;
    rating: number;
    reviewsCount: number;
    joinedDate: string;
  };
}

interface ReviewFormData {
  rating: number;
  comment: string;
}

export default function FreelancerReviewPage() {
  const params = useParams();
  const router = useRouter();
  const { data: session } = useSession();
  const [project, setProject] = useState<ProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState<ReviewFormData>({
    rating: 0,
    comment: ''
  });
  const [error, setError] = useState<string>('');
  const [success, setSuccess] = useState<string>('');

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

  useEffect(() => {
    if (projectId) {
      fetchProjectDetails();
    }
  }, [projectId]);

  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);
      } else {
        setError(data.error || 'Failed to load project details');
      }
    } catch (error) {
      setError('Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  const handleStarClick = (rating: number) => {
    setFormData(prev => ({ ...prev, rating }));
  };

  const handleCommentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setFormData(prev => ({ ...prev, comment: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (formData.rating === 0) {
      setError('Please select a rating');
      return;
    }

    if (formData.comment.trim().length < 10) {
      setError('Please write at least 10 characters for your review');
      return;
    }

    setIsSubmitting(true);
    setError('');

    try {
      const response = await fetch(`/api/projects/${projectId}/review`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          rating: formData.rating,
          comment: formData.comment.trim(),
          revieweeRole: 'client'
        })
      });

      const data = await response.json();

      if (data.success) {
        setSuccess('Review submitted successfully!');
        setTimeout(() => {
          router.push(`/${locale}/freelancer/my-projects`);
        }, 2000);
      } else {
        setError(data.error || 'Failed to submit review');
      }
    } catch (error) {
      setError('Failed to submit review. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const renderStars = (rating: number, interactive: boolean = false) => {
    return (
      <div className={`star-rating ${interactive ? 'interactive' : ''}`}>
        {[1, 2, 3, 4, 5].map((star) => (
          <svg
            key={star}
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill={star <= rating ? "#FB6107" : "none"}
            stroke="#FB6107"
            strokeWidth="1"
            style={{ cursor: interactive ? 'pointer' : 'default' }}
            onClick={interactive ? () => handleStarClick(star) : undefined}
          >
            <path d="M12 .587l3.668 7.571 8.332 1.151-6.064 5.845 1.528 8.263L12 18.896l-7.464 4.521 1.528-8.263L.001 9.309l8.332-1.151z"/>
          </svg>
        ))}
      </div>
    );
  };

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

  return (
    <section className="profile-wrapper review-wrapper">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <Link href={`/${locale}/freelancer/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 className="profile-title">
              <h3>Project Review</h3>
            </div>
          </div>
          
          <div className="col-12">
            <div className="profile-head review-wrapper">
              <div className="row">
                {/* Client Profile Section */}
                <div className="col-md-12 col-lg-3">
                  <div className="profile-edit-block">
                    <div className="customer-title">
                      Client Profile
                    </div>
                    <div className="profile-img">
                      <Image 
                        src={project.client.avatar} 
                        className="profile-update-img" 
                        alt="client avatar"
                        width={80}
                        height={80}
                      />
                    </div>
                    <h5>{project.client.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.client.rating} ({project.client.reviewsCount}+ Reviews)
                    </span>
                    <div className="created-date">
                      <svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M17.7916 11.0417C17.7916 15.0667 14.5249 18.3333 10.4999 18.3333C6.47492 18.3333 3.20825 15.0667 3.20825 11.0417C3.20825 7.01667 6.47492 3.75 10.4999 3.75C14.5249 3.75 17.7916 7.01667 17.7916 11.0417Z" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M10.5 6.66675V10.8334" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M8 1.66675H13" stroke="#0A0C00" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                      Joined: {new Date(project.client.joinedDate).toLocaleDateString()}
                    </div>
                    <button className="btn profile-btn">
                      View Profile
                    </button>
                    <div className="chat-btn">
                      <Link href={`/${locale}/freelancer/messages`} className="button-primary">
                        <Image 
                          src="/assets/image/message-chat.svg" 
                          alt="chat"
                          width={16}
                          height={16}
                        />
                        Chat
                      </Link>
                    </div>
                  </div>
                </div>

                {/* Project Details and Review Form */}
                <div className="col-md-12 col-lg-9">
                  <div className="review-content">
                    <div className="title">
                      <h5>{project.title}</h5>
                    </div>
                    
                    <div className="day-price-box">
                      <div className="inner-dpbox">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M7.22656 11.9415C7.22656 13.0165 8.05156 13.8831 9.07656 13.8831H11.1682C12.0599 13.8831 12.7849 13.1248 12.7849 12.1915C12.7849 11.1748 12.3432 10.8165 11.6849 10.5831L8.32656 9.41646C7.66823 9.18312 7.22656 8.82479 7.22656 7.80812C7.22656 6.87479 7.95156 6.11646 8.84323 6.11646H10.9349C11.9599 6.11646 12.7849 6.98312 12.7849 8.05812" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M10 5V15" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M10.0001 18.3334C14.6025 18.3334 18.3334 14.6025 18.3334 10.0001C18.3334 5.39771 14.6025 1.66675 10.0001 1.66675C5.39771 1.66675 1.66675 5.39771 1.66675 10.0001C1.66675 14.6025 5.39771 18.3334 10.0001 18.3334Z" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        ${project.budget.toLocaleString()}
                      </div>
                      <div className="inner-dpbox">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M17.7916 11.0417C17.7916 15.0667 14.5249 18.3333 10.4999 18.3333C6.47492 18.3333 3.20825 15.0667 3.20825 11.0417C3.20825 7.01667 6.47492 3.75 10.4999 3.75C14.5249 3.75 17.7916 7.01667 17.7916 11.0417Z" stroke="#0A0C00" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        Completed: {new Date(project.endDate).toLocaleDateString()}
                      </div>
                    </div>

                    <div className="review-discription">
                      <p>{project.description}</p>
                    </div>

                    {/* Review Form */}
                    <div className="write-customer">
                      <h5>Write Review for Client</h5>
                      <p>Share your experience working with this client.</p>

                      {error && (
                        <div className="alert alert-danger">
                          {error}
                        </div>
                      )}

                      {success && (
                        <div className="alert alert-success">
                          {success}
                        </div>
                      )}

                      <div className="review-form">
                        <form onSubmit={handleSubmit}>
                          <div className="label-title">
                            Add Rating
                          </div>
                          <div className="add-rating">
                            {renderStars(formData.rating, true)}
                          </div>
                          
                          <div className="review-text-box">
                            <div className="mt-4">
                              <label htmlFor="writereview" className="form-label">
                                Write A Review
                              </label>
                              <textarea 
                                className="form-control" 
                                id="writereview" 
                                rows={8}
                                value={formData.comment}
                                onChange={handleCommentChange}
                                placeholder="Share your experience working with this client..."
                                disabled={isSubmitting}
                              />
                            </div>
                          </div>
                          
                          <div className="text-end">
                            <button 
                              type="submit" 
                              className="button-secondary"
                              disabled={isSubmitting}
                            >
                              {isSubmitting ? 'Submitting...' : 'Submit Review'}
                            </button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

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

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

        .star-rating {
          display: flex;
          gap: 5px;
        }

        .star-rating.interactive svg {
          transition: all 0.3s ease;
        }

        .star-rating.interactive svg:hover {
          transform: scale(1.1);
        }

        .add-rating {
          margin-bottom: 20px;
        }

        .alert {
          padding: 12px 16px;
          border-radius: 8px;
          margin-bottom: 20px;
        }

        .alert-danger {
          background-color: #f8d7da;
          border: 1px solid #f5c6cb;
          color: #721c24;
        }

        .alert-success {
          background-color: #d1edff;
          border: 1px solid #bee5eb;
          color: #0c5460;
        }

        .review-form textarea {
          min-height: 120px;
          resize: vertical;
        }

        .button-secondary:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

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

        .back-link:hover {
          color: var(--color-primary-dark);
        }
      `}</style>
    </section>
  );
}