  "use client";
  import Editor from "react-simple-wysiwyg";
  import 'react-phone-number-input/style.css'
import PhoneInput from 'react-phone-number-input'
  import {
    Input,
    InputNumber,
    Checkbox,
    Button,
    Select,
    Radio,
    ColorPicker,
    Upload,
    DatePicker,
    Popconfirm,
    Space,
    Flex,
    Progress
  } from "antd";
  import dayjs from "dayjs";
  import {
    EyeInvisibleOutlined,
    EyeTwoTone,
    InboxOutlined,
    UploadOutlined,
  } from "@ant-design/icons";
  import { useState } from "react";
  import { TagsInput } from "react-tag-input-component";
  import { useSiteContext } from "../Context/SiteContext";
  import Dragger from "antd/es/upload/Dragger";
  import { errorMessage } from "../utils/variables";

  const { TextArea } = Input;
  const { Option } = Select;
  const { RangePicker } = DatePicker;

  export default function InputItem({
    type,
    title,
    options = [],
    value,
    onChange,
    name,
    label,
    hint,
    btnvariant,
    className,
    onClick,
    btnColor,
    placeholder,
    pendingUploads = {},
    form = {},
    handleFileUpload,
    editable,
    limitPadding,
    typeField,
    isNotEdit,
    getSingleDataById,
    classNames,
    max,
    min,
    disabled,
    textAlign = "left", 
    selected,
    maxFileSize
  }) {
    let content;
    const [isEditable, setIsEditable] = useState(false);
    const { uploadProgress, setUploadProgress } = useSiteContext();



    const labelMarkup = label ? (
      <label
        htmlFor={name}
        className="block mb-3 text-zinc-600 text-xs font-normal leading-tight text-start"
      >
        {label}
      </label>
    ) : null;

    const hintMarkup = hint ? (
      <p className="mt-2 text-xs text-gray-400">{hint}</p>
    ) : null;

    const btnStyle = {
      width: "100%",
      textAlign: "left",
      background: value,
      borderColor: "#d9d9d9",
      color: "#000",
    };

    let imageSrc = null;
    let digitalSignatureSrc = null;

    if (type === "image_upload") {
      imageSrc = pendingUploads[name] || form?.[name] || value;
      digitalSignatureSrc =
        pendingUploads.digital_signature || form?.digital_signature || null;
    }

    switch (type) {
      case "email":
      case "text":
        content = (
          <>
            {labelMarkup}
            <Input
              disabled={disabled}
              id={name}
              name={name}
              type={type}
              placeholder={placeholder || title || "Enter value"}
              size="middle"
              value={value}
              onChange={onChange}
              className={classNames}
              style={{ width: "100%", textAlign }}
            />
            {hintMarkup}
          </>
        );
        break;

      case "password":
        content = (
          <>
            {labelMarkup}
            <Input.Password
              id={name}
              name={name}
              size="middle"
              placeholder={placeholder || title || "Enter your password"}
              iconRender={(visible) =>
                visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
              }
              value={value}
              onChange={onChange}
              style={{ textAlign }}
            />
            {hintMarkup}
          </>
        );
        break;

      case "number":
        content = (
          <>
            {labelMarkup}
            <InputNumber
              className={classNames}
              disabled={disabled}
              id={name}
              name={name}
              placeholder={placeholder || title || "Enter number"}
              size="middle"
              value={value}
              min={min}
              max={max}
              onChange={(val) => {
                if (typeof onChange === "function") {
                  onChange({ target: { name, value: val } });
                }
              }}
              style={{ width: "100%", textAlign }}
              onKeyPress={(e) => {
                if (e.charCode < 48 || e.charCode > 57) {
                  e.preventDefault();
                }
              }}
              onPaste={(e) => {
                const paste = e.clipboardData.getData("text");
                if (!/^\d+$/.test(paste)) {
                  e.preventDefault();
                }
              }}
            />
            {hintMarkup}
          </>
        );
        break;

      case "textarea":
        content = (
          <>
            {labelMarkup}
            <TextArea
              disabled={disabled}
              id={name}
              name={name}
              rows={4}
              placeholder={placeholder || title || ""}
              value={value}
              onChange={onChange}
              style={{ width: "100%", textAlign }}
            />
            {hintMarkup}
          </>
        );
        break;

    
        case "select":
    content = (
      <>
        {labelMarkup}
        <Select
          showSearch
          id={name}
          name={name}
          placeholder={placeholder || title || "Select an option"}
          size="middle"
          value={value}
          className={className}
          onChange={(val) => {
            if (typeof onChange === "function") {
              onChange({ target: { name, value: val } });
            }
            if (getSingleDataById) {
              const selectedItem = options.find((opt) => opt.value === val);
              if (selectedItem) setSeletedCustomer(selectedItem);
            }
          }}
          style={{ width: "100%" }}
        >
          {selected && (
            <Option key="default" value="" disabled>
              Select
            </Option>
          )}

          {options?.map((opt) =>
            typeof opt === "string" ? (
              <Option key={opt} value={opt}>
                {opt}
              </Option>
            ) : (
              <Option key={opt.value} value={opt.value}>
                {opt.label || opt.item_name}
              </Option>
            )
          )}
        </Select>
        {hintMarkup}
      </>
    );
    break;


      case "tags":
        content = (
          <>
            {labelMarkup}
            <TagsInput
              value={value || []}
              onChange={(val) => {
                if (typeof onChange === "function") {
                  onChange({ target: { name, value: val } });
                }
              }}
              name={name}
              placeHolder={placeholder || title || "Enter tags"}
            />
            {hintMarkup}
          </>
        );
        break;

      case "option":
        content = (
          <>
            {labelMarkup}
            <Radio.Group id={name} name={name} onChange={onChange} value={value}>
              {options.map((opt) =>
                typeof opt === "string" ? (
                  <Radio key={opt} value={opt}>
                    {opt}
                  </Radio>
                ) : (
                  <Radio key={opt.value} value={opt.value}>
                    {opt.label}
                  </Radio>
                )
              )}
            </Radio.Group>
            {hintMarkup}
          </>
        );
        break;

      case "checkbox":
        content = (
          <>
            <Checkbox id={name} name={name} checked={value} onChange={onChange}>
              {label || title || "Remember me"}
            </Checkbox>
            {hintMarkup}
          </>
        );
        break;

      case "date":
        content = (
          <>
            {labelMarkup}
            <DatePicker
              disabled={disabled}
              id={name}
              name={name}
              placeholder={placeholder || title || "Select date"}
              style={{ width: "100%" }}
              value={value ? dayjs(value) : null}
              onChange={(date, dateString) => {
                if (typeof onChange === "function") {
                  onChange({ target: { name, value: dateString } });
                }
              }}
            />
            {hintMarkup}
          </>
        );
        break;


        case "daterange":
    content = (
      <>
        {labelMarkup}
        <RangePicker
          id={name}
          name={name}
          style={{ width: "100%" }}
          value={
            Array.isArray(value) && value.length === 2
              ? [dayjs(value[0]), dayjs(value[1])]
              : null
          }
          onChange={(dates, dateStrings) => {
            if (typeof onChange === "function") {
              onChange({ target: { name, value: dateStrings } });
            }
          }}
          disabled={disabled}
          placeholder={["Start date", "End date"]}
        />
        {hintMarkup}
      </>
    );
    break;


      case "color":
        content = (
          <>
            {labelMarkup}
            <ColorPicker
              value={value}
              onChange={(color) => {
                if (typeof onChange === "function") {
                  onChange({ target: { name, value: color.toHexString() } });
                }
              }}
            >
              <Button type="default" style={btnStyle}>
                {value || "Pick Color"}
              </Button>
            </ColorPicker>
            {hintMarkup}
          </>
        );
        break;

      case "button":
        content = (
          <>
            <Button
              className={className || ""}
              id={name}
              name={name}
              size="middle"
              color={btnColor}
              variant={btnvariant}
              onClick={onClick}
            >
              {title || "Submit"}
            </Button>
            {hintMarkup}
          </>
        );
        break;

      case "popconfirm":
        content = (
          <>
            {labelMarkup}
            <Popconfirm
              title={title || "Are you sure?"}
              onConfirm={onClick}
              okText="Yes"
              cancelText="No"
            >
              <Button className={className || ""}>{placeholder || "Click me"}</Button>
            </Popconfirm>
            {hintMarkup}
          </>
        );
        break;

    
        

      
        
  case "drag_upload":
    //const maxFileSize = 1 * 1024 * 1024; // 1 MB in bytes

    content = (
      <>
        {labelMarkup}
        <Dragger
          name="file"
          multiple={false}
          maxCount={1}
          showUploadList={{ showRemoveIcon: true }}
          beforeUpload={(file) => {

    if (file.size > maxFileSize) {
    setTimeout(() => {
      const maxSizeInMB = maxFileSize / (1024 * 1024); // convert to MB
      errorMessage(`Maximum file size allowed is ${maxSizeInMB} MB`);
    }, 0);
    return Upload.LIST_IGNORE;
  }


            if (handleFileUpload) {
              handleFileUpload(file, name);
            }

            return false; // Prevent auto upload
          }}
          onChange={({ fileList }) => {
            // Only allow one file in list
            if (fileList.length > 1) {
              message.error("Only one file can be uploaded at a time.");
            }
          }}
          onDrop={(e) => {
            if (e.dataTransfer.files.length > 1) {
              message.error("Please upload only one file.");
              e.preventDefault();
            }
          }}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined style={{ fontSize: "20px" }} />
          </p>
          <p className="text-xs">Click or drag a file to this area to upload</p>
        </Dragger>

        {/* Progress Bar (optional) */}
        {uploadProgress?.[name] != null && (
          <Flex vertical className="mt-2">
            <Progress size="small" percent={uploadProgress[name]} status="active" />
          </Flex>
        )}

        {hintMarkup}
      </>
    );
    break;





    case "drag_upload":
    content = (
      <>
        {labelMarkup}
        <Dragger
          name="file"
          multiple={false} // block multiple uploads
          maxCount={1}     // enforce one file in upload list
          showUploadList={{ showRemoveIcon: true }}
          beforeUpload={(file, fileList) => {
            if (fileList.length > 1) {
              message.error("Only one file can be uploaded at a time.");
              return Upload.LIST_IGNORE;
            }
            if (handleFileUpload) {
              handleFileUpload(file, name);
            }
            return false; // prevent auto upload
          }}
          onDrop={(e) => {
            if (e.dataTransfer.files.length > 1) {
              message.error("Please upload only one file.");
              e.preventDefault();
            }
          }}
          onChange={(info) => {
            const { status } = info.file;
            if (status === "done") {
              message.success(`${info.file.name} uploaded successfully.`);
            } else if (status === "error") {
              message.error(`${info.file.name} upload failed.`);
            }
          }}
        >
          <p className="ant-upload-drag-icon">
          <InboxOutlined style={{ fontSize: "20px" }}/>
          </p>
          <p className="text-xs">Click or drag a file to this area to upload</p>
          {/* <p className="ant-upload-hint">
            Only one file allowed. Uploading multiple files is disabled.
          </p> */}
        </Dragger>
        {hintMarkup}
      </>
    );
    break;




    case "phone_with_code":
  content = (
    <>
      {labelMarkup}
      <div
        className="ant-input"
        style={{
         display: "flex",
          alignItems: "center",
          height: "35px",
          padding: "2px 9px",
          border: "1px solid #d9d9d9",
          borderRadius: "6px",
          width: "100%",
        }}
      >
        <PhoneInput
          id={name}
          name={name}
          international
          defaultCountry="AE" // ✅ Set UAE as default
          placeholder={placeholder || title || "Enter phone number"}
          value={value}
          onChange={(val) => {
            if (typeof onChange === "function") {
              onChange({ target: { name, value: val } });
            }
          }}
          className="phone-input-inner"
          disabled={disabled}
          style={{
            border: "none",
            outline: "none",
            flex: 1,
            fontSize: "14px",
            backgroundColor: "transparent",
          }}
        />
      </div>
      {hintMarkup}
    </>
  );
  break;


 
  




      case "editor":
        content = (
          <>
            {labelMarkup}
            <Editor
              value={value || ""}
              onChange={(e) => {
                if (typeof onChange === "function") {
                  onChange({ target: { name, value: e.target.value } });
                }
              }}
            />
            {hintMarkup}
          </>
        );
        break;

      default:
        content = <>Unsupported form item</>;
    }

    return <div className="w-full">{content}</div>;
  }
