'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';

interface BidInfo {
  id: string;
  amount: number;
  duration: number;
  status: 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'WITHDRAWN';
  projectId: string;
  projectTitle: string;
  freelancerId: string;
  freelancerName: string;
  createdAt: string;
}

interface BidActionHeaderProps {
  contactId: string;
  projectId?: string;
  onBidAction?: (bidId: string, action: 'accept' | 'reject') => void;
}

export default function BidActionHeader({ contactId, projectId, onBidAction }: BidActionHeaderProps) {
  const { data: session } = useSession();
  const { showSuccess, showError } = useToast();
  const [bidInfo, setBidInfo] = useState<BidInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  useEffect(() => {
    if (contactId && projectId && session?.user?.role === 'CLIENT') {
      fetchBidInfo();
    }
  }, [contactId, projectId, session]);

  const fetchBidInfo = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/projects/${projectId}/bids/freelancer/${contactId}`);
      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data) {
          setBidInfo(data.data);
        }
      }
    } catch (error) {
      console.error('Error fetching bid info:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleBidAction = async (action: 'accept' | 'reject') => {
    if (!bidInfo) return;

    setActionLoading(action);
    try {
      const response = await fetch(`/api/projects/${projectId}/bids/${bidInfo.id}/${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`);
      }

      // Update bid status locally
      setBidInfo(prev => prev ? { ...prev, status: action === 'accept' ? 'ACCEPTED' : 'REJECTED' } : null);
      
      // Show success message
      if (action === 'accept') {
        showSuccess(
          `Bid accepted successfully! ` +
          `Freelancer: ${bidInfo.freelancerName}, ` +
          `Amount: €${bidInfo.amount}, ` +
          `Duration: ${bidInfo.duration} days. ` +
          `Project status updated to "In Progress".`,
          'Bid Accepted 🎉'
        );
      } else {
        showSuccess('Bid rejected successfully.', 'Bid Rejected');
      }

      // Call callback if provided
      if (onBidAction) {
        onBidAction(bidInfo.id, action);
      }

    } catch (err) {
      showError(
        err instanceof Error ? err.message : `An error occurred while ${action}ing the bid`,
        'Bid Action Failed'
      );
    } finally {
      setActionLoading(null);
    }
  };

  // Don't show if not a client or no bid info
  if (session?.user?.role !== 'CLIENT' || !bidInfo || loading) {
    return null;
  }

  return (
    <div className="bid-action-header">
      <div className="bid-info">
        <div className="bid-details">
          <h4>{bidInfo.projectTitle}</h4>
          <div className="bid-amount">
            <span className="price">€{bidInfo.amount}</span>
            <span className="duration">{bidInfo.duration} days</span>
          </div>
        </div>
        <div className="bid-status">
          {bidInfo.status === 'PENDING' && (
            <div className="bid-actions">
              <button 
                onClick={() => handleBidAction('accept')}
                className="btn-accept"
                disabled={actionLoading !== null}
              >
                {actionLoading === 'accept' ? 'Accepting...' : 'Accept Bid'}
              </button>
              <button 
                onClick={() => handleBidAction('reject')}
                className="btn-reject"
                disabled={actionLoading !== null}
              >
                {actionLoading === 'reject' ? 'Rejecting...' : 'Reject'}
              </button>
            </div>
          )}
          {bidInfo.status === 'ACCEPTED' && (
            <div className="bid-status-badge accepted">
              ✓ Bid Accepted
            </div>
          )}
          {bidInfo.status === 'REJECTED' && (
            <div className="bid-status-badge rejected">
              ✗ Bid Rejected
            </div>
          )}
        </div>
      </div>
    </div>
  );
}