'use client';

import { useState, useEffect, use } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { fetchProjectDetails, fetchSimilarProjects, getDocumentIcon, getDocumentIconBackground, detectFileTypeFromUrl } from '@/lib/api/project-details';
import { ProjectDetails, SimilarProject } from '@/types/project-details';
import './project-details.css';
import { getCountryDataByDomain } from '@/lib/countries';

interface ProjectDetailsPageProps {
  params: Promise<{
    locale: string;
    projectId: string;
  }>;
}

export default function ProjectDetailsPage({ params }: ProjectDetailsPageProps) {
  const { locale, projectId } = use(params);
  const router = useRouter();
  const datacounter =    getCountryDataByDomain();
  
  const [project, setProject] = useState<ProjectDetails | null>(null);
  const [similarProjects, setSimilarProjects] = useState<SimilarProject[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadProjectData = async () => {
      
      if(!datacounter?.id){
          setError('Country is missing');
          return false;
      }
      try {
        setIsLoading(true);
        setError(null);
        
        // Fetch project details
        const projectData = await fetchProjectDetails(projectId);
        setProject(projectData);

              
        // Fetch similar projects
        const similarProjectsData = await fetchSimilarProjects(undefined, 2, projectId, datacounter?.id);
        setSimilarProjects(similarProjectsData);
        
      } catch (err) {
        console.error('Error loading project details:', err);
        const errorMessage = err instanceof Error ? err.message : 'Failed to load project details';
        setError(errorMessage);
        
        // Return 404 if project not found
        if (err instanceof Error && err.message.includes('404')) {
          router.push('/404');
          return;
        }
      } finally {
        setIsLoading(false);
      }
    };

    if (projectId) {
      loadProjectData();
    }
  }, [projectId, router]);

  // Handle project sharing
  const handleShareProject = (project: Project) => {
    const projectUrl = `${window.location.origin}/${locale}/projects/${project.id}`;
    const shareText = `Check out this project: ${project.title}`;

    if (navigator.share) {
      // Use native share API if available (mobile devices)
      navigator.share({
        title: project.title,
        text: shareText,
        url: projectUrl,
      }).catch(console.error);
    } else {
      // Fallback to clipboard copy
      navigator.clipboard.writeText(projectUrl).then(() => {
        alert('Project link copied to clipboard!');
      }).catch(() => {
        // Ultimate fallback - show the URL
        prompt('Copy this link:', projectUrl);
      });
    }
  };

  // Loading state
  if (isLoading) {
    return (
      <>
        <div className="container py-5">
          <div className="row justify-content-center">
            <div className="col-md-6 text-center">
              <div className="spinner-border" role="status">
                <span className="visually-hidden">Loading...</span>
              </div>
              <h3 className="mt-3">Loading project details...</h3>
              <p>Please wait while we fetch the project information.</p>
            </div>
          </div>
        </div>
        <Footer locale={locale} />
      </>
    );
  }

  // Error state
  if (error && !project) {
    return (
      <>
        <div className="container py-5">
          <div className="row justify-content-center">
            <div className="col-md-6 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}/projects`} className="custom-btn primary-fill">
                Browse Projects
              </Link>
            </div>
          </div>
        </div>
        <Footer locale={locale} />
      </>
    );
  }

  // If we still don't have project data after loading, show error
  if (!project) {
    return (
      <>
        <div className="container py-5">
          <div className="row justify-content-center">
            <div className="col-md-6 text-center">
              <h2>Unable to Load Project</h2>
              <p>There was an issue loading the project details. Please try again.</p>
              <Link href={`/${locale}/projects`} className="custom-btn primary-fill">
                Browse Projects
              </Link>
            </div>
          </div>
        </div>
        <Footer locale={locale} />
      </>
    );
  }



  return (
    <>
      {/* Hero Section */}
      <section className="inner-hero-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-7 col-lg-8 align-self-center">
              <div className="hero-content">
                <h1>Project Detail</h1>
                <p>Learn more about this project, its needs, and how you can contribute</p>
                <nav aria-label="breadcrumb">
                  <ol className="breadcrumb">
                    <li className="breadcrumb-item">
                      <Link href={`/${locale}/projects`}>Find Projects</Link>
                    </li>
                    <li className="breadcrumb-item active" aria-current="page">
                      Project Details
                    </li>
                  </ol>
                </nav>
              </div>
            </div>
            <div className="col-12 col-md-5 col-lg-4 align-self-end">
              <div className="inner-hero-img text-center pt-1">
                <img 
                  src="/assets/image/pd-banner-img.svg" 
                  alt="pd-banner-img"
                  width={400}
                  height={300}
                />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Project Details Section */}
      <section className="project-detail-wrapper py-60 find-project-detail-wrap">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-4 col-xl-3">
              <div className="find-project-detail-siedebar">
                <div className="find-project-detail-siedebar-top">
                  <div className="find-project-detail-img">
                    <img 
                      src={project.clientAvatar || '/assets/image/profile02.png'} 
                      className="find-project-detail-update-img" 
                      alt={project.clientName}
                      width={90}
                      height={90}
                    />
                  </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"
                          width={20}
                          height={20}
                        />
                      </div>
                      {/* {project.clientRating.toFixed(1)} ({project.clientReviewsCount}+ Reviews) */}

                       {
                            (project.clientRating || project.clientReviewsCount)
                              ? `${project.clientRating.toFixed(1) || 0} (${project.clientReviewsCount || 0} Reviews)`
                              : 'No reviews yet'
                            }

                    </li>
                    <li className="pd-text">
                      <div className="icon">
                        <img 
                          src="/assets/image/briefcase.svg" 
                          alt="briefcase"
                          width={20}
                          height={20}
                        />
                      </div>
                      {project.clientProjectsCount} Projects Posted
                    </li>
                    <li className="pd-text">
                      <div className="icon">
                        <img 
                          src="/assets/image/timer-lg.svg" 
                          alt="timer-lg"
                          width={20}
                          height={20}
                        />
                      </div>
                      Member since {project.clientMemberSince}
                    </li>
                  </ul>
                </div>
                <div className="chat-btn">
                  <img 
                    src="/assets/image/location.svg" 
                    alt="location"
                    width={16}
                    height={16}
                  />
                  {project.clientLocation}
                </div>
              </div>
            </div>
            <div className="col-12 col-md-8 col-xl-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/noto_fire.svg" 
                        alt="bids count"
                        
                      />
                      <span>{project.bidsCount} Bids</span>
                    </li>
                    <li>
                      <img 
                        src="/assets/image/timer.svg" 
                        alt="deadline"
                        
                      />
                      <span>Deadline: {new Date(project.deadline).toLocaleDateString()}</span>
                    </li>
                    <li>
                      <img 
                        src="/assets/image/document-text.svg" 
                        alt="documents"
                        
                      />
                      <span>{project.documents.length.toString().padStart(2, '0')} Documents</span>
                    </li>
                  </ul>
                  <div className="pd-bid">
                    <button type="button" className="share-profile" onClick={() => handleShareProject(project)}>
                      <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
                    </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"
                        width={16}
                        height={16}
                      />
                      {new Date(project.createdAt).toLocaleDateString('en-US', { 
                        year: 'numeric', 
                        month: 'long', 
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                    <div className="d-flex">
                      {/* Only show bid buttons for freelancers */}
                      {project.userRole === 'freelancer' && (
                        <>
                          {!project.hasUserBid ? (
                            <Link href={`/${locale}/login?redirect=/${locale}/freelancer/projects/${projectId}`} className="custom-btn primary-outline">
                              <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.5 12H16.5" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                                <path d="M12.5 16V8" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                                <path d="M9.5 22H15.5C20.5 22 22.5 20 22.5 15V9C22.5 4 20.5 2 15.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22Z" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                              </svg>
                              Bid
                            </Link>
                          ) : (
                            <div className="bid-status-display">
                              <div className="d-flex align-items-center gap-2">
                                <span className={`badge badge-${project.userBidStatus?.toLowerCase() || 'pending'}`}>
                                  {project.userBidStatus === 'PENDING' && 'Bid Submitted'}
                                  {project.userBidStatus === 'ACCEPTED' && 'Bid Accepted'}
                                  {project.userBidStatus === 'REJECTED' && 'Bid Rejected'}
                                  {!project.userBidStatus && 'Bid Submitted'}
                                </span>
                                {project.userBidAmount && (
                                  <span className="text-muted">
                                    {datacounter?.currencySymbol ?? ''} {project.userBidAmount.toLocaleString()}
                                  </span>
                                )}
                              </div>
                              <Link href={`/${locale}/freelancer/projects/${projectId}`} className="custom-btn secondary-outline mt-2">
                                <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <path d="M14.5249 6.94141L19.5832 11.9997L14.5249 17.0581" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                                  <path d="M5.4165 12H19.4415" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                                </svg>
                                View Bid Details
                              </Link>
                            </div>
                          )}
                        </>
                      )}
                      {/* For clients, show project management link if they own the project */}
                      {project.userRole === 'client' && (
                        <Link href={`/${locale}/client/my-projects/${projectId}`} className="custom-btn primary-outline">
                          <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M14.5249 6.94141L19.5832 11.9997L14.5249 17.0581" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                            <path d="M5.4165 12H19.4415" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                          Manage Project
                        </Link>
                      )}
                    </div>
                  </div>
                  <div className="pd-price">
                    {/* {project.currency === 'USD' ? '$' : '€'}  */}
                    {datacounter?.currencySymbol ?? ''} {project.budget.toLocaleString()}
                  </div>
                </div>
                <div className="pd-discription">
                  <h3>About this project</h3>
                  <div dangerouslySetInnerHTML={{ __html: project.description }} />
                  
                  <>
                    <h3>Documents ({project.documents ? project.documents.length.toString().padStart(2, '0') : '00'})</h3>
                    <div className="document-wrapper">
                      {project.documents && project.documents.length > 0 ? (
                        <div className="doc-grid">
                          {project.documents.map((doc) => {
                            // Detect proper file type from URL/filename
                            const detectedType = detectFileTypeFromUrl(doc.url, doc.name);
                            const actualType = detectedType !== 'unknown' ? detectedType : doc.type;
                            
                            const iconSrc = getDocumentIcon(actualType);
                            const bgColor = getDocumentIconBackground(actualType);
                            
                            return (
                              <div key={doc.id} className={`doc-card ${actualType.toLowerCase().replace('/', '-')}`}>
                                <div className="doc-left">
                                  <div className="icon-box" style={{ backgroundColor: bgColor }}>
                                    <img 
                                      src={iconSrc}
                                      alt={actualType}
                                      width={24}
                                      height={24}
                                    />
                                  </div>
                                  <div className="doc-text">
                                    <div className="filename">{doc.name}</div>
                                    <div className="size">{doc.size}</div>
                                  </div>
                                </div>
                                <a
                                  href={doc.url}
                                  download={doc.name}
                                  className="download-arrow"
                                  style={{ border: 'none', background: 'none', cursor: 'pointer', display: 'inline-flex' }}
                                  aria-label={`Download ${doc.name}`}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                >
                                  <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 className="no-documents">
                          <div className="text-center py-4">
                            <img 
                              src="/assets/image/document-text.svg" 
                              alt="No documents"
                              width={48}
                              height={48}
                              style={{ opacity: 0.3, marginBottom: '16px' }}
                            />
                            <p style={{ color: '#6c757d', fontSize: '14px', margin: 0 }}>
                              No documents are available for this project.
                            </p>
                          </div>
                        </div>
                      )}
                    </div>
                  </>
                </div>
              </div>
              
              {similarProjects && similarProjects.length > 0 && (
                <div className="other-product">
                  <h2>You May Also Like</h2>
                  <div className="project-card-outer">
                    {similarProjects.map((similarProject) => (
                      <div key={similarProject.id} className="project-card">
                        <div>
                          <div className="work-outer">
                            <div className="work-profile">
                              <img 
                                src="/assets/image/cabinetmaking.svg" 
                                alt="category"
                              />
                              <span>{similarProject.category}</span>
                            </div>
                            <div className="work-time">
                              <img 
                                src="/assets/image/timer.svg" 
                                alt="duration"
                              />
                              <span>Work duration- {similarProject.duration} days</span>
                            </div>
                          </div>
                          <div className="project-info">
                            <div className="project-title">
                              {similarProject.title}
                            </div>
                            <div className="project-user">
                              <div className="pu-profile d-flex align-items-center">
                                <div className="pu-img">
                                  <img 
                                    src={similarProject.clientAvatar}
                                    alt={similarProject.clientName}
                                  />
                                </div>
                                <div className="pu-content">
                                  <h5>{similarProject.clientName}</h5>
                                  <div className="d-flex align-items-center gap-1">
                                    <span className="star-icon">
                                      <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"></path>
                                      </svg>
                                    </span> 
                                    {/* {similarProject.clientRating.toFixed(1)} ({similarProject.clientReviewsCount}+ Reviews) */}

                                    {
                                      (similarProject.clientRating || similarProject.clientReviewsCount)
                                        ? `${similarProject.clientRating.toFixed(1) || 0} (${similarProject.clientReviewsCount || 0} Reviews)`
                                        : 'No reviews yet'
                                      }
                                  </div>
                                </div>
                              </div>
                              <div className="pu-share">
                                <div className="view-bid">
                                  <img 
                                    src="/assets/image/noto_fire.svg" 
                                    alt="bids"
                                  />
                                  {similarProject.bidsCount} Bids
                                </div>
                                <button type="button" className="share-profile" onClick={() => handleShareProject(similarProject)}>
                                  <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>
                                </button>
                              </div>
                            </div>
                            <div className="project-dis" dangerouslySetInnerHTML={{ __html: project.description }}>
                            </div>
                          </div>
                        </div>
                        <div className="project-bid-oter">
                          <div className="project-price">
                            <img 
                              src="/assets/image/wallet.svg" 
                              alt="price"
                            />
                            {/* {similarProject.currency === 'USD' ? '$' : '€'} */}
                            {datacounter?.currencySymbol ?? ''} {similarProject.budget.toLocaleString()}
                          </div>
                          <div className="project-bid">
                            {/* Only show bid button for freelancers, view button for all */}
                            {project.userRole === 'freelancer' && (
                              <Link href={`/${locale}/projects/${similarProject.id}`} className="custom-btn primary-outline">
                                <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <path d="M8.5 12H16.5" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                  <path d="M12.5 16V8" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                  <path d="M9.5 22H15.5C20.5 22 22.5 20 22.5 15V9C22.5 4 20.5 2 15.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22Z" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                </svg>
                                Bid
                              </Link>
                            )}
                            <Link href={`/${locale}/projects/${similarProject.id}`} className="custom-btn secondary-outline">
                              <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M14.5249 6.94141L19.5832 11.9997L14.5249 17.0581" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                                <path d="M5.4165 12H19.4415" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                              </svg>
                              View
                            </Link>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
      
      <Footer locale={locale} />
    </>
  );
}
