import { useState } from "@wordpress/element";
import { Button, TextControl, Spinner, Notice } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import apiFetch from "@wordpress/api-fetch";
import { check, search, link as linkIcon } from "@wordpress/icons";

const CATEGORY_PRESETS = [
  { id: "business", label: __("Business", "zenblocks"), query: "business" },
  { id: "people", label: __("People", "zenblocks"), query: "people" },
  { id: "nature", label: __("Nature", "zenblocks"), query: "nature" },
  { id: "travel", label: __("Travel", "zenblocks"), query: "travel" },
  { id: "city", label: __("City", "zenblocks"), query: "city" },
  { id: "lifestyle", label: __("Lifestyle", "zenblocks"), query: "lifestyle" },
  { id: "work", label: __("Work", "zenblocks"), query: "work" },
  { id: "food", label: __("Food", "zenblocks"), query: "food" },
  { id: "technology", label: __("Technology", "zenblocks"), query: "technology" },
  { id: "sports", label: __("Sports", "zenblocks"), query: "sports" },
  { id: "animation", label: __("Animation", "zenblocks"), query: "animation" },
];

const PROVIDERS = [
  { id: "pexels", label: __("Pexels", "zenblocks") },
  { id: "pixabay", label: __("Pixabay", "zenblocks") },
];

const PROVIDER_LICENSE_URL = {
  pexels: "https://www.pexels.com/license/",
  pixabay: "https://pixabay.com/service/license-summary/",
};

