'use client';

import { useEffect, useState, use } from 'react';
import { useRouter } from 'next/navigation';
import { useToast } from '@/components/ui/ToastContext';
import Link from 'next/link';
import Image from 'next/image';
import { ProjectDetails, ProjectDocument } from '@/types/project-details';
import { getDocumentIcon, getDocumentIconBackground, detectFileTypeFromUrl } from '@/lib/api/project-details';
import { getCountryDataByDomain } from '@/lib/countries';
import './project-details.css';

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

export default function ProjectDetailsPage({ params }: ProjectDetailsPageProps) {
  const { locale, projectId } = use(params);
  const datacounter = getCountryDataByDomain();  
  const router = useRouter();
  const { showSuccess, showError } = useToast();
  const [project, setProject] = useState<ProjectDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cancelLoading, setCancelLoading] = useState(false);
  const [completeLoading, setCompleteLoading] = useState(false);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [showCompleteModal, setShowCompleteModal] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [completionNote, setCompletionNote] = useState('');

  useEffect(() => {
    const fetchProjectDetails = async () => {
      try {
        const response = await fetch(`/api/projects/${projectId}/details`);
        const data = await response.json();
        
        if (!response.ok) {
          throw new Error(data.error || 'Failed to fetch project details');
        }
        
        console.log('🎯 Received project data:', data.data);
        console.log('📄 Documents in project:', data.data.documents);
        console.log('📊 Documents count:', data.data.documents?.length || 0);
        
        setProject(data.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    if (projectId) {
      fetchProjectDetails();
    }
  }, [projectId]);

  const handleDocumentDownload = (doc: ProjectDocument) => {
    // Create a download link
    const link = window.document.createElement('a');
    link.href = doc.url;
    link.download = doc.name;
    link.target = '_blank';
    window.document.body.appendChild(link);
    link.click();
    window.document.body.removeChild(link);
  };

  const handleCancelProject = async () => {
    if (!project) return;
    setShowCancelModal(true);
  };

  const confirmCancelProject = async () => {
    if (!cancelReason.trim()) {
      showError('Please provide a reason for cancelling this project.', 'Missing Information');
      return;
    }

    setCancelLoading(true);
    try {
      const response = await fetch(`/api/projects/${projectId}/cancel`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          reason: cancelReason.trim(),
          requestRefund: false
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || 'Failed to cancel project');
      }

      // Update project status locally
      setProject(prev => prev ? { ...prev, status: 'cancelled' } : null);

      // Show success message
      showSuccess('Project cancelled successfully.', 'Project Cancelled');

      // Close modal and reset
      setShowCancelModal(false);
      setCancelReason('');

      // Redirect to projects list after a short delay
      setTimeout(() => {
        router.push(`/${locale}/client/my-projects`);
      }, 1500);

    } catch (err) {
      showError(
        err instanceof Error ? err.message : 'An error occurred while cancelling the project',
        'Cancellation Failed'
      );
    } finally {
      setCancelLoading(false);
    }
  };

  const handleCompleteProject = async () => {
    if (!project) return;
    setShowCompleteModal(true);
  };

  const confirmCompleteProject = async () => {
    setCompleteLoading(true);
    try {
      const response = await fetch(`/api/projects/${projectId}/complete-by-client`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          confirmationNote: completionNote.trim() || undefined
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || 'Failed to complete project');
      }

      // Update project status locally
      setProject(prev => prev ? { ...prev, status: 'completed' } : null);
      
      // Show success message
      showSuccess('Project marked as complete successfully! You will now be redirected to leave a review.', 'Project Completed');

      // Close modal and reset
      setShowCompleteModal(false);
      setCompletionNote('');

      // Redirect to review page
      setTimeout(() => {
        router.push(`/${locale}/client/review/${projectId}`);
      }, 1500);

    } catch (err) {
      showError(
        err instanceof Error ? err.message : 'An error occurred while completing the project',
        'Completion Failed'
      );
    } finally {
      setCompleteLoading(false);
    }
  };


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

  if (error || !project) {
    return (
      <div className="container py-60">
        <div className="alert alert-danger">
          {error || 'Project not found'}
        </div>
      </div>
    );
  }

    const handleShareProject = async (project: any) => {
    const shareUrl = `${window.location.origin}/${locale}/projects/${project.id}`;
    const shareData = {
      title: project.title,
      text: `Check out this project: ${project.title}`,
      url: shareUrl
    };

    try {
      // Try native Web Share API first (mobile)
      if (navigator.share) {
        await navigator.share(shareData);
        showSuccess('Project shared successfully!');
      } else {
        // Fallback to clipboard
        await navigator.clipboard.writeText(shareUrl);
        showSuccess('Project link copied to clipboard!');
      }
    } catch (err) {
      // Final fallback - create temporary textarea
      try {
        const textArea = document.createElement('textarea');
        textArea.value = shareUrl;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showSuccess('Project link copied to clipboard!');
      } catch (fallbackErr) {
        showError('Failed to share project');
      }
    }
  };

  return (
    <section className="project-detail-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <Link href="/client/my-projects" className="back-link">
                <Image src="/assets/image/back-arrow.svg" alt="back to dashboard" width={20} height={20} />
                Back to Dashboard
              </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="project-detail-sidebar">
              <div className="profile-edit-top">
                {project.userRole === 'client' && (
                  <>
                    {/* Show freelancer profile for client if project has accepted bid */}
                    {project.freelancerId ? (
                      <div className="pu-profile d-flex align-items-center">
                        <div className="pu-img">
                          <Image 
                            src={project.freelancerAvatar || '/assets/image/user.png'} 
                            alt="Freelancer Profile" 
                            width={40} 
                            height={40} 
                          />
                        </div>
                        <div className="pu-content">
                          <h5>{project.freelancerName}</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> 
                            {/* {project.freelancerRating || 0} ({project.freelancerReviewsCount || 0}+ Reviews) */}

                            {
                            (project.freelancerRating || project.freelancerReviewsCount)
                              ? `${project.freelancerRating || 0} (${project.freelancerReviewsCount || 0} Reviews)`
                              : 'No reviews yet'
                            }

                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="pu-profile d-flex align-items-center project-detail-freelancer">
                        <div className="pu-img">
                          <Image src="/assets/image/user.png" alt="No Freelancer" width={40} height={40} />
                        </div>
                        <div className="pu-content">
                          <h5>No freelancer assigned</h5>
                          <div className="text-muted">Project is still open for bids</div>
                        </div>
                      </div>
                    )}
                  </>
                )}
                {project.userRole === 'freelancer' && (
                  <>
                    {/* Show client profile for freelancer */}
                    <div className="pu-profile d-flex align-items-center">
                      <div className="pu-img">
                        <Image 
                          src={project.clientAvatar || '/assets/image/user.png'} 
                          alt="Client Profile" 
                          width={40} 
                          height={40} 
                        />
                      </div>
                      <div className="pu-content">
                        <h5>{project.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> 
                           {
                            (project.clientRating || project.clientReviewsCount)
                              ? `${project.clientRating || 0} (${project.clientReviewsCount || 0} Reviews)`
                              : 'No reviews yet'
                          } 
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>
              {project.userRole === 'client' && (
                <>
                  {/* Show different content based on project status */}
                  {project.status === 'ongoing' && project.freelancerId ? (
                    <>
                      <Link href={`/messages?projectId=${projectId}&contactId=${project.freelancerId}&projectStatus=${project.status}`} className="chat-btn mb-2">
                        Chat with Freelancer
                        <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>
                      <Link href={`/client/freelancer/${project.freelancerId}`} 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>
                    </>
                  ) : project.status === 'completed' || project.status === 'cancelled' ? (
                    <>
                      <div className="archived-project-info">
                        <p style={{ color: '#6b7280', fontSize: '14px', margin: '10px 0' }}>
                          This project has been {project.status}. 
                          {project.status === 'completed' && (
                            <><br />You can <Link href={`/client/review/${projectId}`} style={{ color: '#EF7310' }}>leave a review</Link> for the freelancer.</>
                          )}
                        </p>
                      </div>
                      <Link href={`/client/freelancer/${project.freelancerId}`} 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>
                    </>
                  ) : (
                    
                     (project?.bidsCount ?? 0) > 0 ?(
                        <Link href={`/client/my-projects/${projectId}/bids`} className="chat-btn">
                          View All Bids ({project.bidsCount || 0})
                          <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 className="chat-btn">
                          0 Bids                        
                        </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">
                    <Image src={'/assets/image/category/' + project.categoryIcon || 'cabinetmaking.svg'} alt={project.category} width={20} height={20} />
                    <span>{project.category}</span>
                  </li>
                  <li>
                    <Image src="/assets/image/noto_fire.svg" alt="bids" width={20} height={20} />
                    <span>{project.bidsCount || 0} Bids</span>
                  </li>
                  <li>
                    <Image src="/assets/image/timer.svg" alt="timer" width={20} height={20} />
                    <span>Work duration- {project.duration} days</span>
                  </li>
                  <li>
                    <Image src="/assets/image/document-text.svg" alt="documents" width={20} height={20} />
                    <span>{project.documents?.length || 0} Documents</span>
                  </li>
                </ul>
                <div className="pd-bid">
                  <a href="#"   onClick={() => handleShareProject(project)} 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="pd-time">
                    <Image 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>
                  
                  {/* Show Cancel Project, Complete Project buttons and Deal Price for accepted projects */}
                  {project.status === 'ongoing' && project.freelancerId && project.freelancerName && project.userRole === 'client' && (
                    <div className="d-flex deal-price-outer gap-3 mt-3">
                      <div className="d-flex gap-2">
                        <button 
                          onClick={handleCompleteProject}
                          className="custom-btn secondary-btn"
                          disabled={completeLoading}
                        >
                          {completeLoading ? 'Completing...' : 'Complete Project'}
                        </button>
                        <button 
                          onClick={handleCancelProject}
                          className="custom-btn red-outline"
                          disabled={cancelLoading}
                        >
                          {cancelLoading ? 'Cancelling...' : 'Cancel Project'}
                        </button>
                      </div>
                      <div className="deal-price">
                        {/* {project.currency} {project.bidAmount || project.budget} */}
                        {datacounter?.currencySymbol ?? ''} {project.bidAmount || project.budget}
                        <span>Deal price</span>
                      </div>
                    </div>
                  )}
                </div>
                <div className="pd-price">
                  {/* {project.currency} {project.budget} */}
                  {datacounter?.currencySymbol ?? ''} {project.budget}
                </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) => {
                          // 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 }}>
                                  <Image 
                                    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>
                              <div 
                                className="download-arrow" 
                                onClick={() => handleDocumentDownload(doc)}
                                style={{ cursor: 'pointer' }}
                                title={`Download ${doc.name}`}
                              >
                                <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>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}