import { Button, TextControl, SelectControl, RangeControl, __experimentalUnitControl as UnitControl } from "@wordpress/components";
import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";
import { __ } from "@wordpress/i18n";
import { useEffect, useMemo, useState } from "@wordpress/element";
import { check, closeSmall, image, link, trash } from "@wordpress/icons";
import VideoProviderSelector from "./VideoProviderSelector";
import "./VideoMediaSelector.css";

export const getVideoConfig = (url) => {
  const input = String(url || "").trim();
  if (!input) return { type: "none", embedUrl: "", fileUrl: "", videoId: "" };

  const iframeSrcMatch = input.match(/<iframe[\s\S]*?\ssrc=["']([^"']+)["']/i);
  const raw = (iframeSrcMatch ? iframeSrcMatch[1] : input).replace(/&amp;/g, "&").trim();
  if (!raw) return { type: "none", embedUrl: "", fileUrl: "", videoId: "" };

  let parsed;
  try {
    parsed = new URL(raw);
  } catch (e) {
    return { type: "file", embedUrl: "", fileUrl: raw, videoId: "" };
  }

  const host = parsed.hostname.replace(/^www\./, "");
  const path = parsed.pathname;

  if (host === "youtu.be") {
    const id = path.split("/").filter(Boolean)[0];
    if (id) {
      return {
        type: "youtube",
        embedUrl: `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&mute=1&controls=0&loop=1&playlist=${id}&playsinline=1&rel=0&modestbranding=1`,
        fileUrl: "",
        videoId: id,
      };
    }
  }

  if (host === "youtube.com" || host === "youtube-nocookie.com" || host.endsWith(".youtube.com")) {
    let id = parsed.searchParams.get("v") || "";
    if (!id) {
      const parts = path.split("/").filter(Boolean);
      if (parts[0] === "embed" || parts[0] === "shorts") id = parts[1] || "";
    }
    if (id) {
      return {
        type: "youtube",
        embedUrl: `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&mute=1&controls=0&loop=1&playlist=${id}&playsinline=1&rel=0&modestbranding=1`,
        fileUrl: "",
        videoId: id,
      };
    }
  }

  if (host === "vimeo.com" || host.endsWith(".vimeo.com")) {
    const parts = path.split("/").filter(Boolean);
    const id = parts[0] === "video" ? (parts[1] || "") : (parts.find((p) => /^\d+$/.test(p)) || "");
    if (id) {
      return {
        type: "vimeo",
        embedUrl: `https://player.vimeo.com/video/${id}?autoplay=1&muted=1&loop=1&background=1&title=0&byline=0&portrait=0`,
        fileUrl: "",
        videoId: id,
      };
    }
  }

  return { type: "file", embedUrl: "", fileUrl: raw, videoId: "" };
};

const getYouTubeThumbnailUrl = (videoUrl) => {
  const config = getVideoConfig(videoUrl);
  if (config.type === "youtube" && config.videoId) {
    return `https://img.youtube.com/vi/${config.videoId}/maxresdefault.jpg`;
  }
  return "";
};

