import { useState, useEffect, ChangeEvent } from "react";
import {
  ModalFooter,
  ModalBody,
  ModalHeader,
  ButtonGroup,
  Button,
  Field as FieldComponent,
  FieldLabel,
  TextInput,
} from "@contentstack/venus-components";

import type { InsertResponse } from "~/types/imagevault";

type ImageEditModalProps = {
  fieldData: InsertResponse;
  setData: (data: InsertResponse) => void;
  closeModal: () => void;
};

export default function ImageEditModal({
  fieldData,
  closeModal,
  setData,
}: ImageEditModalProps) {
  const [altText, setAltText] = useState("");
  const [caption, setCaption] = useState("");

  const assetUrl = fieldData.MediaConversions[0].Url;

  useEffect(() => {
    if (fieldData.Metadata && fieldData.Metadata.length) {
      const altText = fieldData.Metadata.find((meta) =>
        meta.Name.includes("AltText_")
      )?.Value;

      const caption = fieldData.Metadata.find((meta) =>
        meta.Name.includes("Title_")
      )?.Value;

      setAltText(altText ?? "");
      setCaption(caption ?? "");
    }
  }, [fieldData.Metadata]);

  function handleSave() {
    const metaData = fieldData.Metadata ?? [];

    const newMetadata = metaData.map((meta) => {
      if (meta.Name.includes("AltText_")) {
        return { ...meta, Value: altText };
      }
      if (meta.Name.includes("Title_")) {
        return { ...meta, Value: caption };
      }
      return meta;
    });

    setData({
      ...fieldData,
      Metadata: newMetadata,
    });
    closeModal();
  }

  return (
    <>
      <ModalHeader title="Update image" closeModal={closeModal} />
      <ModalBody
        style={{
          display: "flex",
          gap: "1rem",
          justifyContent: "space-between",
          alignItems: "center",
          width: "100%",
        }}
      >
        <div style={{ flex: 1, overflowY: "auto" }}>
          <img
            src={assetUrl}
            alt={altText}
            height="100%"
            style={{ maxHeight: "345px" }}
          />
        </div>
        <div style={{ flex: 1 }}>
          <FieldComponent>
            <FieldLabel htmlFor="alt">Alt text</FieldLabel>
            <TextInput
              value={altText}
              placeholder="Alt text for image"
              name="alt"
              onChange={(e: ChangeEvent<HTMLInputElement>) =>
                setAltText(e.target.value)
              }
            />
          </FieldComponent>

          <FieldComponent>
            <FieldLabel htmlFor="caption">Caption</FieldLabel>
            <TextInput
              value={caption}
              placeholder="Caption for image..."
              name="caption"
              onChange={(e: ChangeEvent<HTMLInputElement>) =>
                setCaption(e.target.value)
              }
            />
          </FieldComponent>
        </div>
      </ModalBody>
      <ModalFooter>
        <ButtonGroup>
          <Button onClick={closeModal} buttonType="light">
            Cancel
          </Button>
          <Button onClick={handleSave} icon="SaveWhite">
            Save
          </Button>
        </ButtonGroup>
      </ModalFooter>
    </>
  );
}
