
import React, { useState, forwardRef, FormEvent, useEffect, useRef } from "react";
import Image from "next/image";
import Form from 'react-bootstrap/Form';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Alert from 'react-bootstrap/Alert';
import Button from 'react-bootstrap/Button';
import ReCAPTCHA from "react-google-recaptcha";
import ListGroup from 'react-bootstrap/ListGroup';

interface FormApplyForJobProps {
  positionselected: string;
}
// type ErrorFields = 'name' | 'email' | 'phone' | 'selectPosition' | 'totalExperience' | 'file' | 'highestQualification' | 'currentCtc' | 'expectedCtc' | 'noticePeriod' | 'keyskill' | 'token';

type ErrorFields = 'name' | 'email' | 'selectPosition' | 'totalExperience' | 'file' | 'highestQualification' | 'currentCtc' | 'expectedCtc' | 'noticePeriod' | 'keyskill' | 'token';

const JobApply = forwardRef<HTMLDivElement, FormApplyForJobProps>((props:any, ref:any) => {
  const [response, setResponse] = useState<{ status: string; message: string } | null>(null);
  const [applyjob, setapplyjob] = useState({
    name: "",
    email: "",
    phone: "",
    currentLocation: '',
    highestQualification: '',
    selectPosition: props.positionselected,
    totalExperience: '',
    currentCtc: '',
    expectedCtc: '',
    noticePeriod: '',
    keyskill: '',
    file: null as File | null,
    token: null as string | null,
  });

  const [errors, seterrors] = useState<Record<ErrorFields, string>>({
    name: "",
    email: "",
    //phone: "",
    highestQualification: "",
    selectPosition: "",
    totalExperience: "",
    currentCtc: "",
    expectedCtc: "",
    noticePeriod: "",
    keyskill: "",
    file: "",
    token: ''
  });
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (props.positionselected !== applyjob.selectPosition) {
      setapplyjob((prev) => ({
        ...prev,
        selectPosition: props.positionselected,
      }));
    }
  }, [props.positionselected]);

  const handle_fields = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => 
  {
    const { name, value } = e.target as HTMLInputElement & { name: keyof typeof applyjob };
 
    if(e.target instanceof HTMLSelectElement) {
      setapplyjob((prev) => ({
        ...prev, 
        [name]: value
      }))
    } else if(e.target instanceof HTMLInputElement) {

      // if (name === 'phone') {
      //   const numericValue = value.replace(/[^0-9]/g, '');
      //   if (numericValue.length < 16) {
      //     setapplyjob((prev) => ({
      //       ...prev,
      //       [name]: numericValue,
      //     }));
      //   }
      // } else {
      //   setapplyjob((prev) => ({
      //     ...prev,
      //     [name]: value,
      //   }));
      // }

      if (name === 'phone') {
        const numericValue = value.replace(/[^0-9]/g, '');
        setapplyjob((prev) => ({
          ...prev,
          [name]: numericValue,
        }));
      } else {
        setapplyjob((prev) => ({
          ...prev,
          [name]: value,
        }));
      }

    } else if(e.target instanceof HTMLTextAreaElement) {
      setapplyjob((prev) => ({
        ...prev, 
        [name]: value
      }))
    }
  };

  const handle_fields_file = (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
        const allowedTypes = [
          "application/pdf",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ];
  
        if (!allowedTypes.includes(file.type)) {
          seterrors((prev) => ({ ...prev, file: "Invalid file format. Please select a valid file." }));
          return;
        }
  
        const maxSize = 10 * 1024 * 1024; // 10 MB
        if (file.size > maxSize) {
          seterrors((prev) => ({ ...prev, file: "File size exceeds the 5MB limit." }));
          return;
        }
  
        setapplyjob({ ...applyjob, file });
        seterrors((prev) => ({ ...prev, file: "" }));
      }
    };

  const handleCaptcha = (value: string | null) =>{
    setapplyjob({
      ...applyjob, token: value
    });
    seterrors((prev) => ({ ...prev, token: "" }));
  }

  const handleCareerJob = async (e: FormEvent) => {
    e.preventDefault();
    let isValid = true;
    var pattern = /^[56789]\d{14}$/;
    // const fielderrors = {
    //   name: '', email: '', phone: '', highestQualification: '', selectPosition: '', totalExperience: '', currentCtc: '', file: '', expectedCtc: '',
    //   noticePeriod: '', keyskill: '', token: ''
    // };

    const fielderrors = {
      name: '', email: '', highestQualification: '', selectPosition: '', totalExperience: '', currentCtc: '', file: '', expectedCtc: '',
      noticePeriod: '', keyskill: '', token: ''
    };

    setapplyjob((prev) => ({
      ...prev,
      name: prev.name.trim(),
      email: prev.email.trim(),
      phone: prev.phone.trim(),
      currentLocation: prev.currentLocation.trim(),
      highestQualification: prev.highestQualification.trim(),
      selectPosition: prev.selectPosition.trim(),
      totalExperience: prev.totalExperience.trim(),
      currentCtc: prev.currentCtc.trim(),
      expectedCtc: prev.expectedCtc.trim(),
      noticePeriod: prev.noticePeriod.trim(),
      keyskill: prev.keyskill.trim(),
    }));
    
    if(!applyjob.name.trim()){
      fielderrors.name = 'Please Enter Your Name.'
      isValid = false;
    }

    if(applyjob.email == ''){
      fielderrors.email = 'Please Enter Your Email.'
      isValid = false;
    } else if (!/\S+@\S+\.\S+/.test(applyjob.email)) {
      fielderrors.email = "Invalid email format.";
      isValid = false;
    }

    // if(applyjob.phone == ''){
    //   fielderrors.phone = 'Please Enter Your Phone.'
    //   isValid = false;
    // } else if (applyjob.phone.length < 15) {
    //   fielderrors.phone = "Invalid phone number (15 digits only)";
    //   isValid = false;
    // } else if(!pattern.test(applyjob.phone)) {
    //   fielderrors.phone = "Invalid mobile number! It must start with 5, 6, 7, 8, or 9.";
    // }

    if(applyjob.highestQualification == ''){
      fielderrors.highestQualification = 'Please Select the Qualification.'
      isValid = false;
    }

    if(applyjob.selectPosition == ''){
      fielderrors.selectPosition = 'Please Select the Position.'
      isValid = false;
    }

    if(applyjob.totalExperience == ''){
      fielderrors.totalExperience = 'Please Enter Your Experience.'
      isValid = false;
    }

    if(!applyjob.file){
      fielderrors.file = 'Please Attach the File.'
      isValid = false;
    }

    if(!applyjob.currentCtc){
      fielderrors.currentCtc = 'Please Enter Your Current Ctc.'
      isValid = false;
    }
    
    if(!applyjob.expectedCtc){
      fielderrors.expectedCtc = 'Please Enter Your Expected Ctc.'
      isValid = false;
    }

    if(!applyjob.noticePeriod){
      fielderrors.noticePeriod = 'Please Enter Your Notice Period.'
      isValid = false;
    }

    if(!applyjob.keyskill){
      fielderrors.keyskill = 'Please Enter Your Skills.'
      isValid = false;
    }

    if(!applyjob.token){
      fielderrors.token = 'Please Validate the Captcha'
      isValid = false;
    }
  
    if(!isValid) {
      seterrors(fielderrors);
      return
    } 
    const formData = new FormData();
    formData.append('name', applyjob.name);
    formData.append('email', applyjob.email);
    formData.append('phone', applyjob.phone);
    formData.append('currentLocation', applyjob.currentLocation);
    formData.append('highestQualification', applyjob.highestQualification);
    formData.append('selectPosition', applyjob.selectPosition);
    formData.append('totalExperience', applyjob.totalExperience);
    formData.append('currentCtc', applyjob.currentCtc);
    formData.append('expectedCtc', applyjob.expectedCtc);
    formData.append('noticePeriod', applyjob.noticePeriod);
    formData.append('keyskill', applyjob.keyskill);
    if(applyjob.file) {
      formData.append('file', applyjob.file);
    }
  if (applyjob.token) {
    formData.append('token', applyjob.token); // Token exists and is appended.
  } else {
    console.error('Token is null or undefined. Cannot append to FormData.');
  }

    setLoading(true);

    try {

      const jobApplyApi = await fetch(process.env.NEXT_PUBLIC_JOBAPPLY_API!, {
        method: "POST",
        body: formData,
      });
      const result = await jobApplyApi.json();


      if (result.status === 'true') {
        setResponse(result);
        seterrors({
          name: '',
          email: '',
          //phone: '',
          highestQualification: '',
          selectPosition: '',
          totalExperience: '',
          file: '',
          currentCtc: '',
          expectedCtc: '',
          noticePeriod: '',
          keyskill: '',
          token: ''
        });
        setapplyjob({
          name: '',
          email: '',
          phone: '',
          currentLocation: '',
          highestQualification: '',
          selectPosition: '',
          totalExperience: '',
          currentCtc: '',
          expectedCtc: '',
          noticePeriod: '',
          keyskill: '',
          file: null,
          token: ''
        });
        if (fileInputRef.current) fileInputRef.current.value = "";
        setTimeout(() => {
          setResponse(null);
        }, 5000);
        const items = document.querySelectorAll('.form-field .form-label');
        items.forEach((item) => {
          if (item.classList.contains('label-view')) {
            item.classList.remove('label-view');
          }
        });
      } 
      else {
        setResponse(result);
        setTimeout(() => {
          setResponse(null);
        }, 5000)
      }
    } 
    catch (error) {
      setResponse({ status: "false", message: "Something went wrong. Please try again." });
      setTimeout(() => {
        setResponse(null);
      },5000)
    } finally {
      setLoading(false);
    }
  }

  const handleFocus = (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    seterrors((prev) => ({
      ...prev,
      [e.target.name]: '',
    }));
  };

  const handlelabel = (event: React.FormEvent<HTMLInputElement>) => {
    const inputElement = event.currentTarget;
    const fieldName = inputElement.getAttribute("name");
    const labelElement = document.querySelector(`label[data-name="${fieldName}"]`);
    if(labelElement){
      if(inputElement.value !== '') {
        labelElement?.classList.add('label-view');
      } else {
        labelElement?.classList.remove('label-view');
      }
    }
  }

  return (
    <>
      <div ref={ref} id="careerjob" className="career_job_apply_form ptb-100 bg-f1f8fb">
        <div className="section-title">
          <span className="sub-title">
            <Image
              src="/img/star-icon.png"
              alt="image"
              width={32}
              height={34}
            />
            Get in Touch
          </span>
          <h2>Apply For Job</h2>
        </div>
        <Container className="job_apply_container request_quote_container">
          <Form onSubmit={handleCareerJob} autoComplete="off" className="form-container">
            <Row className="d-flex flex-wrap">
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className={`form-field ${errors.name ? "is-invalid" : ""}`}>
                  <Form.Label data-name="name">Name</Form.Label>
                  <Form.Control type="text" placeholder="" name="name" value={applyjob.name} onChange={handle_fields} onFocus={handleFocus} onInput={handlelabel} autoComplete="off"/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.name}
                </Form.Control.Feedback>
              </Form.Group>
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className={`form-field ${errors.email ? "is-invalid" : ""}`}>
                  <Form.Label data-name="email">Email Address</Form.Label>
                  <Form.Control type="text" placeholder="" name="email" value={applyjob.email}  onChange={handle_fields} onFocus={handleFocus} onInput={handlelabel}  autoComplete="off"/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.email}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Row className="d-flex flex-wrap">
              {/* <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className={`form-field ${errors.phone ? "is-invalid" : ""}`}>
                  <Form.Label data-name="phone">Phone Number</Form.Label>
                  <Form.Control type="text" placeholder="" name="phone" maxLength={15} value={applyjob.phone} onChange={handle_fields} onFocus={handleFocus} onInput={handlelabel} autoComplete="off"/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.phone}
                </Form.Control.Feedback>
              </Form.Group> */}
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="phone">Phone Number</Form.Label>
                  <Form.Control type="text" placeholder="" name="phone" maxLength={15} value={applyjob.phone} onChange={handle_fields} onFocus={handleFocus} onInput={handlelabel} autoComplete="off"/>
                </ListGroup.Item>
              </Form.Group>

              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="currentLocation">Current Location</Form.Label>
                  <Form.Control type="text" placeholder="" name="currentLocation" value={applyjob.currentLocation} onChange={handle_fields} onInput={handlelabel} autoComplete="off"/>
                </ListGroup.Item>
              </Form.Group>
            </Row>
            <Row className="d-flex flex-wrap">
              <Form.Group className="col-12 col-sm-6 mb-3">
                <Form.Select
                  name="highestQualification"
                  value={applyjob.highestQualification}
                  onChange={handle_fields}
                  isInvalid={!!errors.highestQualification}
                  onFocus={handleFocus}
                >
                  <option value="">Select Highest Qualification</option>
                  <option value="B.Tech">B.Tech</option>
                  <option value="B.E">B.E</option>
                  <option value="M.Tech">M.Tech</option>
                  <option value="M.E">M.E</option>
                  <option value="BCA">BCA</option>
                  <option value="MCA">MCA</option>
                  <option value="B.Sc IT">B.Sc IT</option>
                  <option value="M.Sc IT">M.Sc IT</option>
                  <option value="Diploma in IT">Diploma in IT</option>
                  <option value="Other">Other</option>
                </Form.Select>
                <Form.Control.Feedback type="invalid">
                  {errors.highestQualification}
                </Form.Control.Feedback>
              </Form.Group>
              <Form.Group className="col-12 col-sm-6 mb-3">
                <Form.Select defaultValue="Select a position" name="selectPosition" isInvalid={!!errors.selectPosition} onChange={handle_fields} onFocus={handleFocus} value={applyjob.selectPosition}  >
                  <option value="">Select a position</option>
                  <option value="Fresher">Fresher</option>
                  <option value="PHP Trainee">PHP Trainee</option>
                  <option value="PHP Web Developer">PHP Web Developer</option>
                  <option value="Mobile Apps Developer">Mobile Apps Developer</option>
                  <option value="IOS Developer">IOS Developer</option>
                  <option value="Android Developer">Android Developer</option>
                  <option value="Magento Developer">Magento Developer</option>
                  <option value="Wordpress Developer">Wordpress Developer</option>
                  <option value="Web/Graphic Designer">Web/Graphic Designer</option>
                  {/* <option value="React.js Developer">React.js Developer</option>
                  <option value="Node.js Developer">Node.js Developer</option> 
                  <option value="QA Engineer">QA Engineer</option> */}
                  <option value="Business Development Executive/Manager">Business Development Executive/Manager</option>
                  <option value="Digital Marketing Executive/SEO">Digital Marketing Executive/SEO</option>
                  <option value="Others">Others</option>
                </Form.Select>
                <Form.Control.Feedback type="invalid">
                  {errors.selectPosition}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Row className="d-flex flex-wrap">
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="totalExperience">Total Experience</Form.Label>
                  <Form.Control type="text" placeholder="" name="totalExperience" value={applyjob.totalExperience} onChange={(e) => {
                  const { value } = e.target;
                  if (/^\d*$/.test(value) && value.length <= 10) {
                    handle_fields(e);
                  }
                }} inputMode="numeric" autoComplete="off" onFocus={handleFocus} onInput={handlelabel}/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.totalExperience}
                </Form.Control.Feedback>
              </Form.Group>
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="currentCtc">Current CTC</Form.Label>
                  <Form.Control type="text" placeholder="" name="currentCtc" value={applyjob.currentCtc} inputMode="numeric" onChange={(e) => {
                  const {value} = e.target;
                  if(/^\d*$/.test(value)){
                    handle_fields(e);
                  }
                }} autoComplete="off" onFocus={handleFocus} onInput={handlelabel}/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.currentCtc}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Row className="d-flex flex-wrap">
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="expectedCtc">Expected CTC</Form.Label>
                  <Form.Control type="text" placeholder="" name="expectedCtc" value={applyjob.expectedCtc} inputMode="numeric" onChange={(e) => {
                  const {value} = e.target;
                  if(/^\d*$/.test(value)){
                    handle_fields(e);
                  }
                }} autoComplete="off" onFocus={handleFocus} onInput={handlelabel} />
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.expectedCtc}
                </Form.Control.Feedback>
              </Form.Group>
              <Form.Group className="col-12 col-sm-6 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="noticePeriod">Notice Period</Form.Label>
                  <Form.Control type="text" placeholder="" name="noticePeriod" value={applyjob.noticePeriod} inputMode="numeric" onChange={(e) => {
                  const {value} = e.target;
                  if(/^\d*$/.test(value)){
                    handle_fields(e);
                  }
                }} autoComplete="off" onFocus={handleFocus} onInput={handlelabel}/>
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.noticePeriod}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Row>
              <Form.Group className="col-12 mb-3">
                <ListGroup.Item className="form-field">
                  <Form.Label data-name="keyskill">Key Skill</Form.Label>
                  <Form.Control
                    as="textarea"
                    placeholder=""
                    name="keyskill"
                    value={applyjob.keyskill || ''} 
                    onChange={handle_fields}
                    style={{ height: '150px' }}
                    autoComplete="off"
                    onFocus={handleFocus}
                    onInput={handlelabel}
                  />
                </ListGroup.Item>
                <Form.Control.Feedback type="invalid">
                  {errors.keyskill}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Row className="mb-3">
              <Form.Group className="col-12 col-sm-6 mb-3 formFile">
                <div className="file-upload bg-white">
                  <input type="file" name="file" accept=".pdf, .doc, .docx" onChange={handle_fields_file} ref={fileInputRef} />
                </div>
                <p className="file_format_text mb-0">Supports only PDF / DOC (UP TO 5MB)</p>
                <Form.Control.Feedback type="invalid">
                  {errors.file}
                </Form.Control.Feedback>
              </Form.Group>
            </Row>
            <Form.Group className="captcha">
              <ReCAPTCHA
                sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY!}
                onChange={handleCaptcha}
              />
              {errors.token ? (
                <Form.Control.Feedback type="invalid">
                  {errors.token}
                </Form.Control.Feedback>
              ) : null}
            </Form.Group>
            <Button variant="primary" type="submit" className={`${loading ? "default-btn loading": "default-btn"}`}>
              {loading ? 'Submitting...' : 'Submit'}
              <span></span>
            </Button>
            {response && (
              response.status === "true" ? (
                <Alert variant="success" className="mt-3 mb-0">
                  {response.message}
                </Alert>
              ) : (
                <Alert variant="danger" className="mt-3 mb-0">
                  {response.message}
                </Alert>
              )
            )}
          </Form>
        </Container>

        <div className="vector-shape7">
            <Image
              src="/img/shape/vector-shape7.png"
              alt="image"
              width={955}
              height={359}
            />
          </div>
          <div className="vector-shape8">
            <Image
              src="/img/shape/vector-shape8.png"
              alt="image"
              width={536}
              height={506}
            />
          </div>
      </div>  
    </>
  );
})

export default JobApply;