'use client';

import { useState, use, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import ClientSidebar from '@/components/client/ClientSidebar';
import { useToast } from '@/components/ui/ToastContext';
import { getCountryDataByDomain } from '@/lib/countries';
import './my-projects.css';

interface Project {
  id: string;
  title: string;
  description: string;
  budget: number;
  duration: number;
  status: 'DRAFT' | 'OPEN' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED';
  category: string;
  myReviewIs:any;
  createdAt: string;
  updatedAt: string;
  bidsCount: number;
  clientId: string;
  clientName: string;
  clientRating?: number;
  clientReviewCount?: number;
  freelancerId?: string;
  freelancerName?: string;
  freelancerRating?: number;
  freelancerReviewCount?: number;
  bidAmount?: number; // Deal price from accepted bid
  currency?: string; // Currency for pricing display
}

interface MyProjectsPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function MyProjectsPage({ params }: MyProjectsPageProps) {
  const { locale } = use(params);
  const datacounter = getCountryDataByDomain();

  const { data: session, status } = useSession();
  const router = useRouter();
  const { showError, showSuccess } = useToast();

  const handleShareProject = async (project: Project) => {
    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');
      }
    }
  };
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'all' | 'active' | 'completed' | 'cancelled'>('all');
  const [searchTerm, setSearchTerm] = useState('');

  const fetchProjects = useCallback(async () => {
    try {
      const response = await fetch('/api/projects/my-projects');
      if (!response.ok) {
        throw new Error('Failed to fetch projects');
      }
      const data = await response.json();
      
      if (data.success) {
        console.log(data.data.projects, 'all buid amount is here +++++++++++++++');

        setProjects(data.data.projects || []);
        // Only show success message if projects exist and this isn't the initial load
        if (data.data.projects && data.data.projects.length > 0 && !loading) {
          // showSuccess('Projects updated successfully');
        }
      } else {
        throw new Error(data.error || 'Failed to fetch projects');
      }
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
      showError(`Failed to load projects: ${errorMessage}`);
      console.error('Fetch projects error:', err);
    } finally {
      setLoading(false);
    }
  }, [showError, showSuccess, loading]);

  const renderStars = (rating: number) => {
    return (
      <>
        {/* {[1, 2, 3, 4, 5].map((star) => (
          <Image 
            key={star}
            src="/assets/image/star.svg" 
            alt="star"
            width={0}
            height={0}
            sizes="100vw"
            style={{ 
              width: '12px', 
              height: '12px',
              opacity: star <= Math.round(rating) ? 1 : 0.3
            }}
          />
        ))} */}
        <svg
            key={1}
            width="13"
            height="12"
            viewBox="0 0 13 12"
            fill={"#FB6107"}
            stroke="#FB6107"
            strokeWidth="1"
          >
            <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"/>
          </svg>
      </>
    );
  };

  const formatRating = (rating?: number, reviewCount?: number) => {
    if (!rating || !reviewCount) {
      return 'No reviews yet';
    }
    return `${rating.toFixed(1)} (${reviewCount}${reviewCount >= 25 ? '+' : ''} Review${reviewCount !== 1 ? 's' : ''})`;
  };

  useEffect(() => {
    if (status === 'loading') return;
    
    if (!session) {
      router.push(`/${locale}/login`);
      return;
    }

    fetchProjects();
  }, [session, status, locale, router, fetchProjects]);



  const getProjectUserSection = (project: Project) => {
    if (project.status === 'COMPLETED' || project.status === 'IN_PROGRESS') {
      // Show freelancer info for active/completed projects
      return (
        <div className="pu-profile d-flex align-items-center">
          <div className="pu-img">
            <Image 
              src="/assets/image/user.png" 
              alt="Profile"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '40px', height: '40px' }}
            />
          </div>
          <div className="pu-content">
            <h5>{project.freelancerName || 'Assigned Freelancer'}</h5>
            <div className="d-flex align-items-center gap-1">
              {project.freelancerRating ? renderStars(project.freelancerRating) : renderStars(0)}
              <span>{formatRating(project.freelancerRating, project.freelancerReviewCount)}</span>
            </div>
          </div>
        </div>
      );
    } else if (project.status === 'OPEN') {
      return (
        <div className="pu-profile d-flex align-items-center no-freelancer">
          <div className="pu-img">
            <Image 
              src="/assets/image/no-freelancer.svg" 
              alt="no-freelancer"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '40px', height: '40px' }}
            />
          </div>
          <div className="pu-content">
            <h5 className='no-freelancer'>No Freelancer Assigned</h5>
          </div>
        </div>
      );
    } else {
      // Show freelancer info for other statuses if available
      return (
        <div className="pu-profile d-flex align-items-center">
          <div className="pu-img">
            <Image 
              src="/assets/image/user.png" 
              alt="Profile"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '40px', height: '40px' }}
            />
          </div>
          <div className="pu-content">
            <h5>{project.freelancerName || project.clientName}</h5>
            <div className="d-flex align-items-center gap-1">
              {project.freelancerRating ? renderStars(project.freelancerRating) : renderStars(project.clientRating || 0)}
              <span>{formatRating(
                project.freelancerRating || project.clientRating, 
                project.freelancerReviewCount || project.clientReviewCount
              )}</span>
            </div>
          </div>
        </div>
      );
    }
  };

  const getProjectActions = (project: Project) => {
    if (project.status === 'CANCELLED') {
      return (
        <div className="project-bid">
          <span className="custom-btn cancelled">Cancelled</span>
          <Link 
            href={`/${locale}/client/my-projects/${project.id}`} 
            className="custom-btn secondary-outline"
          >
            <Image 
              src="/assets/image/arrow.svg" 
              alt="arrow"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '25px', height: '24px' }}
            />
          </Link>
        </div>
      );
    } else if (project.status === 'OPEN') {
      return (
        <div className="project-bid">
          <Link 
            href={`/${locale}/client/post-project/${project.id}/edit`} 
            className="custom-btn primary-outline"
          >
            Edit
          </Link>
          <Link 
            href={`/${locale}/client/my-projects/${project.id}/bids`} 
            className="custom-btn primary-outline"
          >
            View Bids
          </Link>
          <Link 
            href={`/${locale}/client/my-projects/${project.id}`} 
            className="custom-btn secondary-outline"
          >
            <Image 
              src="/assets/image/arrow.svg" 
              alt="arrow"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '25px', height: '24px' }}
            />
          </Link>
        </div>
      );
    } else if (project.status === 'COMPLETED') {
      return (
        <div className="project-bid">
            {project?.myReviewIs > 0 ? (
              <>
                <div className='d-flex align-items-center gap-1'>
                  <span className="star-icon">
                    {renderStars(project?.myReviewIs)}
                  </span> 
                  {project?.myReviewIs} Review
                </div>
              </>
              ):(
                <>
                  <Link 
                      href={`/${locale}/client/review?projectId=${project.id}&freelancerId=${project.freelancerId || 'unknown'}`} 
                      className="custom-btn primary-outline"
                    >
                      <Image
                        src="/assets/image/star.svg"
                        alt="review"
                        width={0}
                        height={0}
                        sizes="100vw"
                        style={{ width: '20px', height: '20px',filter: 'brightness(0)' }}
                      />
                      Write Review
                    </Link>
                  </>
              )}           
          <Link 
            href={`/${locale}/client/my-projects/${project.id}`} 
            className="custom-btn secondary-outline"
          >
            <Image 
              src="/assets/image/arrow.svg" 
              alt="arrow"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '25px', height: '24px' }}
            />
          </Link>
        </div>
      );
    } else {
      return (
        <div className="project-bid">
          <Link 
            href={`/${locale}/client/messages`} 
            className="custom-btn primary-outline"
          >
            <Image
              src="/assets/image/chat-icon.svg"
              alt="chat"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '25px', height: '24px' }}
            />
            Chat
          </Link>
          <Link 
            href={`/${locale}/client/my-projects/${project.id}`} 
            className="custom-btn secondary-outline"
          >
            <Image 
              src="/assets/image/arrow.svg" 
              alt="arrow"
              width={0}
              height={0}
              sizes="100vw"
              style={{ width: '25px', height: '24px' }}
            />
          </Link>
        </div>
      );
    }
  };

  const getProjectPriceSection = (project: Project) => {
    // Show Deal price whenever there's an accepted bid (bidAmount exists)
    // Otherwise show budget price
    const shouldShowDealPrice = !!project.bidAmount;

    const displayPrice = shouldShowDealPrice ? project.bidAmount : project.budget;
    // const displayCurrency = project.currency || 'CHF';
    const displayCurrency = datacounter?.currencySymbol ?? '';
    // const priceLabel = shouldShowDealPrice ? 'Deal price' : 'Budget';
    const priceLabel = shouldShowDealPrice ? project.bidAmount : '';
    
    return (
      <div className="project-price">
        <Image 
          src="/assets/image/wallet.svg" 
          alt="wallet"
          width={0}
          height={0}
          sizes="100vw"
          style={{ width: '16px', height: '16px' }}
        />
        {/* <span>{displayCurrency} {displayPrice?.toLocaleString()}</span> */}
        <span>{displayCurrency} {project.budget?.toLocaleString()}</span>
        {shouldShowDealPrice && (
          <small className="deal-price-label text-muted ms-1">({priceLabel})</small>
        )}
      </div>
    );
  };

  const filteredProjects = projects.filter(project => {
    // First filter by search term
    const matchesSearch = searchTerm === '' || 
      project.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      project.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      project.category.toLowerCase().includes(searchTerm.toLowerCase());
    
    if (!matchesSearch) return false;

    // Then filter by tab
    if (activeTab === 'all') return true;
    if (activeTab === 'active') return project.status === 'OPEN' || project.status === 'IN_PROGRESS';
    if (activeTab === 'completed') return project.status === 'COMPLETED';
    if (activeTab === 'cancelled') return project.status === 'CANCELLED';
    return true;
  });

  if (status === 'loading' || loading) {
    return (
      <div className="loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <section className="profile-wrapper create-project-wrapper py-60">
      <div className="container">
        <div className="row">
          {/* Sidebar */}
          <div className="col-12 col-md-4 col-xl-3">
            <ClientSidebar locale={locale} />
          </div>

          {/* Main Content */}
          <div className="col-12 col-md-8 col-xl-9">
            <div className="content-box my-project">
              <div className="tab-title">
                <h5>My Projects ({filteredProjects.length}{searchTerm || activeTab !== 'all' ? ` of ${projects.length}` : ''})</h5>
                <div className="project-filter">
                  <div className="search-wrapper">
                    <Image 
                      src="/assets/image/search.svg" 
                      alt="search" 
                      width={0}
                      height={0}
                      sizes="100vw"
                      style={{ width: '20px', height: '20px' }}
                    />
                    <input 
                      type="search" 
                      placeholder="Search projects..." 
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                  </div>
                  <div className="custom-select shadow-none">
                    <select 
                      value={activeTab} 
                      onChange={(e) => setActiveTab(e.target.value as 'all' | 'active' | 'completed' | 'cancelled')}
                    >
                      <option value="all">All</option>
                      <option value="active">Active</option>
                      <option value="completed">Completed</option>
                      <option value="cancelled">Cancelled</option>
                    </select>
                  </div>
                  <button 
                    onClick={() => fetchProjects()}
                    className="custom-btn secondary-outline"
                    title="Refresh projects"
                    disabled={loading}
                  >
                    {/* {loading ? (
                      <div className="spinner-border spinner-border-sm" role="status">
                        <span className="visually-hidden">Loading...</span>
                      </div>
                    ) : (
                      '↻'
                    )} */}
                    

                    {loading ? (
  <div className="spinner-border spinner-border-sm" role="status">
    <span className="visually-hidden">Loading...</span>
  </div>
) : (
  <svg
    width="20"
    height="22"
    viewBox="0 0 20 22"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
    className="cursor-pointer hover:rotate-180 transition-transform duration-300 text-[#171717]"
  >
    <path
      d="M7.10996 4.08002C7.97996 3.82002 8.93996 3.65002 9.99996 3.65002C14.79 3.65002 18.67 7.53002 18.67 12.32C18.67 17.11 14.79 20.99 9.99996 20.99C5.20996 20.99 1.32996 17.11 1.32996 12.32C1.32996 10.54 1.86996 8.88002 2.78996 7.50002"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <path
      d="M5.87 4.32L8.76 1"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <path
      d="M5.87 4.31995L9.24 6.77995"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
)}


                    
                  </button>
                  <Link 
                    href={`/${locale}/client/post-project`}
                    className="custom-btn primary-outline"
                    title="Post new project"
                  >
                    <Image 
                      src="/assets/image/add2.svg" 
                      alt="add" 
                      width={0}
                      height={0}
                      sizes="100vw"
                      style={{ width: '20px', height: '20px' }}
                    />
                  </Link>
                </div>
              </div>


              {/* Projects Grid */}
              {filteredProjects.length === 0 ? (
                <div className="no-projects">
                  <div className="text-center py-5">
                    <Image 
                      src="/assets/image/no-freelancer.svg" 
                      alt="No projects" 
                      width={0}
                      height={0}
                      sizes="100vw"
                      style={{ width: '200px', height: 'auto', marginBottom: '20px' }}
                    />
                    <h3>No Projects Found</h3>
                    <p className="text-muted mb-4">
                      {activeTab === 'all' 
                        ? "You haven't posted any projects yet. Start by posting your first project!"
                        : `No ${activeTab} projects found.`
                      }
                    </p>
                    {activeTab === 'all' && (
                      <Link 
                        href={`/${locale}/client/post-project`}
                        className="custom-btn secondary-btn"
                      >
                        Post Your First Project
                      </Link>
                    )}
                  </div>
                </div>
              ) : (
                <div className="project-card-outer">
                  {filteredProjects.map((project) => (
                    <div key={project.id} className="project-card">
                      <div>
                        <div className="work-outer">
                          <div className="work-profile">
                            <Image 
                              src="/assets/image/cabinetmaking.svg" 
                              alt={project.category}
                              width={0}
                              height={0}
                              sizes="100vw"
                              style={{ width: '24px', height: '24px' }}
                            />
                            <span>{project.category}</span>
                          </div>
                          <div className="work-time">
                            <Image 
                              src="/assets/image/timer.svg" 
                              alt="timer"
                              width={0}
                              height={0}
                              sizes="100vw"
                              style={{ width: '16px', height: '16px' }}
                            />
                            <span>Work duration- {project.duration} days</span>
                          </div>
                        </div>                      
                        <div className="project-info">
                          <div className="project-title">
                            {project.title}
                          </div>
                          <div className="project-user">
                            {getProjectUserSection(project)}
                            <div className="pu-share">
                              {project.status === 'COMPLETED' && (
                                <div className="completed">
                                  <Image 
                                    src="/assets/image/tick-circle.svg" 
                                    alt="tick-circle"
                                    width={0}
                                    height={0}
                                    sizes="100vw"
                                    style={{ width: '16px', height: '16px' }}
                                  />
                                  Completed
                                </div>
                              )}
                              {project.status === 'IN_PROGRESS' && (
                                <div className="ongoing">
                                  <Image 
                                    src="/assets/image/ongoing.svg" 
                                    alt="ongoing"
                                    width={0}
                                    height={0}
                                    sizes="100vw"
                                    style={{ width: '16px', height: '16px' }}
                                  />
                                  Ongoing
                                </div>
                              )}
                              {project.status === 'OPEN' && project.bidsCount > 0 && (
                                <div className="view-bid">
                                  <Image 
                                    src="/assets/image/noto_fire.svg" 
                                    alt="noto_fire"
                                    width={0}
                                    height={0}
                                    sizes="100vw"
                                    style={{ width: '16px', height: '16px' }}
                                  />
                                  {project.bidsCount} Bid{project.bidsCount > 1 ? 's' : ''}
                                </div>
                              )}
                              {project.status === 'CANCELLED' && (
                                <div className="cancelled">
                                  Cancelled
                                </div>
                              )}
                              <button 
                                type="button"
                                onClick={() => handleShareProject(project)}
                                className="share-profile"
                                title="Share project"
                              >
                                <Image 
                                  src="/assets/image/share.svg" 
                                  alt="share"
                                  width={0}
                                  height={0}
                                  sizes="100vw"
                                  style={{ width: '16px', height: '16px' }}
                                />
                              </button>
                            </div>
                          </div>
                          <div className="project-dis" dangerouslySetInnerHTML={{ __html: project.description.length > 100 
                              ? `${project.description.substring(0, 100)}...` 
                              : project.description }} >
                          </div>
                        </div>
                      </div>
                      
                      <div className="project-bid-oter">
                        {getProjectPriceSection(project)}
                        {getProjectActions(project)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}