import { useState } from 'react';
import Tooltip from './Tooltip';

export const AI_REFRESH_CLASS = [
  'inline-flex items-center justify-center shrink-0 size-[var(--spacing-4)]',
  'rounded-full cursor-pointer',
  'text-foreground-muted hover:text-foreground-secondary',
  'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 group-data-[open=true]:opacity-100 transition-opacity tfds-motion-ui-fast',
  'bg-transparent border-none p-0',
  'transition-colors tfds-motion-ui-fast',
].join(' ');

export const AI_REFRESH_VISIBLE_CLASS = [
  'inline-flex items-center justify-center shrink-0 size-[var(--spacing-4)]',
  'rounded-full cursor-pointer',
  'text-foreground-muted hover:text-foreground-secondary',
  'opacity-100',
  'bg-transparent border-none p-0',
  'transition-colors tfds-motion-ui-fast',
].join(' ');

export const AI_REFRESH_TOOLTIP_TRIGGER_CLASS = 'inline-flex shrink-0 items-center justify-center';

export const SUGGESTION_LIST_CLASS = [
  'tfds-ai-suggestion-panel',
  'inline-flex w-full flex-col rounded-md p-1 gap-0.5',
  'transition-opacity tfds-motion-ui-fast',
].join(' ');

export const SUGGESTION_ITEM_CLASS = [
  'inline-flex w-full rounded-[6px] px-3 py-1',
  'text-left text-sm leading-5 text-foreground-secondary',
  'transition-opacity tfds-motion-ui-fast',
  'disabled:cursor-not-allowed',
].join(' ');

export const AI_SUGGESTION_LIST_STYLE = {
  background: 'var(--gradient-ai-fill-1)',
};

/** 与 Skeleton AI 推荐面板骨条填充一致（事实源：--gradient-ai-fill-1） */
export const AI_SUGGESTION_PANEL_FILL_TOKEN = '--gradient-ai-fill-1';

export const AI_SUGGESTION_ITEM_STYLE = {
  background: 'transparent',
};

export const AI_SUGGESTION_ITEM_HOVER_STYLE = {
  background: 'var(--gradient-ai-fill-2)',
};

export function rotateList(list, offset = 1) {
  if (!Array.isArray(list) || list.length === 0) return [];
  const safeOffset = ((offset % list.length) + list.length) % list.length;
  if (safeOffset === 0) return [...list];
  return [...list.slice(safeOffset), ...list.slice(0, safeOffset)];
}

function normalizeTextSuggestionGroup(items) {
  const seen = new Set();
  return (Array.isArray(items) ? items : [])
    .map((item) => (typeof item === 'string' ? item.trim() : ''))
    .filter((item) => {
      if (!item || seen.has(item)) return false;
      seen.add(item);
      return true;
    });
}

export function buildSuggestionGroupsFromFlatList(items, fallbackGroups = []) {
  const baseGroup = normalizeTextSuggestionGroup(items);
  if (baseGroup.length === 0) return [];
  const serialized = new Set();
  const groups = [];

  const pushGroup = (group) => {
    const normalized = normalizeTextSuggestionGroup(group);
    if (normalized.length === 0) return;
    const key = JSON.stringify(normalized);
    if (serialized.has(key)) return;
    serialized.add(key);
    groups.push(normalized);
  };

  pushGroup(baseGroup);

  if (baseGroup.length > 1) {
    for (let offset = 1; offset < baseGroup.length; offset += 1) {
      pushGroup(rotateList(baseGroup, offset));
    }
    pushGroup([...baseGroup].reverse());
  }

  fallbackGroups.forEach(pushGroup);
  return groups;
}

