'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { ProjectBidsResponse, BidWithFreelancer, BidFilters } from '@/types/bid';
import { getCountryDataByDomain } from '@/lib/countries';
import './view-bids.css';

export default function ViewBidsPage() {
  const { projectId } = useParams();
  const datacounter = getCountryDataByDomain();
  const [bidsData, setBidsData] = useState<ProjectBidsResponse['data'] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [filters, setFilters] = useState<BidFilters>({
    search: '',
    location: '',
    rating: '',
    sortBy: 'newest'
  });

  useEffect(() => {
    const fetchBids = async () => {
      try {
        const queryParams = new URLSearchParams();
        if (filters.search) queryParams.append('search', filters.search);
        if (filters.location) queryParams.append('location', filters.location);
        if (filters.rating) queryParams.append('rating', filters.rating);
        if (filters.sortBy) queryParams.append('sortBy', filters.sortBy);

        const response = await fetch(`/api/projects/${projectId}/bids?${queryParams}`);
        const data = await response.json();
        
        if (!response.ok) {
          throw new Error(data.error || 'Failed to fetch bids');
        }
        
        setBidsData(data.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    if (projectId) {
      fetchBids();
    }
  }, [projectId, filters]);

  const handleBidAction = async (bidId: string, action: 'accept' | 'reject') => {
    setActionLoading(bidId);
    try {
      const response = await fetch(`/api/projects/${projectId}/bids/${bidId}/${action}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || `Failed to ${action} bid`);
      }

      if (action === 'accept') {
        // Find the accepted bid details
        const acceptedBid = bidsData?.bids.find(bid => bid.id === bidId);
        const freelancerName = acceptedBid ? getFreelancerName(acceptedBid.freelancer) : 'the freelancer';
        
        // Show success message with details
        alert(
          `🎉 Bid Accepted Successfully!\n\n` +
          `Freelancer: ${freelancerName}\n` +
          `Amount: €${acceptedBid?.amount}\n` +
          `Duration: ${acceptedBid?.duration} days\n\n` +
          `The project status has been updated to "In Progress" and all other pending bids have been automatically rejected.\n\n` +
          `${freelancerName} has been notified and can now start working on your project.`
        );
      } else {
        // Show simple rejection message
        alert('Bid rejected successfully.');
      }

      // Refresh bids data
      window.location.reload();
    } catch (err) {
      alert(err instanceof Error ? err.message : `An error occurred while ${action}ing the bid`);
    } finally {
      setActionLoading(null);
    }
  };

  const handleFilterChange = (key: keyof BidFilters, value: string) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const getFreelancerName = (freelancer: BidWithFreelancer['freelancer']) => {
    if (freelancer.profile?.firstName || freelancer.profile?.lastName) {
      return `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim();
    }
    return freelancer.email;
  };

  const getFreelancerLocation = (freelancer: BidWithFreelancer['freelancer']) => {
    const city = freelancer.profile?.city;
    const country = freelancer.profile?.country?.name;
    if (city && country) return `${city}, ${country}`;
    if (country) return country;
    return 'Location not specified';
  };

  const getFreelancerPhone = (freelancer: BidWithFreelancer['freelancer']) => {
    return freelancer.profile?.phone || '33-XXXXXXXX';
  };

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

  if (error || !bidsData) {
    return (
      <section className="project-detail-wrapper py-60">
        <div className="container">
          <div className="alert alert-danger">
            {error || 'Failed to load bids'}
          </div>
        </div>
      </section>
    );
  }

  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 project details" width={20} height={20} />
                Back to Project Detail
              </Link>
            </div>
            <div className="page-title">
              <h2>Bids For &quot;{bidsData.projectTitle}&quot; ({bidsData.totalBids})</h2>
              <div className="project-filter">
                <div className="search-wrapper">
                  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19.7291 18.4686L15.035 13.7755C16.3955 12.1421 17.074 10.047 16.9292 7.92618C16.7844 5.80531 15.8275 3.82191 14.2576 2.38859C12.6877 0.955257 10.6256 0.18235 8.50037 0.23065C6.37511 0.27895 4.3503 1.14474 2.84713 2.64791C1.34396 4.15108 0.478169 6.1759 0.429869 8.30115C0.381569 10.4264 1.15448 12.4885 2.5878 14.0584C4.02113 15.6283 6.00453 16.5852 8.12539 16.73C10.2463 16.8748 12.3413 16.1963 13.9747 14.8358L18.6678 19.5299C18.7375 19.5995 18.8202 19.6548 18.9113 19.6925C19.0023 19.7302 19.0999 19.7497 19.1985 19.7497C19.297 19.7497 19.3946 19.7302 19.4856 19.6925C19.5767 19.6548 19.6594 19.5995 19.7291 19.5299C19.7988 19.4602 19.854 19.3775 19.8918 19.2864C19.9295 19.1954 19.9489 19.0978 19.9489 18.9992C19.9489 18.9007 19.9295 18.8031 19.8918 18.7121C19.854 18.621 19.7988 18.5383 19.7291 18.4686ZM1.94846 8.49924C1.94846 7.16421 2.34434 5.85917 3.08604 4.74914C3.82774 3.63911 4.88194 2.77394 6.11534 2.26305C7.34874 1.75216 8.70594 1.61849 10.0153 1.87894C11.3247 2.13939 12.5274 2.78226 13.4714 3.72627C14.4154 4.67027 15.0583 5.87301 15.3188 7.18238C15.5792 8.49175 15.4455 9.84895 14.9346 11.0823C14.4238 12.3158 13.5586 13.37 12.4486 14.1117C11.3385 14.8534 10.0335 15.2492 8.69846 15.2492C6.90885 15.2473 5.19312 14.5355 3.92768 13.27C2.66224 12.0046 1.95044 10.2888 1.94846 8.49924Z" fill="#EF7310"></path>
                  </svg>
                  <input 
                    type="text" 
                    className="form-control shadow-none p-0" 
                    placeholder="Search" 
                    value={filters.search}
                    onChange={(e) => handleFilterChange('search', e.target.value)}
                  />
                </div>
                {/* <div className="custom-select shadow-none">
                  <select 
                    value={filters.location}
                    onChange={(e) => handleFilterChange('location', e.target.value)}
                  >
                    <option value="">Location</option>
                    <option value="Switzerland">Switzerland</option>
                    <option value="France">France</option>
                    <option value="Germany">Germany</option>
                    <option value="Italy">Italy</option>
                  </select>
                </div> */}
                <div className="custom-select shadow-none">
                  <select 
                    value={filters.rating}
                    onChange={(e) => handleFilterChange('rating', e.target.value)}
                  >
                    <option value="">Rating</option>
                    <option value="5">5 Stars</option>
                    <option value="4">4+ Stars</option>
                    <option value="3">3+ Stars</option>
                  </select>
                </div>
                <div className="custom-select shadow-none">
                  <select 
                    value={filters.sortBy}
                    onChange={(e) => handleFilterChange('sortBy', e.target.value)}
                  >
                    <option value="newest">Newest</option>
                    <option value="oldest">Oldest</option>
                    <option value="price_low">Price: Low to High</option>
                    <option value="price_high">Price: High to Low</option>
                    <option value="rating">Highest Rated</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-md-12">
            <div className="viewbid-listing">
              {bidsData.bids.map((bid) => (
                <div key={bid.id} className="viewbid-card">
                  <div className="fc-detail">
                    <div className="viewbid-top">
                      <div className="fc-profile d-flex align-items-center">
                        <div className="fc-img">
                          <Image 
                            src={bid.freelancer.image || '/assets/image/user.png'} 
                            alt="Profile" 
                            width={72} 
                            height={72} 
                          />
                        </div>
                        <div className="fc-content">
                          <h5>{getFreelancerName(bid.freelancer)}</h5>
                          <div className="d-flex align-items-center">
                            <span className="star-icon me-1">
                              <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>
                            {((bid.freelancer.averageRating ?? 0) > 0) &&  (bid.freelancer._count.receivedReviews ?? 0 > 0) ?
                              (
                                <>
                                 {bid.freelancer.averageRating.toFixed(1)} ({bid.freelancer._count.receivedReviews}+ Reviews)
                                </>
                              ) : 
                              (
                                'No reviews yet'
                              ) 
                          }
                           
                          </div>
                        </div>
                      </div>
                      <div className="viewbid-profile">
                        <Link href={`/freelancer/profile/${bid.freelancer.id}`} className="custom-btn"
                          style={{ cursor: "not-allowed", pointerEvents: "none" }}
                        >
                          View Profile
                        </Link>
                      </div>
                    </div>
                    <div className="viewbid-chat">
                      <ul className="fc-contact">
                        <li className="fc-text">
                          <div className="icon">
                            <Image src="/assets/image/call.svg" alt="phone" width={14} height={14} />
                          </div>
                          {getFreelancerPhone(bid.freelancer)}
                        </li>
                        <li className="fc-text">
                          <div className="icon">
                            <Image src="/assets/image/location.svg" alt="location" width={14} height={14} />
                          </div>
                          {getFreelancerLocation(bid.freelancer)}
                        </li>
                      </ul>
                      {bid.status === 'ACCEPTED' ? (
                        <Link href={`/messages?contact=${bid.freelancer.id}&project=${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 1.75H16.5C18.6262 1.75 20.1671 2.30971 21.1787 3.32129C22.1903 4.33287 22.75 5.87378 22.75 8V13C22.75 15.1262 22.1903 16.6671 21.1787 17.6787C20.1671 18.6903 18.6262 19.25 16.5 19.25H16C15.7432 19.25 15.5412 19.3801 15.416 19.5303L15.4072 19.54L15.4004 19.5498L13.9004 21.5488C13.5216 22.051 13.0123 22.3096 12.5 22.3096C11.9877 22.3096 11.4774 22.0511 11.0986 21.5488L9.59961 19.5498C9.53781 19.4675 9.46398 19.418 9.43359 19.3984C9.39322 19.3725 9.35262 19.3515 9.31934 19.3359C9.26061 19.3084 9.17731 19.2757 9.09766 19.2598L9.0498 19.25H8.5C6.43334 19.25 4.90523 18.9633 3.88379 18.1006C2.88209 17.2546 2.25 15.7482 2.25 13V8C2.25 5.87378 2.80971 4.33287 3.82129 3.32129C4.83287 2.30971 6.37378 1.75 8.5 1.75Z" fill="#EF7310" stroke="#EF7310"></path>
                            <path d="M12.5 10.5C12.7739 10.5 13 10.7261 13 11C13 11.2771 12.7806 11.5 12.5 11.5C12.2194 11.5 12 11.2771 12 11C12 10.7261 12.2261 10.5 12.5 10.5Z" fill="#EF7310" stroke="#EF7310"></path>
                            <path d="M16.5 12C15.94 12 15.5 11.55 15.5 11C15.5 10.45 15.95 10 16.5 10C17.05 10 17.5 10.45 17.5 11C17.5 11.55 17.06 12 16.5 12Z" fill="#EF7310"></path>
                            <path d="M8.5 12C7.94 12 7.5 11.55 7.5 11C7.5 10.45 7.95 10 8.5 10C9.05 10 9.5 10.45 9.5 11C9.5 11.55 9.06 12 8.5 12Z" fill="#EF7310"></path>
                          </svg>
                          Chat
                        </Link>
                      ) : bid.status === 'PENDING' ? (
                        <Link href={`/messages?contact=${bid.freelancer.id}&project=${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 1.75H16.5C18.6262 1.75 20.1671 2.30971 21.1787 3.32129C22.1903 4.33287 22.75 5.87378 22.75 8V13C22.75 15.1262 22.1903 16.6671 21.1787 17.6787C20.1671 18.6903 18.6262 19.25 16.5 19.25H16C15.7432 19.25 15.5412 19.3801 15.416 19.5303L15.4072 19.54L15.4004 19.5498L13.9004 21.5488C13.5216 22.051 13.0123 22.3096 12.5 22.3096C11.9877 22.3096 11.4774 22.0511 11.0986 21.5488L9.59961 19.5498C9.53781 19.4675 9.46398 19.418 9.43359 19.3984C9.39322 19.3725 9.35262 19.3515 9.31934 19.3359C9.26061 19.3084 9.17731 19.2757 9.09766 19.2598L9.0498 19.25H8.5C6.43334 19.25 4.90523 18.9633 3.88379 18.1006C2.88209 17.2546 2.25 15.7482 2.25 13V8C2.25 5.87378 2.80971 4.33287 3.82129 3.32129C4.83287 2.30971 6.37378 1.75 8.5 1.75Z" fill="#EF7310" stroke="#EF7310"></path>
                            <path d="M12.5 10.5C12.7739 10.5 13 10.7261 13 11C13 11.2771 12.7806 11.5 12.5 11.5C12.2194 11.5 12 11.2771 12 11C12 10.7261 12.2261 10.5 12.5 10.5Z" fill="#EF7310" stroke="#EF7310"></path>
                            <path d="M16.5 12C15.94 12 15.5 11.55 15.5 11C15.5 10.45 15.95 10 16.5 10C17.05 10 17.5 10.45 17.5 11C17.5 11.55 17.06 12 16.5 12Z" fill="#EF7310"></path>
                            <path d="M8.5 12C7.94 12 7.5 11.55 7.5 11C7.5 10.45 7.95 10 8.5 10C9.05 10 9.5 10.45 9.5 11C9.5 11.55 9.06 12 8.5 12Z" fill="#EF7310"></path>
                          </svg>
                          Chat
                        </Link>
                      ) : (
                        <button className="custom-btn primary-outline" disabled style={{ opacity: 0.5, cursor: 'not-allowed' }}>
                          <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M8.5 1.75H16.5C18.6262 1.75 20.1671 2.30971 21.1787 3.32129C22.1903 4.33287 22.75 5.87378 22.75 8V13C22.75 15.1262 22.1903 16.6671 21.1787 17.6787C20.1671 18.6903 18.6262 19.25 16.5 19.25H16C15.7432 19.25 15.5412 19.3801 15.416 19.5303L15.4072 19.54L15.4004 19.5498L13.9004 21.5488C13.5216 22.051 13.0123 22.3096 12.5 22.3096C11.9877 22.3096 11.4774 22.0511 11.0986 21.5488L9.59961 19.5498C9.53781 19.4675 9.46398 19.418 9.43359 19.3984C9.39322 19.3725 9.35262 19.3515 9.31934 19.3359C9.26061 19.3084 9.17731 19.2757 9.09766 19.2598L9.0498 19.25H8.5C6.43334 19.25 4.90523 18.9633 3.88379 18.1006C2.88209 17.2546 2.25 15.7482 2.25 13V8C2.25 5.87378 2.80971 4.33287 3.82129 3.32129C4.83287 2.30971 6.37378 1.75 8.5 1.75Z" fill="#999" stroke="#999"></path>
                            <path d="M12.5 10.5C12.7739 10.5 13 10.7261 13 11C13 11.2771 12.7806 11.5 12.5 11.5C12.2194 11.5 12 11.2771 12 11C12 10.7261 12.2261 10.5 12.5 10.5Z" fill="#999" stroke="#999"></path>
                            <path d="M16.5 12C15.94 12 15.5 11.55 15.5 11C15.5 10.45 15.95 10 16.5 10C17.05 10 17.5 10.45 17.5 11C17.5 11.55 17.06 12 16.5 12Z" fill="#999"></path>
                            <path d="M8.5 12C7.94 12 7.5 11.55 7.5 11C7.5 10.45 7.95 10 8.5 10C9.05 10 9.5 10.45 9.5 11C9.5 11.55 9.06 12 8.5 12Z" fill="#999"></path>
                          </svg>
                          Chat Disabled
                        </button>
                      )}
                    </div>
                    <div className="fc-dis">
                      <p>{bid.proposal}</p>
                    </div>
                    <div className="divider"></div>
                  </div>
                  <div className="project-bid-oter">
                    <div className="deal-price-outer col">
                      <div className="project-price">
                        <Image src="/assets/image/wallet.svg" alt="wallet" width={20} height={20} />
                        {datacounter?.currencySymbol ?? ''} {bid.amount}
                      </div>
                      <div className="deal-price">
                        Can complete in {bid.duration} Days
                      </div>
                    </div>
                    {bid.status === 'PENDING' && (
                      <div className="project-bid">
                        <button 
                          onClick={() => handleBidAction(bid.id, 'accept')}
                          className="custom-btn primary-fill"
                          disabled={actionLoading === bid.id}
                        >
                          {actionLoading === bid.id ? 'Processing...' : 'Accept'}
                        </button>
                        <button 
                          onClick={() => handleBidAction(bid.id, 'reject')}
                          className="custom-btn red-outline"
                          disabled={actionLoading === bid.id}
                        >
                          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M6 17.8047L17.8032 6.00147" stroke="#F24747" strokeWidth="1.8" strokeLinecap="round"/>
                            <path d="M6 6L17.8032 17.8032" stroke="#F24747" strokeWidth="1.8" strokeLinecap="round"/>
                          </svg>
                        </button>
                      </div>
                    )}
                    {bid.status === 'ACCEPTED' && (
                      <div className="project-bid">
                        <span className="badge bg-success">Accepted</span>
                      </div>
                    )}
                    {bid.status === 'REJECTED' && (
                      <div className="project-bid">
                        <span className="badge bg-danger">Rejected</span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
              
              {bidsData.bids.length === 0 && (
                <div className="col-12">
                  <div className="text-center py-5">
                    <h4>No bids found</h4>
                    <p>No freelancers have submitted bids for this project yet.</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}