'use client';

import { useParams, useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import BidModal from '@/components/freelancer/BidModal';
import SimpleChat from '@/components/chat/SimpleChat';
import { BidFormData } from '@/types/bid';
import './project-details.css';
import { useToast } from '@/components/ui/ToastContext';
import { getCountryDataByDomain } from '@/lib/countries';
import { useSearchParams } from 'next/navigation';

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;
}

export default function ProjectDetailsPage() {
  const params = useParams();
  const router = useRouter();
  const searchParams = useSearchParams();
  const createBid = searchParams.get('create-bid');
  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 { showError, showSuccess } = useToast();
  const [showBidModal, setShowBidModal] = useState(false);
  const [userBidId, setUserBidId] = useState<string | null>(null);
  const [isUpdateBid, setIsUpdateBid] = useState(false);
  const [isWithdrawing, setIsWithdrawing] = useState(false);

  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);
          
          // bid model is update
          if(createBid && !result.data.hasUserBid){
            setShowBidModal(true)
          }
          // if(result.data.userBidStatus === 'PENDING'){
          //     handleBidUpdate();
          // }        
          // bid model is update

        } 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 handleBidUpdate = () => {
    if (project?.hasUserBid && project?.userBidId) {
      setIsUpdateBid(true);
      setShowBidModal(true);
    }
  };

  const handleWithdrawBid = async () => {
    if (!project?.userBidId) return;
    
    setIsWithdrawing(true);
    
    try {
      const response = await fetch(`/api/projects/${projectId}/bid/${project.userBidId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'x-toast-controlled': 'true',
        },
      });

      if (!response.ok) {
        let errorMessage = 'Failed to withdraw bid';
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorData.error || errorMessage;
        } catch {
          // If we can't parse the error response, use the default message
        }
        showError(errorMessage, 'Withdrawal Failed');
        return;
      }

      const result = await response.json();
      
      // Refresh project data
      fetchProjectDetails();
      
      const successMessage = result.message || 'Bid withdrawn successfully.';
      showSuccess(successMessage, 'Bid Withdrawn');
      
    } catch (error: any) {
      console.error('Error withdrawing bid:', error);
      const errorMessage = error?.message || 'An unexpected error occurred while withdrawing your bid. Please try again.';
      const errorTitle = (error instanceof TypeError && String(error.message || '').includes('fetch')) ? 'Network Error' : 'Withdrawal Failed';
      showError(errorMessage, errorTitle);
    } finally {
      setIsWithdrawing(false);
    }
  };

  const handleBidSubmit = async (bidData: BidFormData) => {
    try {
      const url = isUpdateBid && project?.userBidId 
        ? `/api/projects/${projectId}/bid/${project.userBidId}`
        : `/api/projects/${projectId}/bid`;
      
      const method = isUpdateBid ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          amount: bidData.price,
          deliveryTime: bidData.days,
          proposal: bidData.description,
          ...(isUpdateBid ? {} : { projectId })
        }),
      });

      if (response.ok) {
        const result = await response.json();
        // Show success message
        const successMessage = isUpdateBid 
          ? 'Bid updated successfully!'
          : 'Bid submitted successfully! Chat has been initialized.';
        showSuccess(successMessage);
        // Close the modal
        setShowBidModal(false);
        setIsUpdateBid(false);
        // Store the bid ID for chat
        if (result.bid?.id || result.data?.bid?.id) {
          setUserBidId(result.bid?.id || result.data?.bid?.id);
        }
        // Refresh project data to get updated bid count and status
        fetchProjectDetails();
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || `Failed to ${isUpdateBid ? 'update' : 'submit'} bid`);
      }
    } catch (error) {
      console.error(`Error ${isUpdateBid ? 'updating' : 'submitting'} bid:`, error);
      showError(`Failed to ${isUpdateBid ? 'update' : 'submit'} bid. Please try again.`);
    }
  };

  const handleCloseModal = () => {
    setShowBidModal(false);
    setIsUpdateBid(false);
  };

  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>
    );
  }

  return (
    <> 
    <main className="flex-grow-1">
        <section className="project-detail-wrapper py-40 freelancer-project-detail-wrap">
          <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-12 col-md-4 col-xl-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-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/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 className="d-flex flex-column gap-3">
                        {!project.hasUserBid ? (
                          <button 
                            type="button"
                            className="custom-btn primary-outline"
                            onClick={() => setShowBidModal(true)}
                          >
                            <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
                          </button>
                        ) : (
                          <div className="bid-management-section">
                            <div className="bid-status-display mb-3">
                              <div className="bid-info">
                                <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 && (
                                  <div className="bid-details">
                                    <strong>{datacounter?.currencySymbol ?? ''} {project.userBidAmount.toLocaleString()}</strong>
                                    {project.userBidDuration && (
                                      <span className="text-muted"> • {project.userBidDuration} days</span>
                                    )}
                                  </div>
                                )}
                              </div>
                            </div>
                            
                            {project.userBidStatus === 'PENDING' && (
                              <div className="bid-actions d-flex gap-2">
                                <button 
                                  type="button"
                                  className="custom-btn primary-outline"
                                  onClick={handleBidUpdate}
                                >
                                  <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M11.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22H15.5C20.5 22 22.5 20 22.5 15V13" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                    <path d="M16.54 3.02L8.66 10.9C8.35 11.21 8.04 11.82 7.98 12.25L7.52 15.24C7.36 16.26 8.12 17.02 9.14 16.86L12.13 16.4C12.56 16.34 13.17 16.03 13.48 15.72L21.36 7.84C22.6 6.6 23.18 5.13 21.36 3.31C19.54 1.49 18.07 2.07 16.54 3.02Z" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                                    <path d="M15.41 4.15C16.01 6.54 17.96 8.49 20.35 9.09" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                                  </svg>
                                  Update Bid
                                </button>
                                <button 
                                  type="button"
                                  className="custom-btn secondary-outline"
                                  onClick={handleWithdrawBid}
                                  disabled={isWithdrawing}
                                >
                                  {isWithdrawing ? (
                                    <>
                                      <div className="spinner-border spinner-border-sm" role="status" style={{width: '16px', height: '16px'}}>
                                        <span className="visually-hidden">Loading...</span>
                                      </div>
                                      Withdrawing...
                                    </>
                                  ) : (
                                    <>
                                      <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M21.5 7.81V16.09C21.5 19.62 19.62 21.5 16.09 21.5H8.91C5.38 21.5 3.5 19.62 3.5 16.09V7.81C3.5 4.67 5.13 2.84 8.09 2.5H16.91C19.87 2.84 21.5 4.67 21.5 7.81Z" stroke="#F24747" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                        <path d="M15.5 9L9.5 15" stroke="#F24747" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                        <path d="M15.5 15L9.5 9" stroke="#F24747" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                      </svg>
                                      Withdraw
                                    </>
                                  )}
                                </button>
                              </div>
                            )}
                            
                            <div className="chat-info mt-2">
                              <small className="text-muted">Chat available below</small>
                            </div>
                          </div>
                        )}
                      </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>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>

      <BidModal
        isOpen={showBidModal}
        onClose={handleCloseModal}
        onSubmit={handleBidSubmit}
        projectTitle={project?.title}
        isUpdateMode={isUpdateBid}
        initialBidData={isUpdateBid && project?.userBidAmount && project?.userBidDuration ? {
          amount: project.userBidAmount.toString(),
          deliveryTime: project.userBidDuration.toString(),
          proposal: ''
        } : undefined}
      />

    </>
  );
}