'use client';

import { useParams, useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import './project-details.css';
import { useToast } from '@/components/ui/ToastContext';
import { getCountryDataByDomain } from '@/lib/countries';
import { useSession } from 'next-auth/react';

interface Project {
  id: string;
  title: string;
  description: string;
  budget: number;
  duration: number;
  currency: string;
  status: string;
  category: string;
  categoryIcon?: string;
  createdAt: string;
  clientName: string;
  clientAvatar: string;
  clientRating: number;
  clientReviewsCount: number;
  clientProjectsCount: number;
  clientMemberSince: string;
  clientLocation: string;
  bidsCount: number;
  documents: Array<{
    id: string;
    name: string;
    type: string;
    size: string;
    url: string;
  }>;
  // User bid information
  hasUserBid: boolean;
  userBidStatus: string | null;
  userBidAmount: number | null;
  userBidId: string | null;
  userBidDuration: number | null;
  userRole?: any;
}

export default function ProjectDetailsPage() {
  const params = useParams();
  const router = useRouter();
  const locale = params.locale as string;
  const projectId = params.projectId as string;
  const datacounter = getCountryDataByDomain();
  
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);

  const { showSuccess, showError } = useToast();
  const [isSubmittingReview, setIsSubmittingReview] = useState(false);
  const [reviewRating, setReviewRating] = useState<number>(0);
  const [reviewComment, setReviewComment] = useState<string>('');

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

  const fetchProjectDetails = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/details`);
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          setProject(result.data);
        } else {
          console.error('Failed to fetch project details:', result.error);
        }
      } else {
        console.error('Failed to fetch project details');
      }
    } catch (error) {
      console.error('Error fetching project details:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const renderStars = () => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      stars.push(
        <div
          key={i}
          className={`star ${i <= reviewRating ? '' : 'outlined'}`}
          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;
  };



  const getFileIcon = (type: string) => {
    switch (type.toLowerCase()) {
      case 'pdf':
        return '/assets/image/pdf.svg';
      case 'svg':
        return '/assets/image/svg.svg';
      case 'png':
      case 'jpg':
      case 'jpeg':
        return '/assets/image/png.svg';
      case 'mp4':
      case 'avi':
        return '/assets/image/vid.svg';
      default:
        return '/assets/image/pdf.svg';
    }
  };

  if (loading) {
    return (
      <div className="d-flex align-items-center justify-content-center loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="d-flex align-items-center justify-content-center loading-container">
        <div className="text-center">
          <h2>Project not found</h2>
          <p>The project you're looking for doesn't exist or has been removed.</p>
          <Link href={`/${locale}/freelancer/my-projects`} className="custom-btn primary-fill">
            Back to Projects
          </Link>
        </div>
      </div>
    );
  }


  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
        
    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();

        setTimeout(() => {
          const shareUrl = `${window.location.origin}/${locale}/freelancer/my-projects?status=completed`;
          window.location.href = shareUrl; 
        }, 2000);
      } 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);
    }
  };


  return (
    <> 
    <main className="flex-grow-1">
        <section className="project-detail-wrapper py-40">
          <div className="container">
            <div className="row">
              <div className="col-12">
                <div className="back-button">
                  <Link href={`/${locale}/freelancer/my-projects`} className="back-link">
                    <img 
                      src="/assets/image/back-arrow.svg" 
                      alt="back to dashboard"
                    />
                    Back to Projects
                  </Link>
                </div>
                <div className="page-title">
                  <h2>Project Detail</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 || '/assets/image/profile02.png'}
                        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.toFixed(1)} ({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="location"
                    />
                    {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/category/${project.categoryIcon || 'Cabinetmaking-Carpentry.svg'}`}
                          alt={project.category}
                          width={18}
                          height={18}
                        />
                        <span>{project.category}</span>
                      </li>
                      <li>
                        <img 
                          src="/assets/image/noto_fire.svg" 
                          alt="bids"
                        />
                        <span>{project.bidsCount} Bids</span>
                      </li>
                      <li>
                        <img 
                          src="/assets/image/timer.svg" 
                          alt="timer"
                        />
                        <span>Work duration- {project.duration} days</span>
                      </li>
                      <li>
                        <img 
                          src="/assets/image/document-text.svg" 
                          alt="documents"
                        />
                        <span>{project.documents.length} Documents</span>
                      </li>
                    </ul>
                    <div className="pd-bid">
                      <button 
                        type="button"
                        className="share-profile"
                        onClick={() => navigator.share && navigator.share({ 
                          title: project.title, 
                          url: window.location.href 
                        })}
                      >
                        <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>
                        Share
                      </button>
                    </div>
                  </div>
                  
                  <div className="pd-head">
                    <div className="pd-head-titile">
                      <h2>{project.title}</h2>
                      <div className="pd-time">
                        <img 
                          src="/assets/image/calendar.svg" 
                          alt="calendar"
                        />
                        {new Date(project.createdAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit'
                        })}
                      </div>
                     
                    </div>
                    <div className="pd-price">
                      {datacounter?.currencySymbol ?? ''} {project.budget.toLocaleString()}
                    </div>
                  </div>
                  
                  <div className="pd-discription">
                    <h3>About this project</h3>
                    <div dangerouslySetInnerHTML={{ __html: project.description }} />
                    
                    {project.documents && project.documents.length > 0 && (
                      <>
                        <h3>Documents ({project.documents.length})</h3>
                        <div className="document-wrapper">
                          <div className="doc-grid">
                            {project.documents.map((doc) => (
                              <div key={doc.id} className={`doc-card ${doc.type.toLowerCase()}`}>
                                <div className="doc-left">
                                  <div className="icon-box">
                                    <img 
                                      src={getFileIcon(doc.type)}
                                      alt={doc.type}
                                    />
                                  </div>
                                  <div className="doc-text">
                                    <div className="filename">{doc.name}</div>
                                    <div className="size">{doc.size}</div>
                                  </div>
                                </div>
                                <div className="download-arrow">
                                  <a href={doc.url} download>
                                    <svg width="19" height="18" viewBox="0 0 19 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <path d="M10.0294 16.9298C9.89508 17.0642 9.71123 17.149 9.4991 17.149C9.08898 17.149 8.74957 16.8096 8.74957 16.3995V-1.39949C8.74957 -1.80962 9.08898 -2.14903 9.4991 -2.14903C9.90922 -2.14903 10.2486 -1.80962 10.2486 -1.39949L10.2486 16.3995C10.2486 16.6116 10.1638 16.7955 10.0294 16.9298Z" fill="#EF7310"/>
                                      <path d="M17.2912 9.66705L10.0292 16.929C9.73933 17.2189 9.2585 17.2189 8.96859 16.929L1.7066 9.66705C1.41669 9.37714 1.41669 8.8963 1.7066 8.60639C1.99651 8.31647 2.47735 8.31647 2.76726 8.60639L9.49892 15.338L16.2306 8.60639C16.5205 8.31648 17.0013 8.31648 17.2912 8.60639C17.5811 8.8963 17.5811 9.37714 17.2912 9.66705Z" fill="#EF7310"/>
                                    </svg>
                                  </a>
                                </div>
                              </div>
                            ))}
                          </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>
            

          </div>
        </section>
      </main>

    </>
  );
}