'use client';

import { useState } from 'react';
import Image from 'next/image';
import { useToast } from '@/components/ui/ToastContext';
import { useApiCall } from '@/hooks/useApiCall';
import { ApiClient } from '@/lib/api-utils';

interface BidModalProps {
  isOpen: boolean;
  onClose: () => void;
  project: {
    id: string;
    title: string;
    budget: number;
    description: string;
    client: {
      name: string;
      profileImage: string;
    };
  } | null;
  onBidSubmitted: () => void;
}

export default function BidModal({ isOpen, onClose, project, onBidSubmitted }: BidModalProps) {
  const [formData, setFormData] = useState({
    amount: '',
    deliveryTime: '',
    proposal: ''
  });
  const { showError, showSuccess } = useToast();
  // Use custom api call hook to control toast behavior precisely
  const { loading: isSubmitting, execute: submitBid } = useApiCall({
    showSuccessToast: false, // We'll handle success manually to avoid duplicates
    showErrorToast: true,
    errorTitle: 'Bid Submission Failed'
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!project) return;

    // Validation
    if (!formData.amount || !formData.deliveryTime || !formData.proposal) {
      showError('Please fill in all fields');
      return;
    }

    if (parseFloat(formData.amount) <= 0) {
      showError('Bid amount must be greater than 0');
      return;
    }

    if (parseInt(formData.deliveryTime) <= 0) {
      showError('Delivery time must be greater than 0');
      return;
    }

    if (formData.proposal.trim().length < 10) {
      showError('Proposal must be at least 10 characters long');
      return;
    }

    try {
      await submitBid(() => 
        ApiClient.post(`/api/projects/${project.id}/bid`, {
          price: parseFloat(formData.amount),
          days: parseInt(formData.deliveryTime),
          description: formData.proposal.trim()
        })
      );
      
      // Show single success toast
      showSuccess('Bid submitted successfully! Chat has been initialized.');
      
      // Reset form on success
      setFormData({
        amount: '',
        deliveryTime: '',
        proposal: ''
      });
      
      onBidSubmitted();
      onClose();
    } catch (error) {
      // Error toasts are handled by the hook automatically
      console.error('Bid submission failed:', error);
    }
  };

  const handleClose = () => {
    if (!isSubmitting) {
      setFormData({
        amount: '',
        deliveryTime: '',
        proposal: ''
      });
      onClose();
    }
  };

  if (!isOpen || !project) return null;

  return (
    <div className="bid-modal-overlay" onClick={handleClose}>
      <div className="bid-modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="bid-modal-header">
          <h3>Submit Your Bid</h3>
          <button 
            className="bid-modal-close" 
            onClick={handleClose}
            disabled={isSubmitting}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        <div className="bid-modal-body">
          <div className="project-summary">
            <div className="project-client">
              <div className="client-avatar">
                <Image 
                  src={project.client.profileImage} 
                  alt={project.client.name}
                  width={40}
                  height={40}
                />
              </div>
              <div className="client-info">
                <h5>{project.client.name}</h5>
                <span>Project Budget: €{project.budget}</span>
              </div>
            </div>
            <div className="project-title">
              <h4>{project.title}</h4>
              <p>{project.description}</p>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="bid-form">
            <div className="form-row">
              <div className="form-group">
                <label htmlFor="amount">Your Bid Amount (€)</label>
                <input
                  type="number"
                  id="amount"
                  name="amount"
                  value={formData.amount}
                  onChange={handleInputChange}
                  placeholder="Enter your bid amount"
                  min="1"
                  step="0.01"
                  required
                  disabled={isSubmitting}
                />
              </div>
              <div className="form-group">
                <label htmlFor="deliveryTime">Delivery Time (Days)</label>
                <input
                  type="number"
                  id="deliveryTime"
                  name="deliveryTime"
                  value={formData.deliveryTime}
                  onChange={handleInputChange}
                  placeholder="Number of days"
                  min="1"
                  required
                  disabled={isSubmitting}
                />
              </div>
            </div>

            <div className="form-group">
              <label htmlFor="proposal">Your Proposal</label>
              <textarea
                id="proposal"
                name="proposal"
                value={formData.proposal}
                onChange={handleInputChange}
                placeholder="Describe your approach, experience, and why you're the best fit for this project..."
                rows={6}
                minLength={10}
                required
                disabled={isSubmitting}
              />
              <span className="char-count">{formData.proposal.length} characters</span>
            </div>

            <div className="bid-modal-actions">
              <button
                type="button"
                onClick={handleClose}
                className="custom-btn secondary-outline"
                disabled={isSubmitting}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="custom-btn primary-fill"
                disabled={isSubmitting}
              >
                {isSubmitting ? 'Submitting...' : 'Submit Bid'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}