import { useState } from "react";
import "./FundDrive.css";
// Inside src/Components/FundDrive.jsx
//import { submitVvvetForm } from "../vvvetApi";
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: "",
  fundAmount: "",
  paymentMethod: "",
  studentName: "",
  standard: "",
  parentName: "",
  parentPhone: "",
  feeDocument: null,
  patientName: "",
  cause: "",
  hospitalName: "",
  location: "",
  attenderName: "",
  medicalCertificate: null,
  medicalDocument: null,
  disasterName: "",
  disasterPlace: "",
  disasterPhone: "",
  disasterDocument: null,
  generalName: "",
  generalPlace: "",
  generalPhone: "",
  generalDocument: null
  });
  const [isPanVerified, setIsPanVerified] = useState(false); // To track PAN verification status
  const [verificationError, setVerificationError] = useState(""); 
  const [panImage, setPanImage] = useState(null); // Define panImage state

  const categories = [
    "Medical Fundraising",
    "Education & Scholarships",
    "Disaster Relief &  Aid",
    "Memorial & Tribute Funds",
    "Community Development",
    "Social Causes",
    "Religious & Faith-Based Giving",
    "Crowdfunding for Needs",
    "Nonprofit & NGO Fundraising",
    "Others",
  ];

  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 handleSubmit = () => {
  //   alert("Fundraising submission successful!");
  // };
  const handlePanImageUpload = (e) => {
    const file = e.target.files[0];
    setPanImage(file); // Store PAN image in state
  };


  
  const verifyPan = async () => {
    try {
      const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
      if (!panRegex.test(formData.pan)) {
        setVerificationError("Invalid PAN format.");
        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);

      const response = await axios.post(
        "http://localhost:5002/api/verify-pan",
        formDataForPan,
        {
          headers: { "Content-Type": "multipart/form-data" },
        }
      );

      if (response.data.verified) {
        setIsPanVerified(true);
        setVerificationError("");
        return true;
      } else {
        setIsPanVerified(false);
        setVerificationError(response.data.message || "PAN verification failed.");
        return false;
      }
    } catch (error) {
      setVerificationError(
        error.response?.data?.message || "Error connecting to PAN verification service."
      );
      setIsPanVerified(false);
      return false;
    }
  };

  
  
  // const handleSubmit = async (e) => {
  //   e.preventDefault();
  
  //   if (!isPanVerified) {
  //     const verified = await verifyPan();
  //     if (!verified) return;
  //   }
  
  //   try {
  //     await submitVvvetForm(formData); 
  //     await axios.post("http://localhost:5002/api/users/add", formData);
  //     // Ensure this sends the form data to your backend
  //     setStep(5); // Show the thank-you screen
  //   } catch (error) {
  //     console.error("Error submitting form:", error);
  //     // You can optionally show an inline error message instead of alert
  //   }
  // };
  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 all string fields except files
      for (const key in formData) {
        const value = formData[key];
        if (value !== null && value !== undefined) {
          // Check if value is a File or object, skip files here
          if (value instanceof File) continue;
          if (typeof value === "object") continue;

          formSubmissionData.append(key, value);
        }
      }

      // Append files (file inputs) separately
      const fileFields = ["feeDoc", "medicalPhoto", "medicalDoc", "document"];
      fileFields.forEach((field) => {
        if (formData[field]) {
          formSubmissionData.append(field, formData[field]);
        }
      });

      // Also append panImage again if you want backend to receive it on form submit
      if (panImage) {
        formSubmissionData.append("panImage", panImage);
      }

      const response = await axios.post(
        "http://localhost:5002/api/fundraising/submit",
        formSubmissionData,
        {
          headers: { "Content-Type": "multipart/form-data" },
        }
      );

      console.log("Form submission response:", response.data);

      // On success, move to thank-you step
      setStep(4);
    } catch (error) {
      console.error("Error submitting form:", error);
      alert("Error submitting form. Please try again.");
    }
  };
  const isStep2Valid = () => {
    const { category, customCategory, customReason } = formData;
  
    if (!category) return false;
  
    if (category === "Others") {
      return customCategory?.trim() && customReason?.trim();
    }
  
    const requiredFieldsByCategory = {
      "Medical Fundraising": ["patientName", "cause", "hospitalName", "location", "phoneNumber", "attenderName", "amount", "medicalPhoto", "medicalDoc"],
      "Education & Scholarships": ["studentName", "standard", "parentsName", "parentsPhone", "amount", "feeDoc"],
      "Disaster Relief &  Aid": ["name", "place", "phoneNumber", "amount", "document"],
      "Memorial & Tribute Funds": ["name", "place", "phoneNumber", "amount", "document"],
      "Community Development": ["name", "place", "phoneNumber", "amount", "document"],
      "Social Causes": ["name", "place", "phoneNumber", "amount", "document"],
      "Religious & Faith-Based Giving": ["name", "place", "phoneNumber", "amount", "document"],
      "Crowdfunding for Needs": ["name", "place", "phoneNumber", "amount", "document"],
      "Nonprofit & NGO Fundraising": ["name", "place", "phoneNumber", "amount", "document"]
    };
  
    const fields = requiredFieldsByCategory[category];
    if (!fields) return true;
  
    return fields.every(field => {
      const value = formData[field];
      return value && (typeof value === "string" ? value.trim() : true);
    });
  };
  const handleFileChange = (e) => {
    const { name, files } = e.target;
    setFormData(prev => ({ ...prev, [name]: files[0] }));
  };
  
  
  

  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.date}
                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="form-container-box">
            <h4>Step 2:Select a category</h4>
            {categories.map((item, index) => (
              <div key={index} className="radio-box">
                <input
                  type="radio"
                  name="category"
                  value={item}
                  checked={formData.category === item}
                  onChange={handleInputChange}
                  className="radio-input"
                />
                <label className="radio-label">{item}</label>
              </div>
            ))}
            {formData.category === "Others" && (
              <input
                type="text"
                name="customCategory"
                placeholder="Fill the category"
                value={formData.customCategory}
                onChange={handleInputChange}
                className="custom-category-input"
              />
            )}
            <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={handleNext} 
                disabled={!formData.category || (formData.category === "Others" && !formData.customCategory.trim())}
              >
                Next
              </button>
            </div>
          </div>
        )} */}
        {step === 2 && (
  <div className="form-container-box">
    <h4>Step 2: Select a category</h4>

    <select
      name="category"
      value={formData.category}
      onChange={handleInputChange}
      className="dropdown-input"
      required
    >
      <option value="">-- Select a Category --</option>
      {categories.map((item, index) => (
        <option key={index} value={item}>{item}</option>
      ))}
    </select>

    {formData.category === "Others" && (
      <>
        <label>Custom Category</label>
        <input
          type="text"
          name="customCategory"
          placeholder="Specify the category"
          value={formData.customCategory}
          onChange={handleInputChange}
          required
          className="custom-category-input"
        />
      </>
    )}

    {/* Medical Fundraising */}
    {formData.category === "Medical Fundraising" && (
      <>
        <h5>Medical Fundraising Details</h5>
        <label>Patient Name</label>
        <input type="text" name="patientName" value={formData.patientName} onChange={handleInputChange} required />

        <label>Cause</label>
        <input type="text" name="cause" value={formData.cause} onChange={handleInputChange} required />

        <label>Hospital Name</label>
        <input type="text" name="hospitalName" value={formData.hospitalName} onChange={handleInputChange} required />

        <label>Location</label>
        <input type="text" name="location" value={formData.location} onChange={handleInputChange} required />

        <label>Phone Number</label>
        <input type="tel" name="phoneNumber" value={formData.phoneNumber} onChange={handleInputChange} required />

        <label>Attender Name</label>
        <input type="text" name="attenderName" value={formData.attenderName} onChange={handleInputChange} required />

        <label>Amount Needed</label>
        <input type="number" name="amount" value={formData.amount} onChange={handleInputChange} required />

        <label>Medical Certificate</label>
        <input type="file" name="medicalPhoto" accept="image/*" onChange={handleFileChange} required />

        <label>Medical Document</label>
        <input type="file" name="medicalDoc" accept=".pdf,.doc,.docx" onChange={handleFileChange} required />
      </>
    )}

    {/* Education & Scholarships */}
    {formData.category === "Education & Scholarships" && (
      <>
        <h5>Education & Scholarships Details</h5>
        <label>Student Name</label>
        <input type="text" name="studentName" value={formData.studentName} onChange={handleInputChange} required />

        <label>Standard</label>
        <input type="text" name="standard" value={formData.standard} onChange={handleInputChange} required />

        <label>Parent&apos;s Name</label>
        <input type="text" name="parentsName" value={formData.parentsName} onChange={handleInputChange} required />

        <label>Parent&apos;s Phone</label>
        <input type="tel" name="parentsPhone" value={formData.parentsPhone} onChange={handleInputChange} required />

        <label>Amount Needed</label>
        <input type="number" name="amount" value={formData.amount} onChange={handleInputChange} required />

        <label>Fee Document</label>
        <input type="file" name="feeDoc" accept=".pdf,.doc,.docx" onChange={handleFileChange} required />
      </>
    )}

    {/* Disaster Relief */}
    {formData.category === "Disaster Relief &  Aid" && (
      <>
        <h5>Disaster Relief Details</h5>
        <label>Name</label>
        <input type="text" name="name" value={formData.name} onChange={handleInputChange} required />

        <label>Place</label>
        <input type="text" name="place" value={formData.place} onChange={handleInputChange} required />

        <label>Phone Number</label>
        <input type="tel" name="phoneNumber" value={formData.phoneNumber} onChange={handleInputChange} required />

        <label>Amount Needed</label>
        <input type="number" name="amount" value={formData.amount} onChange={handleInputChange} required />

        <label>Relief Document</label>
        <input type="file" name="document" accept=".pdf,.doc,.docx" onChange={handleFileChange} required />
      </>
    )}

    {/* Common template for general categories */}
    {[
      "Memorial & Tribute Funds",
      "Community Development",
      "Social Causes",
      "Religious & Faith-Based Giving",
      "Crowdfunding for Needs",
      "Nonprofit & NGO Fundraising"
    ].includes(formData.category) && (
      <>
        <h5>Fundraising Details</h5>
        <label>Name</label>
        <input type="text" name="name" value={formData.name} onChange={handleInputChange} required />

        <label>Place</label>
        <input type="text" name="place" value={formData.place} onChange={handleInputChange} required />

        <label>Phone Number</label>
        <input type="tel" name="phoneNumber" value={formData.phoneNumber} onChange={handleInputChange} required />

        <label>Amount Needed</label>
        <input type="number" name="amount" value={formData.amount} onChange={handleInputChange} required />

        <label>Support Document</label>
        <input type="file" name="document" accept=".pdf,.doc,.docx" onChange={handleFileChange} required />
      </>
    )}

    {/* Others Reason */}
    {formData.category === "Others" && (
      <>
        <h5>Other Fundraising Reason</h5>
        <label>Reason</label>
        <textarea
          name="customReason"
          placeholder="Specify your reason"
          value={formData.customReason}
          onChange={handleInputChange}
          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={handleNext}
        disabled={!isStep2Valid()}
      >
        Next
      </button>
    </div>
  </div>
)}


        
        {/* {step === 3 && (
          <div className="upload-section-box">
            <h4>Step 3:Upload an Image</h4>
            <h3 className="upload-title">{formData.category === "Others" ? formData.customCategory : formData.category}</h3>
            <div className="upload-box">
              <input
                type="file"
                multiple
                accept="image/*"
                onChange={handleImageUpload}
                className="file-input"
              />
              <p className="upload-placeholder">Click or Drag & Drop to upload images</p>
            </div>
            <div className="image-preview">
              {formData.images.map((image, index) => (
                <img key={index} src={URL.createObjectURL(image)} alt={`Proof ${index + 1}`} className="uploaded-image" />
              ))}
            </div> */}
            
            {step === 3 && (
  <div className="bank-details-section-box">
    <h4>Step 3: 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) => {
          const value = e.target.value;
          if (/^\d{0,17}$/.test(value)) {
            setFormData({ ...formData, accountNumber: value });
          }
        }}
      />
      {(formData.accountNumber.length < 11 || formData.accountNumber.length > 17)
      }
    </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.toUpperCase() })}
      />
      {!/^[A-Z]{4}0[A-Z0-9]{6}$/.test(formData.ifscCode) && formData.ifscCode !== '' && (
        <p className="error-message">Invalid IFSC Code format</p>
      )}
    </div>

    <div className="form-group">
      <label className="form-label">Fundraising Amount</label>
      <input
        type="number"
        placeholder="Fundraising Amount"
        className="form-field"
        value={formData.fundAmount}
        onChange={(e) => {
          const value = parseInt(e.target.value, 10);
          setFormData({ ...formData, fundAmount: isNaN(value) ? '' : value });
        }}
        min="1000"
      />
      {formData.fundAmount > 0 && formData.fundAmount < 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={handleSubmit}
        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.fundAmount ||
          formData.fundAmount < 1000
        }
      >
        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;
