import { useState } from "react";
import "./FundDrive.css";
// Inside src/Components/FundDrive.jsx
import axios from "axios";
import './form-step2.css';



const FundDrive = () => {
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    name: "",
  email: "",
  phone: "",
  age: "",
  dob: "",
  category: "",
  customCategory: "",
  pan: "",
  images: [],
  bankHolderName: "",
  bankName: "",
  accountNumber: "",
  ifscCode: "",
  donation_Amount: "",
  payment: "",
  transactionScreenshot: null,
  feeDoc: null,
  });
  const [isPanVerified, setIsPanVerified] = useState(false); // To track PAN verification status
  const [verificationError, setVerificationError] = useState(""); 
  const [panImage, setPanImage] = useState(null); // Define panImage state

  

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  

  const handleNext = () => {
    setStep(step + 1);
  };

  const handleBack = () => {
    if (step > 1) setStep(step - 1);
  };

 
  const handlePanImageUpload = (e) => {
    const file = e.target.files[0];
    setPanImage(file); // Store PAN image in state
  };



  const verifyPan = async () => {
    try {
      // Validate PAN format client-side first
      const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
      if (!panRegex.test(formData.pan)) {
        setVerificationError("Invalid PAN format. It should be in the format ABCDE1234F.");
        setIsPanVerified(false);
        return false;
      }
  
      if (!panImage) {
        setVerificationError("Please upload a PAN card image.");
        setIsPanVerified(false);
        return false;
      }
  
      const formDataForPan = new FormData();
      formDataForPan.append("pan", formData.pan);
      formDataForPan.append("panImage", panImage);
  
      // Show loading state if needed
      // setIsLoading(true);
  
      const response = await axios.post(
        "http://localhost:5002/api/verify-pan",
        formDataForPan,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
  
 
  
      console.log("PAN verification response:", response.data);
      
      if (response.data.verified) {
        setIsPanVerified(true);
        setVerificationError(""); // Clear any previous errors
        return true;
      } else {
        setIsPanVerified(false);
        setVerificationError(response.data.message || "PAN verification failed.");
        return false;
      }
    } catch (error) {
      // Hide loading state
      // setIsLoading(false);
      
      console.error("Error verifying PAN:", error);
      
      // Handle specific error cases
      if (error.response) {
        // The server responded with an error status
        setVerificationError(error.response.data.message || "PAN verification failed. Server returned an error.");
      } else if (error.request) {
        // The request was made but no response was received
        setVerificationError("Cannot connect to the verification service. Please try again later.");
      } else {
        // Something else caused the error
        setVerificationError("An error occurred during PAN verification.");
      }
      
      setIsPanVerified(false);
      return false;
    }
  };

  
  const handleFileChange = (e) => {
    const { name, files } = e.target;
    setFormData((prev) => ({ ...prev, [name]: files[0] }));
  };
  const handleSubmit = async (e) => {
    e.preventDefault();

    // Verify PAN first if not verified
    if (!isPanVerified) {
      const verified = await verifyPan();
      if (!verified) return;
    }

    try {
      const formSubmissionData = new FormData();
  
      // Append non-file fields
      for (const key in formData) {
        if (formData[key] && !(formData[key] instanceof File)) {
          formSubmissionData.append(key, formData[key]);
        }
      }
  
      // Append donor-specific file fields
      if (panImage) {
        formSubmissionData.append("panImage", panImage);
      }
      if (formData.transactionScreenshot) {
        formSubmissionData.append("transactionScreenshot", formData.transactionScreenshot);
      }
  
      const response = await axios.post(
        "http://localhost:5002/api/donor/submit",
        formSubmissionData,
        { headers: { "Content-Type": "multipart/form-data" } }
      );
  
      console.log("Donor form response:", response.data);
      setStep(4); // success step
    } catch (error) {
      console.error("Donor form submission error:", error);
      alert("Error submitting donor form. Please try again.");
    }
  };
  
  
  

  return (
    <div className="container">
      
       <div className="container-box">
       <form>
       {step === 1 && (
        <div className="step-box">
          <h4>Step 1: Personal Details</h4>

          <div className="form-grid">
            <div className="form-field">
              <label>Name</label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                required
                placeholder="Full Name"
              />
            </div>

            <div className="form-field">
              <label>Email</label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
                placeholder="example@domain.com"
              />
            </div>
            <div className="form-field">
              <label>Age</label>
              <input
                type="number"
                name="age"
                value={formData.age}
                onChange={handleInputChange}
                required
                placeholder="e.g. 25"
              />
            </div>
            <div className="form-field">
              <label>Date of Birth</label>
              <input
                type="date"
                name="dob"
                value={formData.dob}
                onChange={handleInputChange}
                required
                placeholder="e.g. 25"
              />
            </div>
          </div>
          <div className="form-field">
              <label>Phone Number</label>
              <input
                type="tel"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                required
                placeholder="10-digit number"
              />
            </div>
          <div className="form-field">
            <label>PAN Number</label>
            <input
              type="text"
              name="pan"
              value={formData.pan}
              onChange={handleInputChange}
              required
              maxLength={10}
              placeholder="e.g. ABCDE1234F"
              className="input-small"
              pattern="[A-Z]{5}[0-9]{4}[A-Z]{1}"
              title="Enter valid 10-character PAN (e.g. ABCDE1234F)"
            />
          </div>
          <div className="form-field">
                <label>Upload PAN Image</label>
                <input
                  type="file"
                  accept="image/*"
                  onChange={handlePanImageUpload}
                  required
                />
                {panImage && <p>{panImage.name}</p>} {/* Display image file name */}
              </div>
          {verificationError && <p style={{ color: 'red' }}>{verificationError}</p>}
          <div className="form-field">
            <button
              type="button"
              className="form-button verify-button"
              onClick={verifyPan}
              disabled={!formData.pan || !panImage}
            >
              Verify PAN
            </button>
            {isPanVerified && <p style={{ color: 'green' }}>PAN verified successfully!</p>}
          </div>
          <div className="button-group">
            <button
              type="button"
              onClick={handleNext}
              className="form-button next-button"
              disabled={!formData.name || !formData.email || !formData.phone || !formData.age || !formData.dob || !formData.pan || !isPanVerified} 
            >
              Next
            </button>
          </div>
        </div>
      )}
        
      
            
    {step === 2 && (
  <div className="bank-details-section-box">
    <h4>Step 2: Banking Details</h4>

    <div className="form-group">
      <label className="form-label">Bank Account Holder Name</label>
      <input
        type="text"
        placeholder="Bank Account Holder Name"
        className="form-field"
        value={formData.bankHolderName}
        onChange={(e) => setFormData({ ...formData, bankHolderName: e.target.value })}
      />
    </div>

    <div className="form-group">
      <label className="form-label">Bank Name</label>
      <input
        type="text"
        placeholder="Bank Name"
        className="form-field"
        value={formData.bankName}
        onChange={(e) => setFormData({ ...formData, bankName: e.target.value })}
      />
    </div>

    <div className="form-group">
      <label className="form-label">Bank Account Number</label>
      <input
        type="text"
        placeholder="Bank Account Number"
        className="form-field"
        value={formData.accountNumber}
        onChange={(e) => setFormData({ ...formData, accountNumber: e.target.value })}
      />
    </div>

    <div className="form-group">
      <label className="form-label">IFSC Code</label>
      <input
        type="text"
        placeholder="IFSC Code"
        className="form-field"
        value={formData.ifscCode}
        onChange={(e) => setFormData({ ...formData, ifscCode: e.target.value })}
      />
    </div>
    <div className="form-group">
      <label className="form-label">Donating Amount</label>    
      <input
        type="number"
        placeholder="Donating Amount"
        className="form-field"
        value={formData.donation_Amount}
        onChange={(e) => {
          const value = parseInt(e.target.value, 10);
          if (!isNaN(value) && value >= 0) {
            setFormData({ ...formData, donation_Amount: value });
          }
        }}
        min="1000"
      />
      {formData.donation_Amount > 0 && formData.donation_Amount < 1000 && (
        <p className="error-message">Minimum amount should be ₹1000</p>
      )}
    </div>
    <div className="button-group">
      <button type="button" className="form-button back-button" onClick={handleBack}>
        Back
      </button>
      {/* <button type="button" className="form-button submit-button" onClick={handleNext}>
        Next
      </button> */}
       <button
        type="button"
        className="form-button submit-button"
        onClick={handleNext}
        disabled={
          !formData.bankHolderName ||
          !formData.bankName ||
          !formData.accountNumber ||
          formData.accountNumber.length < 11 ||
          formData.accountNumber.length > 17 ||
          !formData.ifscCode ||
          !/^[A-Z]{4}0[A-Z0-9]{6}$/.test(formData.ifscCode) ||
          !formData.donation_Amount||
          formData.donation_Amount < 1000
        }
      >
        Next
      </button>
    </div>
  </div>
)}
  {step === 3 && (
  <div className="form-container-box">
    <h4>Step 3: Payment & Upload Transaction Screenshot</h4>

    <label htmlFor="payment">Select Payment Method *</label>
    <select
      name="payment"
      value={formData.payment || ""}
      onChange={handleInputChange}
      required
      className="form-select"
    >
      <option value="" disabled>Select Payment Mode</option>
      <option value="UPI">UPI</option>
      <option value="Bank Transfer">Bank Transfer</option>
    </select>

    {/* UPI QR Code */}
    {formData.payment === "UPI" && (
      <div className="upi-section">
        <p>Scan the UPI QR code to make the payment:</p>
        <img src="src/Components/upi.png" alt="UPI QR Code" className="upi-image" />
      </div>
    )}

    {/* Bank Transfer Details */}
    {formData.payment === "Bank Transfer" && (
    <div className="bank-details">
      <p><strong>Account No:</strong> 50200082832122</p>
      <p><strong>Bank:</strong> HDFC</p>
      <p><strong>Branch:</strong> DEVAKOTTAI</p>
      <p><strong>Account Name:</strong> DVK VETRIVEL EDU AND WEL PUB CHAR TRUST</p>
      <p><strong>Account Type:</strong> Current</p>
      <p><strong>RTGS/NEFT IFSC:</strong> HDFC0002576</p>
    </div>
  )}


    {/* Screenshot Upload */}
    {formData.payment && (
      <>
        <label htmlFor="transactionScreenshot">Upload Transaction Screenshot *</label>
        <input
          type="file"
          name="transactionScreenshot"
          accept="image/*"
          onChange={handleFileChange}
          required
        />
      </>
    )}

    <div className="button-group">
      <button type="button" className="form-button back-button" onClick={handleBack}>
        Back
      </button>
      <button
        type="button"
        className="form-button next-button"
        onClick={handleSubmit}
        disabled={!formData.payment || !formData.transactionScreenshot}
      >
        Submit
      </button>
    </div>
  </div>
)}

{step === 4 && (
  <div className="form-container-box">
    <h4>Thank You!</h4>
    <p>Thanks for reaching out to VVET. We will review your submission and get back to you soon.</p>

    <button className="form-button" onClick={() => window.location.reload()}>
      Start Over
    </button>
  </div>
)}



        
      </form>
</div>
</div>
    
    
  );
};

export default FundDrive;
