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

import FocalPointPicker from "~/shared-components/FocalPointPicker"
import type { FocalPoint, 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 [focalPoint, setFocalPoint] = useState<FocalPoint>({ x: 50, y: 50 })

  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])

  useEffect(() => {
    if (fieldData.FocalPoint) {
      setFocalPoint(fieldData.FocalPoint)
    }
  }, [fieldData.FocalPoint])

  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,
      FocalPoint: focalPoint,
    })
    closeModal()
  }

  function changeFocalPoint(focalPoint: FocalPoint) {
    setFocalPoint(focalPoint)
  }

  return (
    <>
      <ModalHeader title="Update image" closeModal={closeModal} />
      <ModalBody
        style={{
          display: "grid",
          gridTemplateColumns: "1fr minmax(max-content, 250px)",
          gap: "1rem",
          alignItems: "center",
          width: "auto",
          maxHeight: "calc(90dvh - 124px)", // 124px is the height of the header and footer
          maxWidth: "90dvw",
          overflow: "auto",
        }}
      >
        <FocalPointPicker
          imageSrc={assetUrl}
          focalPoint={focalPoint}
          onChange={changeFocalPoint}
        />
        <div>
          <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>

          <FieldComponent>
            <FieldLabel htmlFor="focalPoint">Focal Point</FieldLabel>
            <TextInput
              value={`X: ${focalPoint.x}, Y: ${focalPoint.y}`}
              name="focalPoint"
              disabled
            />
          </FieldComponent>

          <FieldComponent>
            <FieldLabel htmlFor="imageVaultId">Imagevault Id</FieldLabel>
            <TextInput value={fieldData.Id} name="imageVaultId" disabled />
          </FieldComponent>
        </div>
      </ModalBody>
      <ModalFooter>
        <ButtonGroup>
          <Button onClick={closeModal} buttonType="light">
            Cancel
          </Button>
          <Button onClick={handleSave} icon="SaveWhite">
            Save
          </Button>
        </ButtonGroup>
      </ModalFooter>
    </>
  )
}
