import React, { useState, useRef, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown, faChevronLeft, faCloudUploadAlt, faTimes, faImage } from '@fortawesome/free-solid-svg-icons';
import { FileUploader } from 'react-drag-drop-files';


const BASE_URL = process.env.REACT_APP_BASE_URL
const API_KEY = process.env.REACT_APP_API_KEY

const fileTypes = ['JPG', 'JPEG'];

const CustomLabel = ({ children, ...props }) => {
    return <label {...props}>{children}</label>;
};


const SingleMessage = ({ isSelectOpen, handleFocus, handleBlur }) => {
  const [applicationId, setApplicationId] = useState('');
  const [phoneId, setPhoneId] = useState('');
  const [variable_1, setVariable_1] = useState('');
  const [templateName, setTemplateName] = useState('');
  const [variable_2, setVariable_2] = useState('');
  const [preview, setPreview] = useState(null);
  const [errors, setErrors] = useState({});
  const [applicationIds, setApplicationIds] = useState([]);  
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
      const fetchApplicationIds = async () => {
          setIsLoading(true);
          const url = `${BASE_URL}/application/list`;
          try {
              const response = await fetch(url, {
                  method: 'GET',
                  headers: {
                      'accept': 'application/json',
                      'x-api-key': API_KEY,
                  },
              });

              const data = await response.json();
              if (data.status_code === 200) {
                  setApplicationIds(data.details.data);
              } else {
                  console.error('Failed to fetch data:', data.details.message);
              }
          } catch (error) {
              console.error('Error fetching application IDs:', error);
          } finally {
              setIsLoading(false);
          }
      };

      fetchApplicationIds();
  }, []);

  const handleValidation = () => {
      const newErrors = {};
      if (!applicationId) newErrors.applicationId = "Applications ID is required.";
      if (!phoneId) newErrors.phoneId = "Phone Number is required.";
      if (!variable_1) newErrors.variable_1 = "Variable 1 is required.";
      if (!templateName) newErrors.templateName = "Template Name is required.";
      if (!variable_2) newErrors.variable_2 = "Variable 2 is required.";
      
      setErrors(newErrors);
      return Object.keys(newErrors).length === 0; // Return true if no errors
  };

  const handleButtonClick = () => {
      if (handleValidation()) {
          const formattedPhoneId = `08${phoneId}`;

          // Log the input data
          console.log({
              applicationId,
              formattedPhoneId,
              variable_1,
              templateName,
              variable_2
          });

          setPreview({
              message: `Thank you for RSVP, ${variable_1}! We're excited to see you soon.`,
              details: `Check the details and mark on your calendar:\nDate: Thursday, October 10, 2024 | 6:00 PM - 9:00 PM\nLocation: Stories SCBD, South Jakarta, Fairground Building, SCBD Lot No.14`
          });
      }
  };

  return (
      <div>
          {/* Inject keyframes for the spinner */}
          <style>
              {`
              @keyframes spin {
                  0% { transform: rotate(0deg); }
                  100% { transform: rotate(360deg); }
              }
              `}
          </style>

          {isLoading && (
              <div style={styles.loadingOverlay}>
                  <div style={styles.spinner}></div>
              </div>
          )}
          <div className="form-group row align-items-center">
              <div className="col-md-6">
                  <div style={styles.selectWrapper}>
                      <select
                          id="applicationId"
                          className="form-control"
                          style={styles.select}
                          value={applicationId}
                          onChange={(e) => setApplicationId(e.target.value)}
                          onFocus={handleFocus}
                          onBlur={handleBlur}
                      >
                          <option value="">Select Application ID</option>
                          {applicationIds.map((app) => (
                              <option key={app.id} value={app.id}>
                                  {app.name}
                              </option>
                          ))}
                      </select>
                      <FontAwesomeIcon
                          icon={isSelectOpen ? faChevronDown : faChevronLeft}
                          style={styles.chevronIcon}
                      />
                  </div>
                  {errors.applicationId && <p className="text-danger">{errors.applicationId}</p>}
              </div>
              <div className="col-md-6">
                  <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', margin: '0', marginTop: '8px' }}>
                      Remaining Quota
                  </p>
                  <div style={styles.remainingQuota}>
                      <span style={styles.quotaText}>0</span>
                      <span style={styles.timesText}>(times)</span>
                  </div>
              </div>
          </div>

          <div className="form-group row align-items-center mt-4">
              <div className="col-md-6">
                  <div className="input-group">
                      <span className="input-group-prepend">
                          <span className="input-group-text">+62</span>
                      </span>
                      <input
                          type="text"
                          id="phoneId"
                          className="form-control"
                          placeholder="Phone Number"
                          value={phoneId}
                          onChange={(e) => {
                              const value = e.target.value;
                              // Allow only digits and enforce length constraints
                              if (/^\d*$/.test(value) && value.length <= 14) {
                                  setPhoneId(value);
                              }
                          }}
                          minLength={9}
                          maxLength={14}
                      />
                  </div>
                  {errors.phoneId && <p className="text-danger">{errors.phoneId}</p>}
              </div>
              <div className="col-md-6">
                  <div className="input-group">                        
                      <input
                          type="text"
                          id="variable_1"
                          className="form-control"
                          placeholder="Variables 1"
                          value={variable_1}
                          onChange={(e) => setVariable_1(e.target.value)}
                          maxLength={15}
                      />
                  </div>
                  {errors.variable_1 && <p className="text-danger">{errors.variable_1}</p>}
              </div>
          </div>

          <div className="form-group row align-items-center mt-4">
              <div className="col-md-6">
                  <div className="input-group">                        
                      <input
                          type="text"
                          id="templateName"
                          className="form-control"
                          placeholder="Template Name"
                          value={templateName}
                          onChange={(e) => setTemplateName(e.target.value)}
                          maxLength={15}
                      />
                  </div>
                  {errors.templateName && <p className="text-danger">{errors.templateName}</p>}
              </div>
              <div className="col-md-6">
                  <div className="input-group">                        
                      <input
                          type="text"
                          id="variable_2"
                          className="form-control"
                          placeholder="Variables 2"
                          value={variable_2}
                          onChange={(e) => setVariable_2(e.target.value)}
                          maxLength={15}
                      />
                  </div>
                  {errors.variable_2 && <p className="text-danger">{errors.variable_2}</p>}
              </div>
          </div>

          <div style={styles.submitButton}>
              <button onClick={handleButtonClick} className="btn d-flex justify-content-center align-items-center me-2" style={{ backgroundColor: '#0542CC' }}>
                  <p className="text-white mb-0">Make SMS Demo</p>
              </button>
          </div>

          {/* Preview Section */}
          {preview && (
              <div style={styles.preview}>
                  <div style={styles.waMessagePreview}>
                      <p><strong>[Sips & Synergy Executive]</strong></p>
                      <p>{preview.message}</p>
                      <p>{preview.details}</p>
                      <button className="btn btn-primary mt-3">Maps Event Location</button>
                  </div>
              </div>
          )}
      </div>
  );
};

