import React, { useState, useEffect } from 'react'
import { CloudDownload } from '../../../assets/icon';

const Bulk = () => {
  const BASE_URL = process.env.REACT_APP_BASE_URL
  const API_KEY = process.env.REACT_APP_API_KEY

  const [selectedImageName, setSelectedImageName] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [applicationId, setApplicationId] = useState('');
  const [applicationIds, setApplicationIds] = useState([]);
  const [isSelectOpen, setIsSelectOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768); // Set mobile state based on window width
    };

    handleResize(); // Initial check on component mount
    window.addEventListener('resize', handleResize); // Listen for resize events

    return () => {
      window.removeEventListener('resize', handleResize); // Cleanup on component unmount
    };
  }, []);

  useEffect(() => {
    const fetchApplicationIds = async () => {
      try {
        const url = `${BASE_URL}/application/list`;
        console.log('Fetching URL:', url); // Log the URL
        
        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) {
          const ids = data.details.data.map(app => app.id);
          console.log('Application Id: ' + ids); // Log the IDs
          setApplicationIds(data.details.data); // Update state with the fetched data
        } else {
          console.error('Failed to fetch data:', data.details.message);
        }
      } catch (error) {
        console.error('Error fetching application IDs:', error);
      }
    };

    fetchApplicationIds();
  }, []);

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

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

  const handleFileUpload = (event) => {
    const file = event.target.files[0];

    if (file && (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg')) {
      setSelectedImageName(file.name);
      setErrorMessage('');
    } else {
      alert('Please upload a valid image file (JPG, JPEG, PNG).');
    }
  };

  return (
    <div style={isMobile ? styles.containerMobile : styles.container}>
      <div style={{ ...styles.statusBox, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img src={CloudDownload} alt="Download Icon" style={styles.iconStyle} />
          <div style={{ marginLeft: '10px' }}>
            <h3 style={styles.statusTitle}>Check Our Service Status</h3>
            <p style={{ margin: '0' }}>
              Access pre-approved message templates designed for various purposes, including customer support, appointment reminders, order updates, and more.
              Simplify your communication by using these ready-to-go formats.
            </p>
          </div>
        </div>
        <a href="#" style={{ ...styles.buttonStyle, backgroundColor: '#fff', color: '#0542cc', display: 'flex', alignItems: 'center', padding: '10px 15px', borderRadius: '5px' }}>
          <i className="fas fa-download" style={{ marginRight: '5px' }}></i>
          Download Template
        </a>
      </div>

      <div style={styles.formContainer}>
        <div
          style={{
            ...styles.formRow,
            flexDirection: isMobile ? 'column' : 'row', // Set to column in mobile mode
          }}
        >
          <div style={{ ...styles.formColumn, marginRight: isMobile ? '0' : '20px' }}>
            <label htmlFor="appId" style={styles.label}>Application ID</label>
            <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>

            <label htmlFor="messageInfo" style={styles.label}>Message Info</label>
            <textarea 
              id="messageInfo" 
              rows="5" 
              placeholder="Type your message here..." 
              style={styles.textarea}
            />
            <p style={styles.charCounter}>Character: 0 (Max: 459), SMS Count: 0</p>
          </div>

          <div
            style={{
              ...styles.uploadBox,
              marginBottom: isMobile ? '20px' : '0', // Add margin for spacing in mobile
            }}
          >
            <p style={{ fontWeight: 'bold', color: '#666' }}>Upload Template</p>
            <div
              style={styles.uploadArea}
              onClick={() => document.getElementById('fileUpload').click()} 
            >
              <i className="fas fa-cloud-upload-alt" style={styles.uploadIcon}></i>
              <p style={styles.uploadText}>Drag and Drop Here</p>
              <p>Or</p>
              <button style={styles.browseButton}>Browse</button>
              <p style={styles.charCounter}>Accepted file: .csv<br />Maximum file size: 5MB</p>
            </div>
            <input
              type="file"
              id="fileUpload"
              style={{ display: 'none' }}
              accept=".csv"
              onChange={handleFileUpload}
            />
          </div>
        </div>

        <button style={styles.sendButton}>Send Bulk SMS</button>
      </div>
    </div>
  );
};

export default Bulk;


const styles = {
  container: {
    padding: '20px',
    fontFamily: 'Arial, sans-serif',
  },
  containerMobile: {
    padding: '10px',
    fontFamily: 'Arial, sans-serif',
  },
  statusBox: {
    padding: '20px',
    border: '0.1px solid rgba(0, 0, 0, 0.2)',
    borderLeft: '4px solid #0542cc',
    borderRadius: '10px',
    width: '100%',
    marginBottom: '1rem',
  },
  iconStyle: {
    width: '36px',
    height: '36px',
  },
  buttonStyle: {
    textDecoration: 'none',
    border: 'none',
    cursor: 'pointer',
    transition: 'background-color 0.3s',
    padding: '10px 15px',
    borderRadius: '5px',
  },
  statusTitle: {
    color: '#0066cc',
    fontWeight: '600',
  },
  formContainer: {
    padding: '20px',
    border: '0.1px solid rgba(0, 0, 0, 0.2)',
    borderLeft: '4px solid #0542cc',
    borderRadius: '10px',
    width: '100%',
    marginBottom: '1rem',
  },
  formRow: {
    display: 'flex',
    justifyContent: 'space-between',
    flexWrap: 'wrap', // Allow wrapping for smaller screens
  },
  formColumn: {
    flex: 1,
    marginRight: '20px',
    marginBottom: '20px', // Add spacing between rows in mobile
  },
  uploadBox: {
    flex: 1,
    textAlign: 'center',
    padding: '20px',
    marginBottom: '1rem',
  },
  label: {
    fontWeight: 'bold',
    display: 'block',
    margin: '0.5rem 0',
  },
  select: {
    width: '100%',
    padding: '8px',
    borderRadius: '4px',
    border: '1px solid #ccc',
  },
  textarea: {
    width: '100%',
    padding: '8px',
    borderRadius: '4px',
    border: '1px solid #ccc',
    marginTop: '10px',
    height: '150px', // Adjust height for mobile
  },
  uploadArea: {
    backgroundColor: '#e6f2ff',
    cursor: 'pointer',
    padding: '15px',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    border: '1px solid #ced4da',
    borderRadius: '0.25rem',
    height: 'auto', // Let content dictate height
    minHeight: '200px',
  },
  uploadIcon: {
    fontSize: '36px',
    color: '#0542cc',
    marginBottom: '7px',
  },
  uploadText: {
    color: '#1f2d3d',
    fontWeight: '400',
    fontSize: '14px',
    lineHeight: '13px',
    textAlign: 'center',
  },
  browseButton: {
    color: '#0066cc',
    border: 'none',
    background: 'none',
    cursor: 'pointer',
    marginTop: '5px',
  },
  charCounter: {
    fontSize: '12px',
    color: '#888',
    marginTop: '5px',
  },
  sendButton: {
    backgroundColor: '#0066cc',
    color: 'white',
    padding: '10px 20px',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    marginTop: '20px',
    width: '100%', // Full width for mobile
    maxWidth: '200px', // Limited width for larger screens
    alignSelf: 'center',
  },
};

