import React, { useState, useRef, useEffect } from 'react';
import Select from 'react-select'
import { ServerDownAnimation } from '../../../../assets/images';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImage, faTimes, faCloudUploadAlt } from '@fortawesome/free-solid-svg-icons';


const BASE_URL = process.env.REACT_APP_BASE_URL;
const API_KEY = process.env.REACT_APP_API_KEY;
const fileTypes = ["image/jpeg", "image/png"];

const SingleMessage = ({ applicationId, setApplicationId, messageId, setMessageId, phoneId, setPhoneId, isLoading, setIsLoading, isMobile, handleClick }) => {
  const [inputValueApplication, setInputValueApplication] = useState('');
  const [selectedQuota, setSelectedQuota] = useState(0);
  const [applicationIds, setApplicationIds] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');
  const [isServer, setIsServer] = useState(true);

  const applicationOptions = applicationIds.map(app => ({
    value: app.id,   // This is what will be sent when an option is selected
    label: app.name  // This is what will be displayed in the dropdown
  }));

  const handleInputChangeApplication = (inputValue) => {
    setInputValueApplication(inputValue);
  };

  const handleApplicationChange = (selectedOption) => {
    const selectedId = selectedOption.value;
    const selectedApp = applicationIds.find(app => app.id === parseInt(selectedId));

    setApplicationId(selectedOption ? selectedOption.value : '');

    if (selectedApp) {
      setSelectedQuota(selectedApp.quota);
    }
  };

  useEffect(() => {
    const fetchApplicationIds = async () => {
      try {
        setIsLoading(true);
        const response = await fetch(`${BASE_URL}/application/list`, {
          method: 'GET',
          headers: {
            'accept': 'application/json',
            'x-api-key': API_KEY,
          },
        });
  
        if (!response.ok) {
          throw new Error('Failed to fetch application IDs');
        }
  
        const data = await response.json();
        console.log('Response Data:', data);
  
        if (data.status_code === 200) {
          setApplicationIds(data.details.data);
          setIsServer(true);
        } else {
          setIsServer(false);
          throw new Error(data.details.message || 'Failed to fetch application IDs');
        }
      } catch (error) {
        setErrorMessage(error.message || 'Error fetching application IDs');
        setIsServer(false);
      } finally {
        setIsLoading(false);
      }
    };
  
    fetchApplicationIds();
  }, []);
  
  // Logic to handle the server down state should be inside the render logic, not around useEffect
  if (!isServer) {
    return (
      <div style={{ textAlign: 'center', marginTop: '50px' }}>
        <img
          src={ServerDownAnimation}
          alt="Server Down Animation"
          style={{ width: '18rem', height: '18rem', marginBottom: '20px' }}
        />
        <h2 style={{ color: 'red' }}>Server tidak dapat diakses</h2>
        <p>{errorMessage || 'Silakan periksa koneksi internet Anda atau coba lagi nanti.'}</p>
        <button
          onClick={() => window.location.reload()}
          style={{
            padding: '10px 20px',
            backgroundColor: '#0542cc',
            color: '#fff',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
          }}
        >
          Coba Lagi
        </button>
      </div>
    );
  }  

  return (
    <div style={isMobile ? styles.mobileContainer : styles.container}>
      {/* Select Application ID */}
      <div className="form-group row align-items-center">
        <div className="col-md-6">
          <div style={styles.selectWrapper}>
            <Select
              id="applicationId"
              value={applicationOptions.find(option => option.value === applicationId)}
              onChange={handleApplicationChange}
              options={applicationOptions}
              placeholder="Select Application ID"
              isSearchable
              menuPortalTarget={document.body}
              menuPlacement="auto"
              inputValue={inputValueApplication}
              onInputChange={handleInputChangeApplication} // Limit input length for Application ID
            />
          </div>
        </div>

        <div className="col-md-6" style={{ marginTop: !isMobile ? '0' : '2vh' }}>
          <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', margin: '0', marginTop: '8px' }}>
              Remaining Quota
          </p>
          <div style={styles.remainingQuota}>
            <span style={styles.quotaText}>{selectedQuota}</span>
            <span style={styles.timesText}>(times)</span>
          </div>
        </div>
      </div>

      {/* Message Area */}
      <div className="form-group row align-items-center mt-4">
          <div className="col-md-6">
            <textarea
                id="messageId"
                className="form-control"
                style={{ ...styles.select, height: '200px', resize: 'none' }}
                value={messageId}
                onChange={(e) => setMessageId(e.target.value)}
                placeholder="Message Info"
            />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '8px' }}>
                <p style={{ margin: 0 }}>Character: 0 (Max. 459), SMS Count: 0</p>
            </div>
          </div>
          <div className="col-md-6">
            <div className="input-group" style={{ marginTop: !isMobile ? '-11.8vh' : '2vh' }}>
                <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) => setPhoneId(e.target.value)}
                />
            </div>
          </div>
      </div>

      {/* Submit Button */}
      <div style={styles.submitButton}>
          <button onClick={handleClick} 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>
  );
};