const BulkMessage = ({ isSelectOpen, handleFocus, handleBlur, handleClick, onImageUpload }) => {
  const [applicationId, setApplicationId] = useState('');
  const [templateName, setTemplateName] = useState('');
  const [imageData, setImageData] = useState(null);
  const [selectedImageName, setSelectedImageName] = useState('');
  const [errors, setErrors] = useState({});
  const fileInputRef = useRef(null);
  const [applicationIds, setApplicationIds] = useState([]);  
  const [isLoading, setIsLoading] = useState(false);


  useEffect(() => {
      const fetchApplicationIds = async () => {
          setIsLoading(true);
          const url = `${BASE_URL}/application/list`;
          try {
              const response = await fetch(url, {
                  method: 'GET',
                  headers: {
                      'accept': 'application/json',
                      'x-api-key': API_KEY,
                  },
              });

              const data = await response.json();
              if (data.status_code === 200) {
                  setApplicationIds(data.details.data);
              } else {
                  console.error('Failed to fetch data:', data.details.message);
              }
          } catch (error) {
              console.error('Error fetching application IDs:', error);
          } finally {
              setIsLoading(false);
          }
      };

      fetchApplicationIds();
  }, []);

  const handleValidation = () => {
      const newErrors = {};
      if (!applicationId) newErrors.applicationId = "Application ID is required.";
      if (!templateName) newErrors.templateName = "Template Name is required.";
      if (!imageData) newErrors.imageData = "Image is required.";
      
      setErrors(newErrors);
      return Object.keys(newErrors).length === 0;
  };

  const handleImageUpload = (file) => {
      if (file) {
          setImageData(file);
          setSelectedImageName(file.name);
          if (onImageUpload) {
              onImageUpload(file);
          }
      } else {
          setErrors((prevErrors) => ({
              ...prevErrors,
              imageData: "Image upload failed."
          }));
      }
  };

  const handleButtonClick = () => {
      if (handleValidation()) {
          handleClick();
          console.log('Form Data:', {
              applicationId,
              templateName,
              imageData
          });
      } else {
          console.log('Validation errors:', errors);
      }
  };

  const handleImageCancel = () => {
      setImageData(null);
      setSelectedImageName('');
      if (fileInputRef.current) {
          fileInputRef.current.value = '';
      }
  };

  return (
      <div>
          {/* Inject keyframes for the spinner */}
          <style>
              {`
              @keyframes spin {
                  0% { transform: rotate(0deg); }
                  100% { transform: rotate(360deg); }
              }
              `}
          </style>


          <div className="form-group row align-items-center">
              <div className="col-md-6">
                  <div style={styles.selectWrapper}>
                      <select
                          id="applicationId"
                          className="form-control"
                          style={styles.select}
                          value={applicationId}
                          onChange={(e) => setApplicationId(e.target.value)}
                          onFocus={handleFocus}
                          onBlur={handleBlur}
                      >
                          <option value="">Select Application ID</option>
                          {applicationIds.map((app) => (
                              <option key={app.id} value={app.id}>
                                  {app.name}
                              </option>
                          ))}
                      </select>
                      <FontAwesomeIcon
                          icon={isSelectOpen ? faChevronDown : faChevronLeft}
                          style={styles.chevronIcon}
                      />
                  </div>
                  {errors.applicationId && <p className="text-danger">{errors.applicationId}</p>}
              </div>
              <div className="col-md-6">
                  <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', margin: '0', marginTop: '8px' }}>
                      Remaining Quota
                  </p>
                  <div style={styles.remainingQuota}>
                      <span style={styles.quotaText}>0</span>
                      <span style={styles.timesText}>(times)</span>
                  </div>
              </div>
          </div>

          <div className="form-group row align-items-center mt-4">
              <div className="col-md-6">
                  <div className="input-group">                        
                      <input
                          type="text"
                          id="templateName"
                          className="form-control"
                          placeholder="Template Name"
                          value={templateName}
                          onChange={(e) => setTemplateName(e.target.value)}
                          maxLength={15}
                      />
                  </div>
                  {errors.templateName && <p className="text-danger">{errors.templateName}</p>}
              </div>
          </div>

          {/* Upload Section */}
          <div className='col-md-6'>
              <div className="row form-group mt-4">
                  <CustomLabel htmlFor="uploadPhoto" style={styles.customLabel}>
                      Upload Face Photo
                  </CustomLabel>
                  <FileUploader
                      handleChange={handleImageUpload}
                      name="file"
                      types={fileTypes}
                      multiple={false}
                      onDrop={(files) => {
                          // Ensure files array is not empty
                          if (files.length > 0) {
                              handleImageUpload(files[0]);
                          }
                      }}
                      children={
                          <div style={styles.uploadArea}>
                              <FontAwesomeIcon icon={faCloudUploadAlt} style={styles.uploadIcon} />
                              <p style={styles.uploadText}>Drag and Drop Here</p>
                              <p>Or</p>
                              <a href="#" onClick={() => fileInputRef.current.click()}>Browse</a>
                              <p className="text-muted">Recommended size: 300x300 (Max File Size: 2MB)</p>
                              <p className="text-muted">Supported file types: JPG, JPEG</p>
                          </div>
                      }
                  />
                  <input
                      type="file"
                      id="fileUpload"
                      ref={fileInputRef}
                      style={{ display: 'none' }}
                      accept="image/jpeg, image/jpg"
                      onChange={e => {
                          if (e.target.files.length > 0) {
                              handleImageUpload(e.target.files[0]);
                          }
                      }}
                  />
                  {errors.imageData && <small style={{ color: 'red' }}>{errors.imageData}</small>}
              </div>
          </div>

          {/* Display uploaded image name */}
          {selectedImageName && (
              <div className="col-md-6 mt-4">
                  <div style={styles.fileWrapper}>
                      <FontAwesomeIcon icon={faImage} style={styles.imageIcon} />
                      <div style={{ marginRight: '18rem', marginTop: '0.2rem' }}>
                          <h5>Uploaded File:</h5>
                          <p>{selectedImageName}</p>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                          <button
                              style={{ background: 'none', border: 'none', cursor: 'pointer' }}
                              onClick={handleImageCancel}
                              aria-label="Remove uploaded image"
                          >
                              <FontAwesomeIcon
                                  icon={faTimes}
                                  style={styles.closeIcon}
                              />
                          </button>
                      </div>
                  </div>
              </div>
          )}

          <div style={styles.selectWrapper}>
              <div style={styles.submitButton}>
                  <button onClick={handleButtonClick} className="btn d-flex justify-content-center align-items-center me-2" style={{ backgroundColor: '#0542CC' }}>
                      <p className="text-white mb-0">Make SMS Demo</p>
                  </button>
              </div>
          </div>
      </div>
  );
};