const AI_REFRESH_ICON_MASK = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='black' fill-rule='evenodd' clip-rule='evenodd' d='M1 12C1 6.47715 5.47715 2 11 2C13.7624 2 16.2648 3.12139 18.0735 4.93138C18.7132 5.57146 19.3981 6.36248 20 7.09444V4C20 3.44772 20.4477 3 21 3C21.5523 3 22 3.44772 22 4V10C22 10.5523 21.5523 11 21 11H15C14.4477 11 14 10.5523 14 10C14 9.44772 14.4477 9 15 9H18.9692C18.277 8.13128 17.4165 7.10335 16.6588 6.34511C15.2098 4.89514 13.2104 4 11 4C6.58172 4 3 7.58172 3 12C3 16.4183 6.58172 20 11 20C14.6457 20 17.7243 17.5605 18.6874 14.2227C18.8406 13.6921 19.3948 13.3861 19.9255 13.5392C20.4561 13.6923 20.7622 14.2466 20.609 14.7773C19.4055 18.9481 15.5605 22 11 22C5.47715 22 1 17.5228 1 12Z'/%3E%3C/svg%3E")`;
const AI_REFRESH_ICON_STYLE = {
  width: '16px',
  height: '16px',
  display: 'block',
  flexShrink: 0,
  backgroundImage: 'var(--gradient-ai-fill-3)',
  maskImage: AI_REFRESH_ICON_MASK,
  maskRepeat: 'no-repeat',
  maskPosition: 'center',
  maskSize: 'contain',
  WebkitMaskImage: AI_REFRESH_ICON_MASK,
  WebkitMaskRepeat: 'no-repeat',
  WebkitMaskPosition: 'center',
  WebkitMaskSize: 'contain',
};

export function AiRefreshGradientIcon() {
  return <span aria-hidden="true" style={AI_REFRESH_ICON_STYLE} />;
}

export function AiRefreshButton({ onClick, ariaLabel = '刷新推荐', className = AI_REFRESH_CLASS }) {
  return (
    <Tooltip content="刷新推荐" placement="top" triggerClassName={AI_REFRESH_TOOLTIP_TRIGGER_CLASS}>
      <button
        type="button"
        className={className}
        onClick={onClick}
        aria-label={ariaLabel}
      >
        <AiRefreshGradientIcon />
      </button>
    </Tooltip>
  );
}

export default function AiSuggestionPanel({
  suggestions,
  onSelect,
  getSuggestionKey,
  getSuggestionLabel,
  getSuggestionAriaLabel,
}) {
  const [hoveredSuggestionIndex, setHoveredSuggestionIndex] = useState(-1);

  if (!Array.isArray(suggestions) || suggestions.length === 0) return null;

  return (
    <div
      className={SUGGESTION_LIST_CLASS}
      style={AI_SUGGESTION_LIST_STYLE}
      data-tfds-component="AiSuggestionPanel"
    >
      {suggestions.map((suggestion, index) => {
        const key = getSuggestionKey?.(suggestion, index) ?? `${getSuggestionLabel?.(suggestion) || index}-${index}`;
        const label = getSuggestionLabel?.(suggestion) ?? '';
        const ariaLabel = getSuggestionAriaLabel?.(suggestion, index) ?? `采纳 AI 推荐内容 ${index + 1}`;
        return (
          <button
            key={key}
            type="button"
            className={`${SUGGESTION_ITEM_CLASS} ${hoveredSuggestionIndex === index ? 'items-start' : 'items-center'}`}
            style={hoveredSuggestionIndex === index ? AI_SUGGESTION_ITEM_HOVER_STYLE : AI_SUGGESTION_ITEM_STYLE}
            onClick={() => onSelect?.(suggestion)}
            onMouseEnter={() => setHoveredSuggestionIndex(index)}
            onMouseLeave={() => setHoveredSuggestionIndex(-1)}
            aria-label={ariaLabel}
          >
            <span className={hoveredSuggestionIndex === index ? 'block w-full whitespace-normal break-words' : 'block w-full truncate'}>
              {label}
            </span>
          </button>
        );
      })}
    </div>
  );
}