const VideoMediaSelector = ({
  videoUrl = "",
  posterUrl = "",
  onChangeVideo,
  onChangePoster,
  iframeTitle = "Current video",
  posterAlt = "",
  showProviderSelector = true,
  showEmbedHint = true,
  showPresentationControls = false,
  videoFit = "cover",
  videoPositionX = 50,
  videoPositionY = 50,
  videoCustomWidth = "100",
  videoCustomWidthUnit = "%",
  videoCustomHeight = "auto",
  videoCustomHeightUnit = "%",
  onChangeVideoFit,
  onChangeVideoPositionX,
  onChangeVideoPositionY,
  onChangeVideoCustomWidth,
  onChangeVideoCustomWidthUnit,
  onChangeVideoCustomHeight,
  onChangeVideoCustomHeightUnit,
  posterFit = "cover",
  posterPositionX = 50,
  posterPositionY = 50,
  posterCustomWidth = "100",
  posterCustomWidthUnit = "%",
  posterCustomHeight = "auto",
  posterCustomHeightUnit = "%",
  onChangePosterFit,
  onChangePosterPositionX,
  onChangePosterPositionY,
  onChangePosterCustomWidth,
  onChangePosterCustomWidthUnit,
  onChangePosterCustomHeight,
  onChangePosterCustomHeightUnit,
}) => {
  const [isVideoUrlInputOpen, setIsVideoUrlInputOpen] = useState(false);
  const [videoUrlInputValue, setVideoUrlInputValue] = useState(videoUrl || "");
  const [isPosterUrlInputOpen, setIsPosterUrlInputOpen] = useState(false);
  const [posterUrlInputValue, setPosterUrlInputValue] = useState(posterUrl || "");

  useEffect(() => {
    setVideoUrlInputValue(videoUrl || "");
  }, [videoUrl]);

  useEffect(() => {
    setPosterUrlInputValue(posterUrl || "");
  }, [posterUrl]);

  const videoConfig = useMemo(() => getVideoConfig(videoUrl), [videoUrl]);
  const isEmbedVideo = videoConfig.type === "youtube" || videoConfig.type === "vimeo";
  const isVideoWidthAuto = videoCustomWidth === "auto";
  const isVideoHeightAuto = videoCustomHeight === "auto";
  const isPosterWidthAuto = posterCustomWidth === "auto";
  const isPosterHeightAuto = posterCustomHeight === "auto";
  const customSizeUnits = [
    { label: "px", value: "px" },
    { label: "%", value: "%" },
    { label: "vw", value: "vw" },
  ];
  const controlSpacing = { marginBottom: "8px" };
  const iconButtonRowStyle = { display: "flex", alignItems: "flex-start", gap: "8px", marginBottom: "8px" };
  const iconButtonStyle = {
    width: "40px",
    minWidth: "40px",
    height: "40px",
    minHeight: "40px",
    padding: "0",
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    boxSizing: "border-box",
    margin: "0",
    lineHeight: 1,
    verticalAlign: "top",
  };

  const resetVideoPosition = () => {
    if (onChangeVideoPositionX) onChangeVideoPositionX(50);
    if (onChangeVideoPositionY) onChangeVideoPositionY(50);
  };

  return (
    <div className="zenblocks-video-media-selector">
      {showProviderSelector && (
        <VideoProviderSelector
          onSelect={(selectedVideoUrl, selectedPosterUrl) => {
            if (onChangeVideo) onChangeVideo(selectedVideoUrl || "");
            const effectivePoster = selectedPosterUrl || getYouTubeThumbnailUrl(selectedVideoUrl) || "";
            if (onChangePoster) onChangePoster(effectivePoster);
            resetVideoPosition();
          }}
        />
      )}

      <div style={{ marginBottom: "12px", padding: "10px", background: "#f6f7f7", borderRadius: "4px" }}>
        <div style={{ fontSize: "11px", fontWeight: 600, marginBottom: "6px" }}>{__("Video", "zenblocks")}</div>
        {videoUrl ? (
          <div style={{ marginBottom: "8px" }}>
            {videoConfig.type === "file" ? (
              <video src={videoConfig.fileUrl} muted playsInline controls style={{ width: "100%", height: "auto", borderRadius: "3px", display: "block", background: "#111" }} />
            ) : isEmbedVideo ? (
              <iframe
                src={videoConfig.embedUrl}
                title={iframeTitle}
                style={{ width: "100%", aspectRatio: "16 / 9", border: 0, borderRadius: "3px", display: "block", background: "#111" }}
                allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
                allowFullScreen
              />
            ) : (
              <p style={{ margin: "0 0 8px", fontSize: "11px", color: "#646970" }}>{__("Unsupported video URL.", "zenblocks")}</p>
            )}
            {isEmbedVideo && (
              <p style={{ margin: "6px 0 0", fontSize: "11px", color: "#646970" }}>
                {__("Autoplay is not available in the editor. The video will autoplay on the published page.", "zenblocks")}
              </p>
            )}
          </div>
        ) : (
          <p style={{ margin: "0 0 8px", fontSize: "11px", color: "#646970" }}>{__("No video selected.", "zenblocks")}</p>
        )}

        <div className="zenblocks-image-selector__buttons" style={iconButtonRowStyle}>
          <MediaUploadCheck>
            <MediaUpload
              onSelect={(media) => {
                if (onChangeVideo) onChangeVideo(media?.url || "");
                if (onChangePoster) onChangePoster("");
                resetVideoPosition();
              }}
              allowedTypes={["video"]}
              value={videoUrl}
              render={({ open }) => (
                <Button
                  onClick={open}
                  variant="primary"
                  icon="video-alt3"
                  className="zenblocks-image-selector__media-button"
                  label={videoUrl ? __("Change Video", "zenblocks") : __("Select Video", "zenblocks")}
                  showTooltip
                  style={iconButtonStyle}
                />
              )}
            />
          </MediaUploadCheck>
          <Button
            onClick={() => setIsVideoUrlInputOpen(!isVideoUrlInputOpen)}
            variant={isVideoUrlInputOpen ? "primary" : "secondary"}
            icon={link}
            className="zenblocks-image-selector__url-button"
            label={__("Video URL", "zenblocks")}
            showTooltip
            style={iconButtonStyle}
          />
          {videoUrl && (
            <Button
              variant="secondary"
              isDestructive
              onClick={() => {
                if (onChangeVideo) onChangeVideo("");
                setVideoUrlInputValue("");
              }}
              icon={trash}
              className="zenblocks-image-selector__remove-button"
              label={__("Remove Video", "zenblocks")}
              style={iconButtonStyle}
            />
          )}
        </div>

        {isVideoUrlInputOpen && (
          <div className="zenblocks-image-selector__url-input">
            <TextControl
              label={__("Video URL (MP4 / YouTube / Vimeo)", "zenblocks")}
              value={videoUrlInputValue}
              onChange={setVideoUrlInputValue}
              placeholder="https://example.com/video.mp4 or https://youtu.be/..."
            />
            <div className="zenblocks-image-selector__url-actions">
              <Button
                onClick={() => {
                  if (onChangeVideo) onChangeVideo(videoUrlInputValue);
                  const autoPoster = getYouTubeThumbnailUrl(videoUrlInputValue) || "";
                  if (onChangePoster) onChangePoster(autoPoster);
                  resetVideoPosition();
                  setIsVideoUrlInputOpen(false);
                }}
                variant="primary"
                disabled={!videoUrlInputValue.trim()}
                icon={check}
                label={__("Apply", "zenblocks")}
                showTooltip
                style={iconButtonStyle}
              />
              <Button
                onClick={() => {
                  setIsVideoUrlInputOpen(false);
                  setVideoUrlInputValue(videoUrl || "");
                }}
                variant="secondary"
                icon={closeSmall}
                label={__("Cancel", "zenblocks")}
                showTooltip
                style={iconButtonStyle}
              />
            </div>
            {showEmbedHint && (
              <p style={{ margin: "6px 0 0", fontSize: "11px", color: "#646970" }}>
                {__("YouTube/Vimeo are embedded via iframe. The source video must allow embedding.", "zenblocks")}
              </p>
            )}
          </div>
        )}
      </div>

      {showPresentationControls && (
        <div style={{ marginBottom: "12px", padding: "10px", background: "#f6f7f7", borderRadius: "4px" }}>
          <div style={{ height: "8px" }} />
          <div style={controlSpacing}>
            <SelectControl
              label={__("Video Fit", "zenblocks")}
              value={videoFit}
              options={[
                { label: __("Cover", "zenblocks"), value: "cover" },
                { label: __("Contain", "zenblocks"), value: "contain" },
                { label: __("Fill", "zenblocks"), value: "fill" },
                { label: __("None", "zenblocks"), value: "none" },
              ]}
              onChange={(value) => onChangeVideoFit && onChangeVideoFit(value)}
            />
          </div>
          <div style={controlSpacing}>
            <RangeControl
              label={__("Video Position X", "zenblocks")}
              value={videoPositionX}
              min={0}
              max={100}
              onChange={(value) => onChangeVideoPositionX && onChangeVideoPositionX(value)}
            />
          </div>
          <div style={controlSpacing}>
            <RangeControl
              label={__("Video Position Y", "zenblocks")}
              value={videoPositionY}
              min={0}
              max={100}
              onChange={(value) => onChangeVideoPositionY && onChangeVideoPositionY(value)}
            />
          </div>
          {(videoFit === "fill" || videoFit === "none") && (
            <>
              <div style={{ marginBottom: "12px" }}>
                <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Width", "zenblocks")}</label>
                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                  <div style={{ flex: 1, opacity: isVideoWidthAuto ? 0.5 : 1, pointerEvents: isVideoWidthAuto ? "none" : "auto" }}>
                    <UnitControl
                      value={isVideoWidthAuto ? "" : `${videoCustomWidth}${videoCustomWidthUnit}`}
                      onChange={(value) => {
                        const numValue = parseFloat(value);
                        const unit = value.replace(/[\d.-]/g, "") || videoCustomWidthUnit;
                        if (!isNaN(numValue) && onChangeVideoCustomWidth) onChangeVideoCustomWidth(String(numValue));
                        if (unit && onChangeVideoCustomWidthUnit) onChangeVideoCustomWidthUnit(unit);
                      }}
                      units={customSizeUnits}
                      placeholder={isVideoWidthAuto ? "auto" : ""}
                    />
                  </div>
                  <Button
                    isSmall
                    variant={isVideoWidthAuto ? "primary" : "secondary"}
                    onClick={() => {
                      if (isVideoWidthAuto) {
                        onChangeVideoCustomWidth && onChangeVideoCustomWidth("100");
                        onChangeVideoCustomWidthUnit && onChangeVideoCustomWidthUnit("%");
                      } else {
                        onChangeVideoCustomWidth && onChangeVideoCustomWidth("auto");
                      }
                    }}
                  >
                    AUTO
                  </Button>
                </div>
              </div>
              <div style={{ marginBottom: "12px" }}>
                <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Height", "zenblocks")}</label>
                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                  <div style={{ flex: 1, opacity: isVideoHeightAuto ? 0.5 : 1, pointerEvents: isVideoHeightAuto ? "none" : "auto" }}>
                    <UnitControl
                      value={isVideoHeightAuto ? "" : `${videoCustomHeight}${videoCustomHeightUnit}`}
                      onChange={(value) => {
                        const numValue = parseFloat(value);
                        const unit = value.replace(/[\d.-]/g, "") || videoCustomHeightUnit;
                        if (!isNaN(numValue) && onChangeVideoCustomHeight) onChangeVideoCustomHeight(String(numValue));
                        if (unit && onChangeVideoCustomHeightUnit) onChangeVideoCustomHeightUnit(unit);
                      }}
                      units={customSizeUnits}
                      placeholder={isVideoHeightAuto ? "auto" : ""}
                    />
                  </div>
                  <Button
                    isSmall
                    variant={isVideoHeightAuto ? "primary" : "secondary"}
                    onClick={() => {
                      if (isVideoHeightAuto) {
                        onChangeVideoCustomHeight && onChangeVideoCustomHeight("100");
                        onChangeVideoCustomHeightUnit && onChangeVideoCustomHeightUnit("%");
                      } else {
                        onChangeVideoCustomHeight && onChangeVideoCustomHeight("auto");
                      }
                    }}
                  >
                    AUTO
                  </Button>
                </div>
              </div>
            </>
          )}
          {(videoConfig.type === "youtube" || videoConfig.type === "vimeo") && (
            <p style={{ margin: "6px 0 0", fontSize: "11px", color: "#646970" }}>
              {__("YouTube/Vimeo are displayed as embeds, so position control is approximate.", "zenblocks")}
            </p>
          )}
        </div>
      )}

      <div style={{ marginBottom: "8px", padding: "10px", background: "#f6f7f7", borderRadius: "4px" }}>
        <div style={{ fontSize: "11px", fontWeight: 600, marginBottom: "6px" }}>{__("Poster", "zenblocks")}</div>
        {posterUrl ? (
          <img
            src={posterUrl}
            alt={posterAlt}
            style={{ width: "100%", height: "120px", objectFit: "cover", borderRadius: "3px", display: "block", marginBottom: "8px" }}
          />
        ) : (
          <p style={{ margin: "0 0 8px", fontSize: "11px", color: "#646970" }}>{__("No poster selected.", "zenblocks")}</p>
        )}

        <div className="zenblocks-image-selector__buttons" style={iconButtonRowStyle}>
          <MediaUploadCheck>
            <MediaUpload
              onSelect={(media) => {
                if (onChangePoster) onChangePoster(media?.url || "");
              }}
              allowedTypes={["image"]}
              value={posterUrl}
              render={({ open }) => (
                <Button
                  onClick={open}
                  variant="secondary"
                  icon={image}
                  className="zenblocks-image-selector__media-button"
                  label={posterUrl ? __("Change Poster", "zenblocks") : __("Select Poster", "zenblocks")}
                  showTooltip
                  style={iconButtonStyle}
                />
              )}
            />
          </MediaUploadCheck>
          <Button
            onClick={() => setIsPosterUrlInputOpen(!isPosterUrlInputOpen)}
            variant={isPosterUrlInputOpen ? "primary" : "secondary"}
            icon={link}
            className="zenblocks-image-selector__url-button"
            label={__("Poster URL", "zenblocks")}
            showTooltip
            style={iconButtonStyle}
          />
          {posterUrl && (
            <Button
              variant="secondary"
              isDestructive
              onClick={() => {
                if (onChangePoster) onChangePoster("");
                setPosterUrlInputValue("");
              }}
              icon={trash}
              className="zenblocks-image-selector__remove-button"
              label={__("Remove Poster", "zenblocks")}
              style={iconButtonStyle}
            />
          )}
        </div>

        {isPosterUrlInputOpen && (
          <div className="zenblocks-image-selector__url-input">
            <TextControl
              label={__("Poster URL (optional)", "zenblocks")}
              value={posterUrlInputValue}
              onChange={setPosterUrlInputValue}
              placeholder="https://example.com/poster.jpg"
            />
            <div className="zenblocks-image-selector__url-actions">
              <Button
                onClick={() => {
                  if (onChangePoster) onChangePoster(posterUrlInputValue);
                  setIsPosterUrlInputOpen(false);
                }}
                variant="primary"
                icon={check}
                label={__("Apply", "zenblocks")}
                showTooltip
                style={iconButtonStyle}
              />
              <Button
                onClick={() => {
                  setIsPosterUrlInputOpen(false);
                  setPosterUrlInputValue(posterUrl || "");
                }}
                variant="secondary"
                icon={closeSmall}
                label={__("Cancel", "zenblocks")}
                showTooltip
                style={iconButtonStyle}
              />
            </div>
          </div>
        )}

        {showPresentationControls && (
          <div style={{ marginTop: "8px" }}>
            <div style={{ height: "8px" }} />
            <div style={controlSpacing}>
              <SelectControl
                label={__("Poster Fit", "zenblocks")}
                value={posterFit}
                options={[
                  { label: __("Cover", "zenblocks"), value: "cover" },
                  { label: __("Contain", "zenblocks"), value: "contain" },
                  { label: __("Fill", "zenblocks"), value: "fill" },
                  { label: __("None", "zenblocks"), value: "none" },
                ]}
                onChange={(value) => onChangePosterFit && onChangePosterFit(value)}
              />
            </div>
            <div style={controlSpacing}>
              <RangeControl
                label={__("Poster Position X", "zenblocks")}
                value={posterPositionX}
                min={0}
                max={100}
                onChange={(value) => onChangePosterPositionX && onChangePosterPositionX(value)}
              />
            </div>
            <div style={controlSpacing}>
              <RangeControl
                label={__("Poster Position Y", "zenblocks")}
                value={posterPositionY}
                min={0}
                max={100}
                onChange={(value) => onChangePosterPositionY && onChangePosterPositionY(value)}
              />
            </div>
            {(posterFit === "fill" || posterFit === "none") && (
              <>
                <div style={{ marginBottom: "12px" }}>
                  <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Width", "zenblocks")}</label>
                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <div style={{ flex: 1, opacity: isPosterWidthAuto ? 0.5 : 1, pointerEvents: isPosterWidthAuto ? "none" : "auto" }}>
                      <UnitControl
                        value={isPosterWidthAuto ? "" : `${posterCustomWidth}${posterCustomWidthUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "") || posterCustomWidthUnit;
                          if (!isNaN(numValue) && onChangePosterCustomWidth) onChangePosterCustomWidth(String(numValue));
                          if (unit && onChangePosterCustomWidthUnit) onChangePosterCustomWidthUnit(unit);
                        }}
                        units={customSizeUnits}
                        placeholder={isPosterWidthAuto ? "auto" : ""}
                      />
                    </div>
                    <Button
                      isSmall
                      variant={isPosterWidthAuto ? "primary" : "secondary"}
                      onClick={() => {
                        if (isPosterWidthAuto) {
                          onChangePosterCustomWidth && onChangePosterCustomWidth("100");
                          onChangePosterCustomWidthUnit && onChangePosterCustomWidthUnit("%");
                        } else {
                          onChangePosterCustomWidth && onChangePosterCustomWidth("auto");
                        }
                      }}
                    >
                      AUTO
                    </Button>
                  </div>
                </div>
                <div style={{ marginBottom: "12px" }}>
                  <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{__("Height", "zenblocks")}</label>
                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <div style={{ flex: 1, opacity: isPosterHeightAuto ? 0.5 : 1, pointerEvents: isPosterHeightAuto ? "none" : "auto" }}>
                      <UnitControl
                        value={isPosterHeightAuto ? "" : `${posterCustomHeight}${posterCustomHeightUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "") || posterCustomHeightUnit;
                          if (!isNaN(numValue) && onChangePosterCustomHeight) onChangePosterCustomHeight(String(numValue));
                          if (unit && onChangePosterCustomHeightUnit) onChangePosterCustomHeightUnit(unit);
                        }}
                        units={customSizeUnits}
                        placeholder={isPosterHeightAuto ? "auto" : ""}
                      />
                    </div>
                    <Button
                      isSmall
                      variant={isPosterHeightAuto ? "primary" : "secondary"}
                      onClick={() => {
                        if (isPosterHeightAuto) {
                          onChangePosterCustomHeight && onChangePosterCustomHeight("100");
                          onChangePosterCustomHeightUnit && onChangePosterCustomHeightUnit("%");
                        } else {
                          onChangePosterCustomHeight && onChangePosterCustomHeight("auto");
                        }
                      }}
                    >
                      AUTO
                    </Button>
                  </div>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default VideoMediaSelector;
