'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import ProjectMilestones from '@/components/project/ProjectMilestones';
import './completed-project-details.css';

interface CompletedProjectDetails {
  id: string;
  title: string;
  description: string;
  status: 'completed';
  budget: number;
  currency: string;
  deadline: string;
  createdAt: string;
  completedAt: string;
  freelancerId: string;
  clientId: string;
  freelancerName: string;
  clientName: string;
  clientAvatar: string;
  clientRating: number;
  clientReviewsCount: number;
  clientProjectsCount: number;
  clientMemberSince: string;
  clientLocation: string;
  category: string;
  userRole: 'freelancer' | 'client';
  hasReviewed: boolean;
  existingReview?: {
    id: string;
    rating: number;
    comment: string;
    createdAt: string;
  };
  deliverables: Array<{
    id: string;
    name: string;
    description: string;
    fileUrl: string;
    deliveredAt: string;
  }>;
}

export default function CompletedProjectDetailsPage({ params }: { params: Promise<{ projectId: string }> }) {
  const { data: session, status } = useSession();
  const { showSuccess, showError } = useToast();
  
  const [project, setProject] = useState<CompletedProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [projectId, setProjectId] = useState<string>('');
  const [isSubmittingReview, setIsSubmittingReview] = useState(false);
  const [reviewRating, setReviewRating] = useState<number>(0);
  const [reviewComment, setReviewComment] = useState<string>('');

  useEffect(() => {
    const initializeParams = async () => {
      const resolvedParams = await params;
      setProjectId(resolvedParams.projectId);
    };
    
    initializeParams();
  }, [params]);

  useEffect(() => {
    if (status === 'authenticated' && projectId) {
      fetchProjectDetails();
    }
  }, [status, projectId]);

  const fetchProjectDetails = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/projects/completed/${projectId}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch completed project details');
      }
      
      const data = await response.json();
      if (data.success) {
        setProject(data.data);
        // Pre-fill review form if already reviewed
        if (data.data.existingReview) {
          setReviewRating(data.data.existingReview.rating);
          setReviewComment(data.data.existingReview.comment);
        }
      } else {
        throw new Error(data.error || 'Failed to fetch project details');
      }
    } catch (error: any) {
      console.error('Error fetching completed project details:', error);
      showError(error.message || 'Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  const handleStarClick = (rating: number) => {
    if (!project?.hasReviewed) {
      setReviewRating(rating);
    }
  };

  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!project || project.hasReviewed) return;
    
    if (reviewRating === 0) {
      showError('Please select a rating');
      return;
    }

    if (!reviewComment.trim()) {
      showError('Please write a review comment');
      return;
    }

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

      if (!response.ok) {
        throw new Error('Failed to submit review');
      }

      const data = await response.json();
      if (data.success) {
        showSuccess('Review submitted successfully!');
        // Refresh project details to show updated review status
        await fetchProjectDetails();
      } else {
        throw new Error(data.error || 'Failed to submit review');
      }
    } catch (error: any) {
      console.error('Error submitting review:', error);
      showError(error.message || 'Failed to submit review');
    } finally {
      setIsSubmittingReview(false);
    }
  };

  const formatBudget = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency
    }).format(amount);
  };

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

  const renderStars = () => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      stars.push(
        <div
          key={i}
          className={`star ${i <= reviewRating ? '' : 'outlined'} ${project?.hasReviewed ? 'disabled' : ''}`}
          onClick={() => handleStarClick(i)}
        >
          <svg viewBox="0 0 24 24">
            <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>
      );
    }
    return stars;
  };

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

  if (status === 'unauthenticated') {
    return (
      <div className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Access Denied</h2>
                <p>Please log in to view this project.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Project Not Found</h2>
                <p>The completed project you're looking for doesn't exist or you don't have access to it.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <section className="project-detail-wrapper py-40">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <a href="/en/freelancer" className="back-link">
                <img src="/assets/image/back-arrow.svg" alt="back to dashboard" />
                Back to Dashboard
              </a>
            </div>
            <div className="page-title">
              <h2>Completed Project Details</h2>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-md-12 col-lg-3">
            <div className="profile-edit-block">
              <div className="profile-edit-top">
                <div className="profile-img">
                  <img src={project.clientAvatar} className="profile-update-img" alt={project.clientName} />
                </div>
                <h5>{project.clientName}</h5>
                <ul className="pd-contact">
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/star-lg.svg" alt="star-lg" />
                    </div>
                    {project.clientRating} ({project.clientReviewsCount}+ Reviews)
                  </li>
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/briefcase.svg" alt="briefcase" />
                    </div>
                    {project.clientProjectsCount} Projects Posted
                  </li>
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/timer-lg.svg" alt="timer-lg" />
                    </div>
                    Member since {project.clientMemberSince}
                  </li>
                </ul>
              </div>
              <div className="chat-btn">
                <img src="/assets/image/location.svg" alt="" />
                {project.clientLocation}
              </div>
            </div>
          </div>
          <div className="col-md-12 col-lg-9">
            <div className="review-content">
              <div className="pd-tag">
                <ul className="pd-tag0list">
                  <li className="bg-light-sec">
                    <img src="/assets/image/cabinetmaking.svg" alt="category" />
                    <span>{project.category}</span>
                  </li>
                  <li>
                    <img src="/assets/image/calendar.svg" alt="calendar" />
                    <span>{formatDate(project.createdAt)}</span>
                  </li>
                </ul>
                <div className="pd-bid">
                  <a href="#" 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"></path>
                    </svg>
                    Share
                  </a>
                </div>
              </div>
              <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">
                      <img src="/assets/image/tick-circle.svg" alt="tick-circle" />
                      {formatDate(project.completedAt)}
                    </div>
                  </div>
                </div>
                <div className="pd-price">
                  {formatBudget(project.budget, project.currency)}
                </div>
              </div>

              <div className="pd-discription">
                <h3>About this project</h3>
                <p>{project.description}</p>

                {/* Deliverables Section */}
                {project.deliverables && project.deliverables.length > 0 && (
                  <div className="deliverables-section">
                    <h3>Project Deliverables</h3>
                    <div className="deliverables-list">
                      {project.deliverables.map((deliverable) => (
                        <div key={deliverable.id} className="deliverable-item">
                          <div className="deliverable-info">
                            <h4>{deliverable.name}</h4>
                            <p>{deliverable.description}</p>
                            <small>Delivered on {formatDate(deliverable.deliveredAt)}</small>
                          </div>
                          <div className="deliverable-action">
                            <a href={deliverable.fileUrl} className="download-btn" target="_blank" rel="noopener noreferrer">
                              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                                <path d="M7 10L12 15L17 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                                <path d="M12 15V3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                              </svg>
                              Download
                            </a>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Project Milestones */}
                {projectId && (
                  <ProjectMilestones 
                    projectId={projectId} 
                    userRole={project.userRole} 
                    projectStatus="completed" 
                  />
                )}

                {/* Review Section */}
                <div className="review-section">
                  <h3>
                    {project.hasReviewed 
                      ? `Your Review for ${project.userRole === 'client' ? 'Freelancer' : 'Client'}`
                      : `Write review for ${project.userRole === 'client' ? 'freelancer' : 'client'}`
                    }
                  </h3>
                  
                  {project.hasReviewed ? (
                    <div className="existing-review">
                      <div className="review-rating">
                        <div className="star-rating">
                          {renderStars()}
                        </div>
                        <span className="rating-text">({reviewRating}/5)</span>
                      </div>
                      <div className="review-comment">
                        <p>{reviewComment}</p>
                      </div>
                      <div className="review-date">
                        <small>Reviewed on {formatDate(project.existingReview?.createdAt || '')}</small>
                      </div>
                    </div>
                  ) : (
                    <form onSubmit={handleSubmitReview}>
                      <div className="form-wrap mb-3">
                        <label className="form-label">Add Rating</label>
                        <div className="star-rating">
                          {renderStars()}
                        </div>
                      </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={reviewComment}
                          onChange={(e) => setReviewComment(e.target.value)}
                          disabled={isSubmittingReview}
                        />
                      </div>

                      <button 
                        type="submit" 
                        className="custom-btn secondary-btn"
                        disabled={isSubmittingReview || reviewRating === 0 || !reviewComment.trim()}
                      >
                        {isSubmittingReview ? 'Submitting...' : 'Submit Review'}
                      </button>
                    </form>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}