import React, { useEffect, useRef } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "../../../../Input";
import { TextArea } from "../../../../TextArea";
import { Button } from "../../../../Button";
import "./AddChatContainer.styles.scss";

// Validation rules
const validationRules = {
  chatName: {
    required: "Chat name is required",
    minLength: {
      value: 2,
      message: "Chat name must be at least 2 characters long",
    },
    maxLength: {
      value: 50,
      message: "Chat name cannot exceed 50 characters",
    },
    // pattern: {
    //   value: /^[a-zA-Z0-9\s\-_]+$/,
    //   message:
    //     "Chat name can only contain letters, numbers, spaces, hyphens, and underscores",
    // },
  },
  chatDescription: {
    maxLength: {
      value: 100,
      message: "Description cannot exceed 100 characters",
    },
  },
};

const AddChat = ({
  setShowAddChat,
  handleChatName,
  selectedChannelInfo,
  handleToast,
  setIsCreateNewChatOpen,
}) => {
  const containerRef = useRef(null);

  const {
    control,
    handleSubmit,
    formState: { errors, isSubmitting, isValid },
    reset,
  } = useForm({
    mode: "onSubmit", // Validate on change for real-time feedback
    defaultValues: {
      chatName: "",
      chatDescription: "",
    },
  });

  useEffect(() => {
    function handleClickOutside(event) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target)
      ) {
        handleCancel();
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  // Form submission handler
  const onSubmit = async (data) => {
    try {
      // 👇 Call the root function with validated data
      const response = await handleChatName(data, selectedChannelInfo);

      handleToast(true, "Chat saved successfully", "success");

      // ✅ Close container after success and reset form
      handleCancel();
    } catch (err) {
      console.error("Error while saving chat:", err);
      handleToast(true, "Error while saving chat", "error");
      // TODO: Add proper error handling/toast notification
    }
  };

  // Cancel handler - resets form and closes modal
  const handleCancel = () => {
    reset();
    setShowAddChat(false);
    setIsCreateNewChatOpen(false);
  };

  return (
    <div ref={containerRef} className="addChat_container">
      <form
        className="chatcontainer"
        onSubmit={handleSubmit(onSubmit)}
        noValidate
      >
        <Controller
          name="chatName"
          control={control}
          rules={validationRules.chatName}
          render={({ field }) => (
            <Input
              label="Chat name"
              placeholder="Price negotiation"
              type="text"
              isDisabled={isSubmitting}
              isError={!!errors.chatName}
              isHelperText={!!errors.chatName}
              helperText={errors.chatName?.message}
              value={field.value}
              onChange={field.onChange}
              onBlur={field.onBlur}
              name={field.name}
            />
          )}
        />

        <Controller
          name="chatDescription"
          control={control}
          rules={validationRules.chatDescription}
          render={({ field }) => (
            <TextArea
              label="Add description"
              placeholder="Lets review the latest changes"
              isDisabled={isSubmitting}
              height="80px"
              maxRows={2}
              characterLimit={100}
              width="100%"
              isError={!!errors.chatDescription}
              secondaryLabel={errors.chatDescription?.message}
              value={field.value || ""} // Ensure value is never undefined
              onChange={field.onChange}
              onBlur={field.onBlur}
              name={field.name}
            />
          )}
        />

        <div className="chatFooterContainer">
          <Button
            variant="tertiary"
            size="large"
            type="button"
            disabled={isSubmitting}
            onClick={handleCancel}
          >
            Cancel
          </Button>
          <Button
            className="chat_save_btn"
            variant="primary"
            size="large"
            type="submit"
            disabled={isSubmitting}
          >
            {isSubmitting ? <>Saving...</> : "Save"}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default AddChat;
