'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { BidFormData, BidModalProps } from '@/types/bid';
import { getCountryDataByDomain } from '@/lib/countries';

export default function BidModal({ 
  isOpen, 
  onClose, 
  onSubmit, 
  projectTitle, 
  loading = false,
  isUpdateMode = false,
  initialBidData
}: BidModalProps) {
  const [bidForm, setBidForm] = useState<BidFormData>({
    price: initialBidData?.amount || '',
    days: initialBidData?.deliveryTime || '',
    description: initialBidData?.proposal || ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
   const datacounter = getCountryDataByDomain();

  // Update form when initialBidData changes (for update mode)
  useEffect(() => {
    if (isOpen && initialBidData) {
      setBidForm({
        price: initialBidData.amount || '',
        days: initialBidData.deliveryTime || '',
        description: initialBidData.proposal || ''
      });
    } else if (isOpen && !initialBidData) {
      // Reset form for new bids
      setBidForm({ price: '', days: '', description: '' });
    }
  }, [isOpen, initialBidData]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!bidForm.price || !bidForm.days || !bidForm.description) {
      return;
    }

    setIsSubmitting(true);
    
    try {
      await onSubmit(bidForm);
      // Reset form after successful submission
      setBidForm({ price: '', days: '', description: '' });
      onClose();

      setTimeout(() => {
        window.location.reload();   // true forces reload from server; default is fine for most cases
      }, 1500)


    } catch (error) {
      console.error('Error submitting bid:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!isSubmitting) {
      setBidForm({ price: '', days: '', description: '' });
      onClose();
    }
  };

  const handleInputChange = (field: keyof BidFormData, value: string) => {
    setBidForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  if (!isOpen) return null;

  return (
    <>
      <div className="modal fade show custom-modal" style={{ display: 'block' }} tabIndex={-1}>
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="tab-title">
              <h5>{isUpdateMode ? 'Update Proposal' : 'Add Proposal'}</h5>
              <button 
                type="button" 
                className="btn-close" 
                onClick={handleClose}
                disabled={isSubmitting}
                aria-label="Close"
              />
            </div>
            
            {projectTitle && (
              <div className="mb-3">
                <small className="text-muted">
                  Bidding on: <strong>{projectTitle}</strong>
                </small>
              </div>
            )}
            
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="bid-price" className="form-label">
                    Price * <span className="text-muted">(in {datacounter?.currencySymbol ?? ''})</span>
                  </label>
                  <div className="input-icon">
                    <input 
                      type="number" 
                      className="form-control" 
                      name="price" 
                      id="bid-price" 
                      placeholder="Enter your bid amount"
                      value={bidForm.price}
                      onChange={(e) => handleInputChange('price', e.target.value)}
                      min="1"
                      step="0.01"
                      required
                      disabled={isSubmitting}
                    />
                  </div>
                </div>
                
                <div className="mb-20">
                  <label htmlFor="bid-days" className="form-label">
                    Days needed to complete the work *
                  </label>
                  <div className="input-icon">
                    <input 
                      type="number" 
                      className="form-control" 
                      name="days" 
                      id="bid-days" 
                      placeholder="Enter number of days"
                      value={bidForm.days}
                      onChange={(e) => handleInputChange('days', e.target.value)}
                      min="1"
                      required
                      disabled={isSubmitting}
                    />
                  </div>
                </div>
              </div>

              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="bid-description" className="form-label">
                    Proposal Description *
                  </label>
                  <div className="input-icon">
                    <textarea 
                      className="form-control" 
                      name="description"
                      id="bid-description"
                      placeholder="Describe your approach, experience, and why you're the best fit for this project..."
                      value={bidForm.description}
                      onChange={(e) => handleInputChange('description', e.target.value)}
                      required
                      disabled={isSubmitting}
                      rows={6}
                    />
                  </div>
                </div>
              </div>
              
              <div className="pop-dis">
                <p>
                  Please read in full and understand the client's requirements. A well written and fully understood proposal is key to winning the work. See our{' '}
                  <Link href="/proposal-advice">Proposal Advice Here.</Link>
                </p>
              </div>
              
              <div className="d-flex gap-2">
                <button 
                  type="button" 
                  className="flex-fill custom-btn outline-btn cancel-modal-btn"
                  onClick={handleClose}
                  disabled={isSubmitting}
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  className="flex-fill custom-btn secondary-btn"
                  // disabled={isSubmitting || !bidForm.price || !bidForm.days || !bidForm.description}
                  disabled={isSubmitting}
                >
                  {isSubmitting ? (
                    <>
                      <span 
                        className="spinner-border spinner-border-sm me-2" 
                        role="status" 
                        aria-hidden="true"
                      />
                      Submitting...
                    </>
                  ) : (
                    isUpdateMode ? 'Update Proposal' : 'Submit Proposal'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
      
      {/* Modal Backdrop */}
      <div 
        className="modal-backdrop fade show" 
        onClick={handleClose}
        style={{ pointerEvents: isSubmitting ? 'none' : 'auto' }}
      />
    </>
  );
}