import { __, sprintf } from "@wordpress/i18n";
import { Notice } from "@wordpress/components";
import CustomSection from "../components/CustomSection";
import PropagationPanel from "../components/PropagationPanel";
import PageTargetsSelector from "../components/PageTargetsSelector";
import { NextToggleControl } from "../components/NextControls";
import { isFullFlushTargetMode } from "../utils/targetMode";

import {
  ContentRelationshipsSectionSlot,
  PostTypeExpansionSectionSlot,
} from "@cache-autopilot/invalidator-settings-feature-panels";

const CACHE_INVALIDATOR_DOCS_URL =
  "https://wpcacheautopilot.com/docs/cache-invalidator/";

const POST_TYPE_PANEL_HELP_URLS = {
    targetPages: `${CACHE_INVALIDATOR_DOCS_URL}#target-pages`,
    archiveTargets: `${CACHE_INVALIDATOR_DOCS_URL}#archive-targets`,
    propagationBehavior: `${CACHE_INVALIDATOR_DOCS_URL}#propagation-behavior`,
};

function hasExistingPostTypeSelection(selectedPostTypes, allPostTypes) {
  if (!Array.isArray(selectedPostTypes) || selectedPostTypes.length === 0) {
    return false;
  }

  const availablePostTypes = new Set(Object.keys(allPostTypes || {}));
  return selectedPostTypes.some((postType) =>
    availablePostTypes.has(`${postType || ""}`.trim()),
  );
}

export default function PostTypeTab({
  postTypeKey,
  postType,
  postTypeLabel,
  settings,
  availablePages,
  pageSelectionMeta,
  postTypeCatalog,
  publicPostTypes,
  includeNonPublicPostTypes = false,
  onIncludeNonPublicPostTypesChange,
  onUpdate,
  propagation,
  onPropagationChange,
}) {
  const isFullFlushMode = isFullFlushTargetMode(settings.target_mode);
  const isNonPublic = !!postType && !postType.public;
  const selectedRelationships = Array.isArray(settings.relationships)
    ? settings.relationships
    : [];
  const selectedExpandPostTypes = Array.isArray(settings.expand_post_types)
    ? settings.expand_post_types
    : [];
  const shouldOpenPostTypeExpansion = hasExistingPostTypeSelection(
    selectedExpandPostTypes,
    publicPostTypes,
  );

  const handleRelationshipsChange = (relationships) => {
    onUpdate({
      ...settings,
      relationships,
    });
  };

  const handleExpandPostTypesChange = (expandPostTypes) => {
    onUpdate({
      ...settings,
      expand_post_types: expandPostTypes,
    });
  };

  const handleTagsEnabledChange = (tagsEnabled) => {
    onUpdate({
      ...settings,
      tags_enabled: !!tagsEnabled,
    });
  };

  return (
      <>
          {isNonPublic && (
              <Notice status='info' isDismissible={false}>
                  {__(
                      "This post type does not provide public URLs. It can only trigger invalidation for selected target pages.",
                      "cache-autopilot",
                  )}
              </Notice>
          )}

          <CustomSection
              title={__("Target Pages", "cache-autopilot")}
              helpUrl={POST_TYPE_PANEL_HELP_URLS.targetPages}
          >
              <p className='ekesto-section-description'>
                  {sprintf(
                      __(
                          "Choose which pages should be invalidated when %s content changes.",
                          "cache-autopilot",
                      ),
                      postTypeLabel || postTypeKey,
                  )}
              </p>

              <PageTargetsSelector
                  idBase={`post-type-${postTypeKey}`}
                  availablePages={availablePages}
                  pageSelectionMeta={pageSelectionMeta}
                  targetMode={settings.target_mode || "selected"}
                  includeFullFlush={true}
                  selectedIds={settings.target_page_ids || []}
                  onTargetModeChange={(targetMode) =>
                      onUpdate({
                          ...settings,
                          target_mode: targetMode,
                      })
                  }
                  onSelectedIdsChange={(targetPageIds) =>
                      onUpdate({
                          ...settings,
                          target_page_ids: targetPageIds,
                      })
                  }
              />
          </CustomSection>

          {!isFullFlushMode && (
              <ContentRelationshipsSectionSlot
                  postTypeCatalog={postTypeCatalog}
                  relationships={selectedRelationships}
                  onChange={handleRelationshipsChange}
                  includeNonPublicPostTypes={includeNonPublicPostTypes}
                  onIncludeNonPublicPostTypesChange={
                      onIncludeNonPublicPostTypesChange
                  }
              />
          )}

          {!isFullFlushMode && !isNonPublic && (
              <CustomSection
                  title={__("Archive Targets", "cache-autopilot")}
                  helpUrl={POST_TYPE_PANEL_HELP_URLS.archiveTargets}
                  collapsible={true}
                  initialOpen={false}
              >
                  <NextToggleControl
                      label={__("Post type archive URL", "cache-autopilot")}
                      help={__(
                          "Include this post type archive URL when this post type contributes to invalidation.",
                          "cache-autopilot",
                      )}
                      checked={!!settings.archives_enabled}
                      onChange={(value) => {
                          onUpdate({
                              ...settings,
                              archives_enabled: !!value,
                          });
                      }}
                  />
                  <NextToggleControl
                      label={__("Taxonomy archive URLs", "cache-autopilot")}
                      help={__(
                          "Include taxonomy archive pages (categories, tags) as invalidation targets.",
                          "cache-autopilot",
                      )}
                      checked={!!settings.taxonomy_archives_enabled}
                      onChange={(value) => {
                          onUpdate({
                              ...settings,
                              taxonomy_archives_enabled: !!value,
                          });
                      }}
                  />
              </CustomSection>
          )}

          {!isFullFlushMode && !isNonPublic && (
              <PostTypeExpansionSectionSlot
                  initialOpen={shouldOpenPostTypeExpansion}
                  postTypeCatalog={publicPostTypes}
                  relationships={selectedExpandPostTypes}
                  onChange={handleExpandPostTypesChange}
              />
          )}

          {!isFullFlushMode && !isNonPublic && (
              <CustomSection
                  title={__("Propagation Behavior", "cache-autopilot")}
                  helpUrl={POST_TYPE_PANEL_HELP_URLS.propagationBehavior}
                  collapsible={true}
                  initialOpen={false}
              >
                  {propagation && onPropagationChange && (
                      <PropagationPanel
                          propagation={propagation}
                          onChange={onPropagationChange}
                          tagsEnabled={!!settings.tags_enabled}
                          onTagsEnabledChange={handleTagsEnabledChange}
                          disabled={isFullFlushMode}
                      />
                  )}
              </CustomSection>
          )}
      </>
  );
}