const VideoProviderSelector = ({ onSelect, showToggle = true, initialOpen = false }) => {
  const [isOpen, setIsOpen] = useState(showToggle ? initialOpen : true);
  const [provider, setProvider] = useState("pexels");
  const [query, setQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState("");
  const [results, setResults] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [isSelectingId, setIsSelectingId] = useState("");
  const [error, setError] = useState("");

  const searchVideos = async ({ nextPage = 1, append = false, keyword = "" } = {}) => {
    const searchTerm = String(keyword || query).trim();
    if (!searchTerm) {
      setError(__("Please enter a keyword.", "zenblocks"));
      return;
    }

    setIsSearching(true);
    setError("");

    try {
      const endpointMap = {
        pexels: "/zenblocks/v1/media/pexels/videos/search",
        pixabay: "/zenblocks/v1/media/pixabay/videos/search",
      };
      const endpoint = endpointMap[provider] || endpointMap.pexels;
      const response = await apiFetch({
        path: `${endpoint}?q=${encodeURIComponent(searchTerm)}&page=${nextPage}&per_page=20`,
        method: "GET",
      });

      const items = response?.items || [];
      const nextHasMore = Boolean(response?.pagination?.has_more);
      setResults((prev) => (append ? [...prev, ...items] : items));
      setPage(nextPage);
      setHasMore(nextHasMore);
    } catch (searchError) {
      const errorCode = searchError?.code || "";
      const errorStatus = searchError?.data?.status;
      if (provider === "pexels" && (errorCode === "zenblocks_pexels_key_missing" || errorStatus === 401)) {
        setError(__("A Pexels API key is required for video search. Please set the same Pexels API key used for image search in ZenBlocks Settings.", "zenblocks"));
      } else if (provider === "pixabay" && (errorCode === "zenblocks_pixabay_key_missing" || errorStatus === 401)) {
        setError(__("A Pixabay API key is required for video search. Please set the same Pixabay API key used for image search in ZenBlocks Settings.", "zenblocks"));
      } else {
        setError(searchError?.message || __("Failed to search videos.", "zenblocks"));
      }
    } finally {
      setIsSearching(false);
    }
  };

  const handleProviderChange = (nextProvider) => {
    if (provider === nextProvider) return;
    setProvider(nextProvider);
    setActiveCategory("");
    setResults([]);
    setPage(1);
    setHasMore(false);
    setError("");
  };

  const handleCategoryClick = (category) => {
    setActiveCategory(category.id);
    setQuery(category.query);
    searchVideos({ nextPage: 1, append: false, keyword: category.query });
  };

  const selectVideo = async (item) => {
    setIsSelectingId(item.id);
    setError("");
    try {
      if (onSelect && item.videoUrl) {
        onSelect(item.videoUrl, item.thumbnailUrl || "");
      }
    } finally {
      setIsSelectingId("");
    }
  };

  const getMetaLinks = (item) => {
    const authorUrl = item.creatorUrl || item.authorUrl || item.sourceUrl || "";
    const sourceUrl = item.sourceUrl || "";
    const licenseUrl = item.licenseUrl || PROVIDER_LICENSE_URL[provider] || "";
    return { authorUrl, sourceUrl, licenseUrl };
  };

  return (
    <div className="zenblocks-openverse-image-selector">
      {showToggle && (
        <Button
          variant={isOpen ? "primary" : "secondary"}
          onClick={() => setIsOpen((prev) => !prev)}
          className="zenblocks-openverse-image-selector__toggle"
        >
          {__("Video Search", "zenblocks")}
        </Button>
      )}
      <p className="zenblocks-openverse-image-selector__notice">
        {provider === "pexels" && __("Search Pexels videos. Uses the same API key as image search. Please review Pexels terms of use.", "zenblocks")}
        {provider === "pixabay" && __("Search Pixabay videos. Uses the same API key as image search. Please review Pixabay terms of use.", "zenblocks")}
      </p>

      {isOpen && (
        <div className="zenblocks-openverse-image-selector__content">
          <div className="zenblocks-openverse-image-selector__provider-tabs">
            {PROVIDERS.map((item) => (
              <Button
                key={item.id}
                isSmall
                variant={provider === item.id ? "primary" : "secondary"}
                onClick={() => handleProviderChange(item.id)}
                className="zenblocks-openverse-image-selector__provider-btn"
              >
                {item.label}
              </Button>
            ))}
          </div>

          <div className="zenblocks-openverse-image-selector__search">
            <TextControl
              label={__("Search videos", "zenblocks")}
              hideLabelFromVision={true}
              value={query}
              onChange={(value) => {
                setQuery(value);
                setActiveCategory("");
              }}
              placeholder={__("e.g. business, nature, workspace", "zenblocks")}
            />
            <Button
              variant="primary"
              onClick={() => searchVideos({ nextPage: 1, append: false })}
              disabled={isSearching || !query.trim()}
              icon={search}
              label={__("Search", "zenblocks")}
              className="zenblocks-openverse-image-selector__search-button"
            >
              <span className="screen-reader-text">
                {isSearching ? __("Searching...", "zenblocks") : __("Search", "zenblocks")}
              </span>
            </Button>
          </div>

          <div className="zenblocks-openverse-image-selector__categories">
            {CATEGORY_PRESETS.map((category) => (
              <Button
                key={category.id}
                isSmall
                variant={activeCategory === category.id ? "primary" : "secondary"}
                onClick={() => handleCategoryClick(category)}
                className="zenblocks-openverse-image-selector__category-btn"
              >
                {category.label}
              </Button>
            ))}
          </div>

          {error && (
            <Notice status="error" isDismissible onDismiss={() => setError("")}>
              {error}
            </Notice>
          )}

          {isSearching && results.length === 0 && (
            <div className="zenblocks-openverse-image-selector__loading">
              <Spinner />
            </div>
          )}

          {results.length > 0 && (
            <>
              <div className="zenblocks-openverse-image-selector__grid">
                {results.map((item) => (
                  <div key={item.id} className="zenblocks-openverse-image-selector__item-card">
                    <div className="zenblocks-openverse-image-selector__image-wrap">
                      <button
                        type="button"
                        className="zenblocks-openverse-image-selector__image-button"
                        onClick={() => selectVideo(item)}
                        disabled={Boolean(isSelectingId)}
                        aria-label={__("Select video", "zenblocks")}
                      >
                        {item.thumbnailUrl ? (
                          <img src={item.thumbnailUrl} alt={__("Video thumbnail", "zenblocks")} />
                        ) : (
                          <span className="zenblocks-openverse-image-selector__importing">{__("No preview", "zenblocks")}</span>
                        )}
                        {isSelectingId === item.id && (
                          <span className="zenblocks-openverse-image-selector__importing">
                            {__("Selecting...", "zenblocks")}
                          </span>
                        )}
                      </button>
                    </div>
                    {(() => {
                      const { authorUrl, sourceUrl, licenseUrl } = getMetaLinks(item);
                      return (
                        <div className="zenblocks-openverse-image-selector__item-actions">
                          {(authorUrl || sourceUrl) && (
                            <a
                              href={authorUrl || sourceUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="zenblocks-openverse-image-selector__action-icon"
                              title={__("Author", "zenblocks")}
                              aria-label={__("Author", "zenblocks")}
                            >
                              <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                                <circle cx="12" cy="8" r="3.5" fill="none" stroke="currentColor" strokeWidth="1.8" />
                                <path d="M5.5 19c0-3.2 2.9-5.5 6.5-5.5s6.5 2.3 6.5 5.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
                              </svg>
                            </a>
                          )}
                          {sourceUrl && (
                            <a
                              href={sourceUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="zenblocks-openverse-image-selector__action-icon"
                              title={__("Source", "zenblocks")}
                              aria-label={__("Source", "zenblocks")}
                            >
                              {linkIcon}
                            </a>
                          )}
                          {licenseUrl && (
                            <a
                              href={licenseUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="zenblocks-openverse-image-selector__action-icon"
                              title={__("License", "zenblocks")}
                              aria-label={__("License", "zenblocks")}
                            >
                              {check}
                            </a>
                          )}
                        </div>
                      );
                    })()}
                  </div>
                ))}
              </div>

              {hasMore && (
                <div className="zenblocks-openverse-image-selector__actions">
                  <Button
                    variant="secondary"
                    onClick={() => searchVideos({ nextPage: page + 1, append: true })}
                    disabled={isSearching}
                  >
                    {isSearching ? __("Loading...", "zenblocks") : __("Load more", "zenblocks")}
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default VideoProviderSelector;
