/**
 * Presets Panel Component
 *
 * Displays available presets for the current scenario in a 2-column grid.
 * Separates standard and advanced presets into different sections.
 * Advanced presets are PRO-only features.
 * Each preset shows a preview image and can be clicked to apply to the canvas.
 * Collapsible with state persisted via Zustand.
 */

import { useCallback, useMemo, useState } from "react";
import * as Tooltip from "@radix-ui/react-tooltip";
import { ChevronDownIcon, ChevronRightIcon, LockClosedIcon } from "@radix-ui/react-icons";
import { getPresetsForScenario } from "@/registry";
import type { PresetDefinition } from "@/registry";
import { getPresetPreviewUrl, getPresetFullPreviewUrl } from "./presetPreviewMap";
import type { PriceScenario } from "@/types";
import { useLayoutPersistStore } from "@/stores/layoutPersistStore";
import { isPro } from "@/utils/license";
import { ProBadge, ProUpgradeDialog } from "@/components/Pro";

interface PresetsPanelProps {
  scenario: PriceScenario;
  onApplyPreset: (preset: PresetDefinition) => void;
}

interface PresetCardProps {
  preset: PresetDefinition;
  onApply: (preset: PresetDefinition) => void;
  isLocked?: boolean;
  onLockedClick?: () => void;
}

function PresetCard({ preset, onApply, isLocked = false, onLockedClick }: PresetCardProps) {
  const [imageError, setImageError] = useState(false);
  const previewUrl = getPresetPreviewUrl(preset.id);
  // Use fullPreview gif if defined, otherwise fall back to regular preview png
  const tooltipPreviewUrl = getPresetFullPreviewUrl(preset.fullPreview) ?? previewUrl;

  const handleClick = useCallback(() => {
    if (isLocked && onLockedClick) {
      onLockedClick();
    } else {
      onApply(preset);
    }
  }, [preset, onApply, isLocked, onLockedClick]);

  const handleImageError = useCallback(() => {
    setImageError(true);
  }, []);

  return (
    <Tooltip.Root>
      <Tooltip.Trigger asChild>
        <button
          onClick={handleClick}
          className={`group flex flex-col items-center gap-1.5 p-2 rounded-lg border border-border 
                     bg-surface hover:border-primary/50 hover:bg-primary/5 
                     transition-all duration-150 cursor-pointer w-full relative
                     ${isLocked ? "oppb-preset-card--locked" : ""}`}
        >
          {/* Pro Badge for locked presets */}
          {isLocked && (
            <div className="absolute top-1 right-1 z-10">
              <ProBadge size="sm" />
            </div>
          )}

          {/* Preview */}
          <div
            className={`w-full aspect-[2.3] rounded overflow-hidden bg-surface-secondary flex items-center justify-center relative ${isLocked ? "opacity-60" : ""}`}
          >
            {!imageError ? (
              <img src={previewUrl} alt={preset.name} className="w-full h-full object-contain" onError={handleImageError} />
            ) : (
              <div className="text-xs text-text-muted">{preset.name}</div>
            )}
            {isLocked && (
              <div className="absolute inset-0 flex items-center justify-center bg-surface/40">
                <LockClosedIcon className="w-4 h-4 text-text-muted" />
              </div>
            )}
          </div>

          {/* Name */}
          <span className="text-xs font-medium text-text-muted group-hover:text-text truncate w-full text-center">{preset.name}</span>
        </button>
      </Tooltip.Trigger>
      <Tooltip.Portal>
        <Tooltip.Content className="px-3 py-2 text-xs bg-text text-white rounded-md shadow-lg max-w-[200px] z-[9999]" sideOffset={5}>
          <div className="font-medium mb-0.5">
            {preset.name}
            {isLocked && <span className="text-amber-400 ml-1">(Pro)</span>}
          </div>
          <div className="mb-1">
            <img src={tooltipPreviewUrl} alt={`${preset.name} Preview`} className="w-full h-auto object-contain rounded" />
          </div>
          <div className="text-white/70">{preset.description}</div>
          {isLocked && <div className="text-amber-400 mt-1">Upgrade to Pro to use this preset</div>}
          <Tooltip.Arrow className="fill-text" />
        </Tooltip.Content>
      </Tooltip.Portal>
    </Tooltip.Root>
  );
}

interface PresetSectionProps {
  title: string;
  presets: PresetDefinition[];
  onApplyPreset: (preset: PresetDefinition) => void;
  isProSection?: boolean;
  userIsPro?: boolean;
  onProClick?: () => void;
}

function PresetSection({ title, presets, onApplyPreset, isProSection = false, userIsPro = true, onProClick }: PresetSectionProps) {
  if (presets.length === 0) return null;

  return (
    <div className="mb-4">
      <h4 className="oppb-presets-panel__subtitle font-medium text-text-muted uppercase tracking-wider px-0.5 flex items-center gap-2">
        {title}
        {isProSection && !userIsPro && <ProBadge size="sm" />}
      </h4>
      <div className="grid grid-cols-2 gap-2">
        {presets.map((preset) => (
          <PresetCard
            key={preset.id}
            preset={preset}
            onApply={onApplyPreset}
            isLocked={isProSection && !userIsPro}
            onLockedClick={onProClick}
          />
        ))}
      </div>
    </div>
  );
}

export function PresetsPanel({ scenario, onApplyPreset }: PresetsPanelProps) {
  // Persist collapsed state
  const isCollapsed = useLayoutPersistStore((state) => state.sidebarCollapsed.presets);
  const toggleSection = useLayoutPersistStore((state) => state.toggleSidebarSection);

  // Pro dialog state
  const [proDialogOpen, setProDialogOpen] = useState(false);

  // Pro license status
  const userIsPro = isPro();

  // Get presets for current scenario, separated by type
  const { standardPresets, advancedPresets } = useMemo(() => {
    const allPresets = getPresetsForScenario(scenario);
    return {
      standardPresets: allPresets.filter((p) => !p.isAdvanced),
      advancedPresets: allPresets.filter((p) => p.isAdvanced),
    };
  }, [scenario]);

  if (standardPresets.length === 0 && advancedPresets.length === 0) {
    return null;
  }

  return (
    <Tooltip.Provider delayDuration={300}>
      <div className="px-3 py-3 border-b border-border">
        <button
          className="flex items-center justify-between w-full text-left hover:text-text transition-colors cursor-pointer"
          onClick={() => toggleSection("presets")}
        >
          <h3 className="text-xs font-semibold text-text-muted tracking-wider m-0">Presets</h3>
          {isCollapsed ? <ChevronRightIcon className="w-4 h-4 text-text-muted" /> : <ChevronDownIcon className="w-4 h-4 text-text-muted" />}
        </button>
        {!isCollapsed && (
          <>
            <PresetSection title="Standard" presets={standardPresets} onApplyPreset={onApplyPreset} />
            <PresetSection
              title="Advanced"
              presets={advancedPresets}
              onApplyPreset={onApplyPreset}
              isProSection={true}
              userIsPro={userIsPro}
              onProClick={() => setProDialogOpen(true)}
            />
          </>
        )}
      </div>

      {/* Pro Upgrade Dialog */}
      <ProUpgradeDialog open={proDialogOpen} onOpenChange={setProDialogOpen} triggeredBy="advanced_presets" />
    </Tooltip.Provider>
  );
}
