import React, { useState } from "react";
import {
  Box,
  TextField,
  Button,
  Chip,
  Stack
} from "@mui/material";
import { check } from "recheck"
import PropTypes from "prop-types";

function DynamicListTypeInput({ field, disabled, onChange, error, helperText }) {
  const [inputValue, setInputValue] = useState("");
  const [localError, setLocalError] = useState("");

  const getActualValue = (val) => (val ? String(val).split(",") : []);
  const values = Array.isArray(field.ProValue)
    ? field.ProValue
    : getActualValue(field.ProValue);

  // Validate input on change
  const handleInputChange = async (e) => {
  const val = e.target.value;
  setInputValue(val);

  // Reset error by default
  setLocalError("");

  if (field.Pattern && val) {
    try {
      // Await if check is async
      const isValidCheck = await check(field.Pattern, ""); // if check is synchronous, remove 'await'
      const regex = new RegExp(field.Pattern);

      if (!regex.test(val) || !isValidCheck) {
        setLocalError(field.ErrorText || "Invalid format");
      }
    } catch (err) {
      console.error("Error validating pattern:", err);
      setLocalError("Invalid format");
    }
  }
};


  // Only add chip if no error
  const handleAdd = () => {
    const trimmed = inputValue.trim();
    if (!trimmed || localError) return;

    if (!values.includes(trimmed)) {
      const updated = [...values, trimmed];
      onChange(updated);
    }
    setInputValue("");
    setLocalError("");
  };

  const handleRemove = (val) => {
    const updated = values.filter((v) => v !== val);
    onChange(updated);
  };

  return (
    <Box>
      <Stack direction="row" spacing={1} alignItems="center" mb={1}>
        <TextField
          style={{ width: "300px" }}
          size="small"
          label={field.Label}
          placeholder={field.Placeholder || "Enter value"}
          value={inputValue}
          disabled={disabled}
          error={!!localError || error}
          helperText={localError || helperText}
          onChange={handleInputChange}
          onKeyDown={(e) => {
            if (e.key == "Enter") {
              e.preventDefault();
              handleAdd();
            }
          }}
        />
       <Button
          variant="contained"
          size="small"
          disabled={!!localError || disabled || !inputValue.trim()}
          onClick={handleAdd}
        >
          Add
        </Button>
        
      </Stack>

      {values.length > 0 && (
        <Stack direction="row" spacing={1} flexWrap="wrap">
          {values.map((val) => (
            <Chip
              key={val}
              label={val}
              onDelete={() => handleRemove(val)}
              disabled={disabled}
              color="primary"
              variant="outlined"
              sx={{ mb: 1 }}
            />
          ))}
        </Stack>
      )}
    </Box>
  );
}

export default DynamicListTypeInput;

DynamicListTypeInput.propTypes = {
  field: PropTypes.object.isRequired,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  error: PropTypes.bool,
  helperText: PropTypes.string,
};