const BulkMessage = ({ applicationId, setApplicationId, messageId, setMessageId, isMobile, isLoading, setIsLoading, handleClick }) => {
  const fileInputRef = useRef(null);
  const [selectedImageName, setSelectedImageName] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [inputValueApplication, setInputValueApplication] = useState('');
  const [applicationIds, setApplicationIds] = useState([]);
  const [selectedQuota, setSelectedQuota] = useState(0);
  const [isServer, setIsServer] = useState(true);
  const [file, setFile] = useState(null);
  const [imageError, setImageError] = useState('');
  const [validationErrors, setValidationErrors] = useState({
    applicationId: '',
    file: ''
  });
  const uploadAreaHeight = isMobile ? '50svh' : '25svh';

  const applicationOptions = applicationIds.map(app => ({
    value: app.id,   // This is what will be sent when an option is selected
    label: app.name  // This is what will be displayed in the dropdown
  }));

  const handleInputChangeApplication = (inputValue) => {
    setInputValueApplication(inputValue);
  };

  const handleApplicationChange = (selectedOption) => {
    const selectedId = selectedOption.value;
    const selectedApp = applicationIds.find(app => app.id === parseInt(selectedId));

    setApplicationId(selectedOption ? selectedOption.value : '');

    if (selectedApp) {
      setSelectedQuota(selectedApp.quota);
    }
  };

  const handleFileDrop = (files) => {
    if (files && files[0]) {
        handleImageUpload(files[0]);
    } else {
        console.error('No valid files dropped');
    }
  };

  const handleImageUpload = (file) => {
    setFile(file);
    setSelectedImageName(file.name);

    // Validate file type
    if (!fileTypes.includes(file.type)) {
        setImageError('Invalid file type. Only JPG, JPEG, and PNG are allowed.');
    } else if (file.size > 2 * 1024 * 1024) { // Max 2MB
        setImageError('File size exceeds 2MB.');
    } else {
        setImageError('');
    }
  };

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

  useEffect(() => {
    const fetchApplicationIds = async () => {
      try {
        setIsLoading(true);
        const response = await fetch(`${BASE_URL}/application/list`, {
          method: 'GET',
          headers: {
            'accept': 'application/json',
            'x-api-key': API_KEY,
          },
        });
  
        if (!response.ok) {
          throw new Error('Failed to fetch application IDs');
        }
  
        const data = await response.json();
        console.log('Response Data:', data);
  
        if (data.status_code === 200) {
          setApplicationIds(data.details.data);
          setIsServer(true);
        } else {
          setIsServer(false);
          throw new Error(data.details.message || 'Failed to fetch application IDs');
        }
      } catch (error) {
        setErrorMessage(error.message || 'Error fetching application IDs');
        setIsServer(false);
      } finally {
        setIsLoading(false);
      }
    };
  
    fetchApplicationIds();
  }, []);
  
  // Conditional rendering should still be handled here, not affecting hook order
  if (!isServer) {
    return (
      <div style={{ textAlign: 'center', marginTop: '50px' }}>
        <img
          src={ServerDownAnimation}
          alt="Server Down Animation"
          style={{ width: '18rem', height: '18rem', marginBottom: '20px' }}
        />
        <h2 style={{ color: 'red' }}>Server tidak dapat diakses</h2>
        <p>{errorMessage || 'Silakan periksa koneksi internet Anda atau coba lagi nanti.'}</p>
        <button
          onClick={() => window.location.reload()}
          style={{
            padding: '10px 20px',
            backgroundColor: '#0542cc',
            color: '#fff',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
          }}
        >
          Coba Lagi
        </button>
      </div>
    );
  }
  
  const CustomLabel = ({ overRide, children, ...props }) => {
    return <label {...props}>{children}</label>;
  };

  const formatFileSize = (sizeInBytes) => {
    if (sizeInBytes < 1024) {
        return `${sizeInBytes} bytes`; // Jika ukuran lebih kecil dari 1 KB
    } else if (sizeInBytes < 1048576) {
        return `${(sizeInBytes / 1024).toFixed(2)} KB`; // Jika ukuran lebih kecil dari 1 MB
    } else {
        return `${(sizeInBytes / 1048576).toFixed(2)} MB`; // Jika ukuran lebih besar dari 1 MB
    }
  };


  return (
    <div style={isMobile ? styles.mobileContainer : styles.container}>
        {/* Select Application ID */}
        <div className="form-group row align-items-center">
          <div className="col-md-6">
              <div style={styles.selectWrapper}>
                <Select
                  id="applicationId"
                  value={applicationOptions.find(option => option.value === applicationId)}
                  onChange={handleApplicationChange}
                  options={applicationOptions}
                  placeholder="Select Application ID"
                  isSearchable
                  menuPortalTarget={document.body}
                  menuPlacement="auto"
                  inputValue={inputValueApplication}
                  onInputChange={handleInputChangeApplication} // Limit input length for Application ID
                />
              </div>
          </div>

          <div className="col-md-6" style={{ marginTop: !isMobile ? '0' : '2vh' }}>
            <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', margin: '0', marginTop: '8px' }}>
                Remaining Quota
            </p>
            <div style={styles.remainingQuota}>
              <span style={styles.quotaText}>{selectedQuota}</span>
              <span style={styles.timesText}>(times)</span>
            </div>
          </div>
        </div>

        {/* Message Area */}
        <div className="form-group row align-items-center">
          <div className="col-md-6 mt-3">
            <textarea
              id="messageId"
              className="form-control"
              style={{ ...styles.select, height: '250px', resize: 'none' }}
              value={messageId}
              onChange={(e) => setMessageId(e.target.value)}
              placeholder="Message Info"
            />
            {errorMessage && <small style={styles.uploadError}>{errorMessage}</small>}
          </div>

          {/* Upload Section */}
          <div className="col-md-6 mb-3">
              <div className="form-group mb-4">
                  <CustomLabel htmlFor="imageInput" style={styles.customLabel}>
                      Upload Image (KTP)
                  </CustomLabel>
                  <div style={styles.uploadWrapper}>
                      {/* Drag and Drop File Input */}
                      <div
                          style={{
                            ...styles.uploadArea,
                            height: uploadAreaHeight,
                          }}
                          onDrop={(e) => {
                              e.preventDefault();
                              handleFileDrop(e.dataTransfer.files);
                          }}
                          onDragOver={(e) => e.preventDefault()}
                      >
                          <FontAwesomeIcon icon={faCloudUploadAlt} style={styles.uploadIcon} />
                          <p style={styles.uploadText}>Drag and Drop Here</p>
                          <p>Or</p>
                          <a href="#" onClick={() => fileInputRef.current.click()} style={styles.browseLink}>Browse</a>
                          <p className="text-muted" style={styles.uploadText}>Recommended size: 300x300 (Max File Size: 2MB)</p>
                          <p className="text-muted" style={styles.uploadText}>Supported file types: JPG, JPEG</p>
                      </div>

                      {/* File Input */}
                      <input
                        ref={fileInputRef}
                        type="file"
                        id="imageInput"
                        className="form-control"
                        style={{ display: 'none' }}
                        accept="image/jpeg, image/png"
                        onChange={(e) => handleImageUpload(e.target.files[0])}
                      />

                      {selectedImageName && (
                          <div className="mt-3">
                              <p><strong>File:</strong> {selectedImageName}</p>
                              {file && (
                                  <p style={styles.fileSize}>
                                      Size: {formatFileSize(file.size)}
                                  </p>
                              )}
                              <button className="btn btn-danger" onClick={handleImageCancel}>
                                  <FontAwesomeIcon icon={faTimes} className="me-2" />Cancel
                              </button>
                          </div>
                      )}
                      {validationErrors.file && <p style={styles.errorText}>{validationErrors.file}</p>}
                  </div>
              </div>
          </div>
        </div>

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


const Announcement = () => {
    const [applicationId, setApplicationId] = useState('');
    const [messageId, setMessageId] = useState('');
    const [phoneId, setPhoneId] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('single');
    const [isMobile, setIsMobile] = useState(false);

    useEffect(() => {
        // Check if the device is mobile
        const handleResize = () => {
            setIsMobile(window.innerWidth <= 768);
        };

        window.addEventListener('resize', handleResize);
        handleResize(); // Initial check

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

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

    return (
        <div>
            {isLoading && (
                <div style={styles.loadingOverlay}>
                    <div style={styles.spinner}></div>
                </div>
            )}

            {/* Tab buttons */}
            <div style={styles.tabContainer}>
                <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
                  applicationId={applicationId}
                  setApplicationId={setApplicationId}
                  messageId={messageId}
                  setMessageId={setMessageId}
                  phoneId={phoneId}
                  setPhoneId={setPhoneId}
                  isLoading={isLoading}
                  setIsLoading={setIsLoading}
                  isMobile={isMobile}                  
                  handleClick={handleClick}
                />
            )}

            {activeTab === 'bulk' && (
                <BulkMessage
                  applicationId={applicationId}
                  setApplicationId={setApplicationId}
                  messageId={messageId}
                  setMessageId={setMessageId}
                  isLoading={isLoading}
                  setIsLoading={setIsLoading}
                  isMobile={isMobile}                  
                  handleClick={handleClick}
                />
            )}
        </div>
    );
};

export default Announcement;

const styles = {
  container: {
      padding: '20px',
  },
  mobileContainer: {
      padding: '10px',
  },
  tabContainer: {
      marginBottom: '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',
  },
  customLabel: {
    fontSize: '18px',
    fontWeight: '600',
    color: '#1f2d3d',
    marginTop: '1rem'
  },
  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',
  },
  submitButton: {
      marginTop: '20px',
      textAlign: 'start',
      position: 'relative',
      zIndex: 1,
  },
  uploadWrapper: {
    marginTop: '1rem',
  },
  uploadArea: {
    backgroundColor: '#e6f2ff',
    cursor: 'pointer',
    marginTop: '1rem',
    padding: '3rem',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    border: '1px solid #ced4da',
    borderRadius: '0.25rem',
    textAlign: 'center',
  },
  uploadIcon: {
      fontSize: '40px',
      color: '#0542cc',
      marginBottom: '10px',
  },
  uploadText: {
      color: '#1f2d3d',
      fontWeight: '400',
      fontSize: '16px',
  },
  browseLink: {
      color: '#0542cc',
      textDecoration: 'none',
      fontWeight: 'bold',
  },
  uploadError: {
      color: 'red',
      fontSize: '12px',
      marginTop: '10px',
  },
  remainingQuota: {
    display: 'flex',
    alignItems: 'center',
  },
  quotaText: {
      fontSize: '24px',
      fontWeight: '600',
      color: '#0542cc'
  },
  timesText: {
      fontSize: '16px',
      fontWeight: '300',
  },
};