const Message = () => {
    const [isSelectOpen, setIsSelectOpen] = useState(false);
    const [activeTab, setActiveTab] = useState('single');
    const fileInputRef = useRef(null);

    const handleFocus = () => {
        setIsSelectOpen(true);
    };

    const handleBlur = () => {
        setIsSelectOpen(false);
    };

    const handleClick = async () => {
        console.log('Make SMS Demo');
    };

    const handleImageUpload = (event) => {
        const file = event.target.files[0];
        if (file && (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg')) {
            console.log('File uploaded:', file.name); // Handle the file upload
        } else {
            alert('Please upload a valid image file (JPG, JPEG).');
        }
    };

    return (
        <div>
            {/* Tab buttons */}
            <div>
                <button
                    onClick={() => setActiveTab('single')}
                    style={activeTab === 'single' ? styles.tabButton : styles.tabInactiveButton}
                >
                    Single Message
                </button>
                <button
                    onClick={() => setActiveTab('bulk')}
                    style={activeTab === 'bulk' ? styles.tabButton : styles.tabInactiveButton}
                >
                    Bulk Message
                </button>
            </div>

            {/* Conditional content based on active tab */}
            {activeTab === 'single' && <SingleMessage 
                isSelectOpen={isSelectOpen} 
                handleFocus={handleFocus} 
                handleBlur={handleBlur} 
                handleClick={handleClick} 
            />}
            {activeTab === 'bulk' && <BulkMessage 
                isSelectOpen={isSelectOpen} 
                handleFocus={handleFocus} 
                handleBlur={handleBlur} 
                handleClick={handleClick} 
                handleImageUpload={handleImageUpload} 
                fileInputRef={fileInputRef} 
            />}
        </div>
    );
};


export default Message;

const styles = {
    selectWrapper: {
        position: 'relative',
        marginTop: '0',
    },
    select: {
        width: '100%',
        paddingRight: '30px',
        flex: 1,
        fontSize: '16px',
        outline: 'none',
    },
    chevronIcon: {
        position: 'absolute',
        right: '10px',
        top: '50%',
        transform: 'translateY(-50%)',
        pointerEvents: 'none',
    },
    remainingQuota: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: '4px',
    },
    quotaText: {
        fontSize: '40px',
        color: '#0542cc',
        fontWeight: '600',
    },
    timesText: {
        marginLeft: '8px',
        verticalAlign: 'super',
        fontSize: '20px',
    },
    tabButton: {
        display: 'inline-block',
        padding: '10px 20px',
        fontSize: '16px',
        cursor: 'pointer',
        backgroundColor: '#0542cc',
        color: '#fff',
        border: 'none',
        marginRight: '10px',
        borderRadius: '7px'
    },
    tabInactiveButton: {
        display: 'inline-block',
        padding: '10px 20px',
        fontSize: '16px',
        cursor: 'pointer',
        backgroundColor: '#fff',
        color: '#0542cc',
        border: '1px solid #0542cc',
        marginRight: '10px',
        borderRadius: '7px'
    },
    submitButton: {
        marginLeft: 'auto',
        marginTop: '1rem',
        textAlign: 'start',
        position: 'relative',
        zIndex: 1,
    },
    uploadArea: {
        backgroundColor: '#e6f2ff',
        height: '250px',
        cursor: 'pointer',
        paddingTop: '22px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        border: '1px solid #ced4da',
        borderRadius: '0.25rem',
    },
    uploadIcon: {
        fontSize: '40px',
        color: '#0542cc',
        marginBottom: '7px',
    },
    uploadText: {
        color: '#1f2d3d',
        fontWeight: '400',
        fontSize: '16px',
        lineHeight: '13px',
    },
    uploadError: {
        color: 'red',
    },
    waMessagePreview: {
        backgroundColor: '#F8F9FA',
        padding: '15px',
        borderRadius: '8px',
        border: '1px solid #dcdcdc',
        marginBottom: '20px',
    },
    preview: {
        marginTop: '20px',
    },
    // Bulk Message
    uploadArea: {
        backgroundColor: '#e6f2ff',
        height: '250px',
        cursor: 'pointer',
        marginTop: '1rem',
        paddingTop: '22px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        border: '1px solid #ced4da',
        borderRadius: '0.25rem',
    },
    uploadIcon: {
        fontSize: '40px',
        color: '#0542cc',
        marginBottom: '7px',
    },
    uploadText: {
        color: '#1f2d3d',
        fontWeight: '400',
        fontSize: '16px',
        lineHeight: '13px',
    },
    fileWrapper: {
        backgroundColor: '#fff',
        border: '0.2px solid gray',
        padding: '15px 0 0 17px',
        borderRadius: '5px',
        position: 'relative',
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        justifyContent: 'space-between',
    },        
    imageIcon: {
        color: '#0542cc',
        fontSize: '24px',
        marginBottom: '1rem'
    },
    closeIcon: {
        color: 'red',
        cursor: 'pointer',
        fontSize: '26px',
        marginRight: '1rem',
        marginBottom: '1rem'
    },
    customLabel: {
        fontWeight: 600,
        fontSize: '14px',
        color: '#212529'
    },
    submitButton: {
        marginTop: '20px',
    },
};
