import { useState, useRef, useEffect } from '@wordpress/element';
import { createRule, updateRule } from '../../../utils/api';
import { useStyles } from '../../../hooks/useStyles';

export const useRuleForm = (rule, onSave) => {
  const mountedRef = useRef(true);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const {
    progressStyles,
    successStyles,
    updateProgressStyle,
    updateSuccessStyle,
  } = useStyles(
    rule?.meta?.dlift_progress_styles,
    rule?.meta?.dlift_success_styles
  );

  const initialFormData = {
    title: rule?.title?.rendered || rule?.title?.raw || 'New Rule',
    conditionType: rule?.meta?.dlift_condition_type || 'cart_total',
    conditionValue: rule?.meta?.dlift_condition_value || '100',
    discountType: rule?.meta?.dlift_discount_type || 'percentage',
    discountValue: rule?.meta?.dlift_discount_value || '10',
    progressMessage: rule?.meta?.dlift_progress_message || 'Spend {remaining_amount} more to get {discount} off!',
    successMessage: rule?.meta?.dlift_success_message || 'Congratulations! You\'ve unlocked {discount} off your order!',
    celebrationType: rule?.meta?.dlift_celebration_type || 'none',
    previewEnabled: false
  };

  const [formData, setFormData] = useState(initialFormData);
  const [isSaving, setIsSaving] = useState(false);
  const saveInProgressRef = useRef(false);

  const handleChange = (key, value) => {
    if (!mountedRef.current) return;
    setFormData(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const handleStyleChange = (type, key, value) => {
    if (!mountedRef.current) return;
    if (type === 'progress') {
      updateProgressStyle(key, value);
    } else {
      updateSuccessStyle(key, value);
    }
  };

  const handleSave = async () => {
    // Prevent duplicate submissions using both state and ref
    if (isSaving || saveInProgressRef.current) {
      return;
    }

    const data = {
      title: formData.title,
      status: 'publish',
      meta: {
        dlift_condition_type: formData.conditionType,
        dlift_condition_value: formData.conditionValue,
        dlift_discount_type: formData.discountType,
        dlift_discount_value: formData.discountValue,
        dlift_progress_message: formData.progressMessage,
        dlift_success_message: formData.successMessage,
        dlift_progress_styles: progressStyles,
        dlift_success_styles: successStyles,
        dlift_celebration_type: formData.celebrationType || 'none'
      }
    };

    saveInProgressRef.current = true;
    try {
      if (mountedRef.current) {
        setIsSaving(true);
      }

      let result;
      if (rule?.id) {
        result = await updateRule(rule.id, data);
      } else {
        result = await createRule(data);
      }
      // Only call onSave if we haven't unmounted
      if (mountedRef.current) {
        onSave(result);
      }
    } catch (err) {
      throw err;
    } finally {
      saveInProgressRef.current = false;
      // Only update state if component is still mounted
      if (mountedRef.current) {
        setIsSaving(false);
      }
    }
  };

  return {
    formData,
    handleChange,
    handleStyleChange,
    handleSave,
    progressStyles,
    successStyles,
    isSaving
  };
};