import React, { useState } from 'react';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import { useCurrentAction, useOrderDetails, useOrderId } from '../../../store';
import { ContentContainer, StyledInput, StyledTextArea } from '../modalstyle';
import { Label, useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../../types';
import { notification } from 'antd';

function SendEmailModal() {
  const [, setCurrentAction] = useCurrentAction();
  const [orderDetails] = useOrderDetails();
  const [orderId] = useOrderId();

  const initialTo = orderDetails?.order_recipient?.contact_email || '';
  const initialSubject = `${orderDetails?.trading_name ||
    ''} Order Update - ${orderDetails?.consignment || ''}`;

  const [formData, setFormData] = useState({
    to: initialTo,
    subject: initialSubject,
    body: '',
  });

  const [emailError, setEmailError] = useState('');
  const [loading, setLoading] = useState(false);

  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

  const validateEmail = (email: string) => {
    setEmailError(emailRegex.test(email) ? '' : 'Invalid email format');
  };

  const closeModal = () => setCurrentAction(undefined);

  const { fetchData: callSendEmail } = useAxios<{ data: ApiResponse[] }>({
    endpoint: `orders/${orderId}/trigger-email/`,
    method: 'POST',
  });

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));

    if (name === 'to') validateEmail(value);
  };

  const handleSubmit = async () => {
    const { to, subject, body } = formData;

    if (!to.trim() || !subject.trim() || !body.trim()) {
      alert('All fields are required!');
      return;
    }
    if (emailError) {
      alert('Please enter a valid email address.');
      return;
    }

    const payload = [
      {
        order_id: Number(orderId),
        email: to,
        subject,
        message: body,
      },
    ];

    setLoading(true);

    try {
      const response = await callSendEmail({ payload });
      console.log(response, 'responseresponse');
      if (response) {
        notification.success({
          message: 'Success',
          description: 'Email sent successfully!',
        });
        closeModal(); // Close modal on success
      } else {
        notification.error({
          message: 'Error',
          description: 'Failed to send email. Please try again.',
        });
      }
    } catch (error) {
      alert('An error occurred while sending the email.');
    } finally {
      setLoading(false);
    }
  };

  const isDisabled =
    Object.values(formData).some(val => !val.trim()) || !!emailError || loading;

  return (
    <OrderActionModal
      headerTitle="Send Email"
      onCloseHeader={closeModal}
      onSubmit={handleSubmit}
      submitBtnTitle={loading ? 'Sending...' : 'Send Email'}
      isSubmitDisabled={isDisabled}
    >
      <ContentContainer>
        <Label label="To" required />
        <StyledInput
          type="text"
          name="to"
          required
          placeholder="Enter email"
          value={formData.to}
          onChange={handleChange}
          onBlur={() => validateEmail(formData.to)}
        />
        {emailError && <span style={{ color: 'red' }}>{emailError}</span>}

        <Label label="Subject" required />
        <StyledInput
          type="text"
          name="subject"
          required
          value={formData.subject}
          onChange={handleChange}
        />

        <Label label="Body" required />
        <StyledTextArea
          name="body"
          placeholder="Write here..."
          required
          value={formData.body}
          onChange={handleChange}
        />
      </ContentContainer>
    </OrderActionModal>
  );
}

export default SendEmailModal;
