'use client';

import { useState, useEffect, use } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import { useToast } from '@/components/ui/ToastContext';
import SimpleChat from '@/components/chat/SimpleChat';
import './view-bids.css';

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

interface Freelancer {
  id: string;
  name: string;
  profileImage: string;
  rating: number;
  reviewCount: number;
  skills: string[];
  bio: string;
}

interface Bid {
  id: string;
  amount: number;
  proposal: string;
  deliveryTime: number;
  status: string;
  createdAt: string;
  updatedAt: string;
  freelancer: Freelancer;
}

interface Project {
  id: string;
  title: string;
  status: string;
}

interface BidsData {
  bids: Bid[];
  project: Project;
  pagination: {
    currentPage: number;
    totalPages: number;
    totalItems: number;
    itemsPerPage: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };
}

export default function ViewBidsPage({ params }: ViewBidsPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const searchParams = useSearchParams();
  const projectId = searchParams.get('projectId');
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [bidsData, setBidsData] = useState<BidsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [selectedBidId, setSelectedBidId] = useState<string | null>(null);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState('');
  const [locationFilter, setLocationFilter] = useState('');
  const [ratingFilter, setRatingFilter] = useState('');
  const [sortBy, setSortBy] = useState('newest');
  const [statusFilter, setStatusFilter] = useState('all');
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1);

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

    if (!projectId) {
      showError('Project ID is required');
      router.push(`/${locale}/client/my-projects`);
      return;
    }

    fetchBids();
  }, [session, status, projectId, locale, router, showError, currentPage, searchTerm, locationFilter, ratingFilter, sortBy, statusFilter]);

  const fetchBids = async () => {
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: '10',
        ...(statusFilter !== 'all' && { status: statusFilter }),
        ...(searchTerm && { search: searchTerm }),
        ...(locationFilter && { location: locationFilter }),
        ...(ratingFilter && { rating: ratingFilter }),
        ...(sortBy && { sort: sortBy })
      });

      const response = await fetch(`/api/projects/${projectId}/bids?${params.toString()}`);
      if (!response.ok) {
        throw new Error('Failed to fetch bids');
      }
      const data = await response.json();
      setBidsData(data.data);
    } catch (error) {
      console.error('Error fetching bids:', error);
      showError('Failed to load bids');
      if (currentPage === 1) {
        router.push(`/${locale}/client/my-projects`);
      }
    } finally {
      setIsLoading(false);
    }
  };

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

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

      showSuccess(`Bid ${action}ed successfully!`);
      
      // If a bid was accepted, redirect to project details
      if (action === 'accept') {
        router.push(`/${locale}/client/project-details?id=${projectId}`);
      } else {
        // Refresh bids data
        fetchBids();
      }
    } catch (error: any) {
      console.error(`Error ${action}ing bid:`, error);
      showError(error.message || `Failed to ${action} bid`);
    } finally {
      setActionLoading(null);
    }
  };

  const getStatusBadgeClass = (status: string) => {
    switch (status.toLowerCase()) {
      case 'pending': return 'badge-pending';
      case 'accepted': return 'badge-accepted';
      case 'rejected': return 'badge-rejected';
      default: return 'badge-pending';
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const renderStars = (rating: number) => {
    return (
      <div className="star-display">
        {[1, 2, 3, 4, 5].map((star) => (
          <svg
            key={star}
            width="13"
            height="12"
            viewBox="0 0 13 12"
            fill={star <= rating ? "#FB6107" : "none"}
            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>
        ))}
      </div>
    );
  };

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

  if (!bidsData) {
    return (
      <div className="error-container">
        <h2>Project not found</h2>
        <p>The project you're looking for doesn't exist or you don't have access to it.</p>
        <Link href={`/${locale}/client/my-projects`} className="custom-btn primary-fill">
          Back to My Projects
        </Link>
      </div>
    );
  }

  return (
    <section className="project-detail-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <Link href={`/${locale}/client/my-projects/${projectId}`} className="back-link">
                <Image src="/assets/image/back-arrow.svg" alt="back to project detail" width={20} height={20} />
                Back to Project Detail
              </Link>
            </div>
            <div className="page-title">
              <h2>Bids For "{bidsData.project.title}"</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"/>
                  </svg>
                  <input
                    type="text"
                    className="form-control shadow-none p-0"
                    placeholder="Search"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
                <div className="custom-select shadow-none">
                  <select value={locationFilter} onChange={(e) => setLocationFilter(e.target.value)}>
                    <option value="">Location</option>
                    <option value="India">India</option>
                    <option value="USA">USA</option>
                    <option value="UK">UK</option>
                    <option value="Germany">Germany</option>
                    <option value="Switzerland">Switzerland</option>
                  </select>
                </div>
                <div className="custom-select shadow-none">
                  <select value={ratingFilter} onChange={(e) => setRatingFilter(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={sortBy} onChange={(e) => setSortBy(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 className="custom-select shadow-none">
                  <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
                    <option value="all">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="accepted">Accepted</option>
                    <option value="rejected">Rejected</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="row">
          <div className="col-md-12">
            {bidsData.bids.length === 0 ? (
              <div className="no-bids-container">
                <div className="no-bids-content">
                  <Image src="/assets/image/no-freelancer.svg" alt="No bids" width={200} height={150} />
                  <h3>No Bids Found</h3>
                  <p>There are no bids for this project matching your current filters.</p>
                  {searchTerm || locationFilter || ratingFilter || statusFilter !== 'all' ? (
                    <button 
                      onClick={() => {
                        setSearchTerm('');
                        setLocationFilter('');
                        setRatingFilter('');
                        setStatusFilter('all');
                      }}
                      className="custom-btn primary-fill"
                    >
                      Clear Filters
                    </button>
                  ) : null}
                </div>
              </div>
            ) : (
              <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.profileImage}
                              alt={bid.freelancer.name}
                              width={72}
                              height={72}
                            />
                          </div>
                          <div className="fc-content">
                            <h5>{bid.freelancer.name}</h5>
                            <div className="d-flex align-items-center">
                              <span className="star-icon me-1">
                                {renderStars(bid.freelancer.rating)}
                              </span>
                              {bid.freelancer.rating} ({bid.freelancer.reviewCount}+ Reviews)
                            </div>
                          </div>
                        </div>
                        <div className="viewbid-profile">
                          <Link href={`/${locale}/freelancers/${bid.freelancer.id}`} className="custom-btn">
                            View Profile
                          </Link>
                        </div>
                      </div>
                      
                      <div className="viewbid-chat">
                        <ul className="fc-contact">
                          <li className="fc-text">
                            <div className="icon">
                              <Image src="/assets/image/location.svg" alt="location" width={14} height={14} />
                            </div>
                            Location not specified
                          </li>
                          <li className="fc-text">
                            <div className="icon">
                              <Image src="/assets/image/calendar.svg" alt="date" width={14} height={14} />
                            </div>
                            Bid placed: {formatDate(bid.createdAt)}
                          </li>
                        </ul>
                        <button 
                          onClick={() => {
                            setSelectedBidId(selectedBidId === bid.id ? null : bid.id);
                          }}
                          className={`custom-btn ${selectedBidId === bid.id ? 'primary-fill' : '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.75ZM8.5 2.25C6.64167 2.25 5.17481 2.68261 4.17871 3.67871C3.18261 4.67481 2.75 6.14167 2.75 8V13C2.75 15.282 3.13316 16.7946 4.15723 17.6953C5.164 18.5807 6.66081 18.75 8.5 18.75H9C9.35167 18.75 9.78449 18.965 10.001 19.251L11.5 21.25L11.502 21.2529C11.7454 21.5728 12.0927 21.7949 12.5 21.7949C12.9073 21.7949 13.2546 21.5728 13.498 21.2529L13.5 21.25L15 19.25C15.2356 18.9359 15.6074 18.75 16 18.75H16.5C18.3583 18.75 19.8252 18.3174 20.8213 17.3213C21.8174 16.3252 22.25 14.8583 22.25 13V8C22.25 6.14167 21.8174 4.67481 20.8213 3.67871C19.8252 2.68261 18.3583 2.25 16.5 2.25H8.5Z" fill="#EF7310" stroke="#EF7310"/>
                            <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 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 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"/>
                          </svg>
                          {selectedBidId === bid.id ? 'Hide Chat' : 'Chat with Bid'}
                        </button>
                      </div>
                      
                      <div className="fc-dis">
                        <p>{bid.proposal}</p>
                      </div>
                      
                      <div className="bid-status">
                        <span className={`status-badge ${getStatusBadgeClass(bid.status)}`}>
                          {bid.status}
                        </span>
                      </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} />
                          €{bid.amount}
                        </div>
                        <div className="deal-price">
                          Can complete in {bid.deliveryTime} Days
                        </div>
                      </div>
                      
                      {bid.status === 'PENDING' && bidsData.project.status === 'OPEN' && (
                        <div className="project-bid">
                          <button
                            onClick={() => handleBidAction(bid.id, 'accept')}
                            disabled={actionLoading === bid.id}
                            className="custom-btn primary-fill"
                          >
                            {actionLoading === bid.id ? 'Processing...' : 'Accept'}
                          </button>
                          <button
                            onClick={() => handleBidAction(bid.id, 'reject')}
                            disabled={actionLoading === bid.id}
                            className="custom-btn red-outline"
                          >
                            <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>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Pagination */}
            {bidsData.pagination.totalPages > 1 && (
              <div className="pagination-container">
                <div className="pagination-info">
                  Showing {((bidsData.pagination.currentPage - 1) * bidsData.pagination.itemsPerPage) + 1} to {Math.min(bidsData.pagination.currentPage * bidsData.pagination.itemsPerPage, bidsData.pagination.totalItems)} of {bidsData.pagination.totalItems} bids
                </div>
                <div className="pagination-buttons">
                  {bidsData.pagination.hasPrevPage && (
                    <button
                      onClick={() => setCurrentPage(currentPage - 1)}
                      className="pagination-btn"
                    >
                      Previous
                    </button>
                  )}
                  <span className="page-info">
                    Page {bidsData.pagination.currentPage} of {bidsData.pagination.totalPages}
                  </span>
                  {bidsData.pagination.hasNextPage && (
                    <button
                      onClick={() => setCurrentPage(currentPage + 1)}
                      className="pagination-btn"
                    >
                      Next
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

    </section>
  );
}