/**
 * Shared renderer utilities and wrapper — used by all canvas component renderers.
 */
import { useState } from 'react';
import { motion } from 'framer-motion';
import { Database, Shield, BarChart2, Info, Users, Lock } from 'lucide-react';
import { toast } from 'sonner';
import type { CanvasComponent } from '../../types/canvas';
import type { ComponentRenderContext } from '../ComponentRegistry';

export { type ComponentRenderContext };

export const GLASS_PANEL = {
  background: 'rgba(10, 12, 20, 0.72)',
  border: '1px solid rgba(59,130,246,0.12)',
  backdropFilter: 'blur(20px)',
  WebkitBackdropFilter: 'blur(20px)',
  boxShadow: '0 6px 24px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.03)',
  borderRadius: '16px',
} as const;

const PRIVACY_COLORS = {
  standard: { color: '#22d3ee', label: 'Standard' },
  restricted: { color: '#fbbf24', label: 'Restricted' },
  sensitive: { color: '#f87171', label: 'Sensitive' },
};

interface RendererWrapperProps {
  component: CanvasComponent;
  ctx: ComponentRenderContext;
  children: React.ReactNode;
  minHeight?: number;
}

export function RendererWrapper({ component, ctx, children, minHeight = 280 }: RendererWrapperProps) {
  const [localVisibility, setLocalVisibility] = useState(component.accessControls.visibilityScope);
  const privacy = PRIVACY_COLORS[component.dataSourceDescriptor.privacyTier] ?? PRIVACY_COLORS.standard;

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.28, ease: [0.4, 0, 0.2, 1] }}
      className="group relative w-full"
      style={{ minHeight }}
      onClick={() => ctx.onSelect?.(component.componentId)}
    >
      <div
        className="h-full p-5 flex flex-col"
        style={{
          ...GLASS_PANEL,
          ...(ctx.isSelected ? {
            border: '1px solid rgba(59,130,246,0.45)',
            boxShadow: '0 0 0 2px rgba(59,130,246,0.2), 0 6px 24px rgba(0,0,0,0.45)',
          } : {}),
        }}
      >
        {/* Header */}
        <div className="flex items-start justify-between gap-3 mb-4 flex-shrink-0">
          <div className="min-w-0">
            <h3 className="text-sm font-semibold text-zinc-100 truncate">{component.title}</h3>
            {component.description && (
              <p className="text-xs text-zinc-500 mt-0.5 line-clamp-1">{component.description}</p>
            )}
          </div>
          {/* Badges */}
          <div className="flex items-center gap-1.5 flex-shrink-0">
            {ctx.showLineageBadges && (
              <span
                className="flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full"
                style={{ background: `${privacy.color}18`, color: privacy.color, border: `1px solid ${privacy.color}30` }}
                title={`Privacy tier: ${privacy.label}`}
              >
                <Shield className="w-2.5 h-2.5" />
                {privacy.label}
              </span>
            )}
            <span
              className="flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full"
              style={{ background: 'rgba(255,255,255,0.04)', color: '#52525b', border: '1px solid rgba(255,255,255,0.07)' }}
            >
              v{component.version}
            </span>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 min-h-0">
          {children}
        </div>

        {/* Footer — provenance + dataset */}
        <div className="flex items-center justify-between mt-3 pt-3 flex-shrink-0" style={{ borderTop: '1px solid rgba(255,255,255,0.05)' }}>
          <div className="flex items-center gap-2">
            <Database className="w-3 h-3 text-zinc-600" />
            <span className="text-[10px] text-zinc-600 font-mono truncate max-w-[140px]">
              {component.dataSourceDescriptor.dataset}
            </span>
          </div>
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              const isPrivate = localVisibility === 'private';
              const nextVisibility = isPrivate ? 'tenant_team' : 'private';
              setLocalVisibility(nextVisibility);
              
              if (nextVisibility === 'tenant_team') {
                toast.success('Visibility set to Team', {
                  description: 'This component is now visible to other members on this fork according to team policy.'
                });
              } else {
                toast.info('Visibility set to Private', {
                  description: 'This component is now restricted and visible only to you.'
                });
              }
            }}
            className="flex items-center gap-1.5 text-[10px] text-zinc-500 hover:text-zinc-200 transition-colors px-1.5 py-0.5 rounded hover:bg-white/10"
          >
            {localVisibility === 'private' ? (
              <>
                <Lock className="w-3 h-3" />
                <span>private</span>
              </>
            ) : (
              <>
                <Users className="w-3 h-3" />
                <span>team</span>
              </>
            )}
          </button>
        </div>
      </div>
    </motion.div>
  );
}

/** Tooltip for chart hover states */
export function GlassTooltip({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number | string; color: string }>; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <div
      className="rounded-xl px-3 py-2 text-sm shadow-2xl"
      style={{
        background: 'rgba(10,12,20,0.95)',
        border: '1px solid rgba(59,130,246,0.2)',
        backdropFilter: 'blur(8px)',
      }}
    >
      {label && <p className="text-xs text-zinc-400 mb-1">{label}</p>}
      {payload.map((p) => (
        <div key={p.name} className="flex items-center gap-2">
          <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: p.color }} />
          <span className="text-zinc-200 font-medium">{p.value}</span>
        </div>
      ))}
    </div>
  );
}

/** Lineage badge */
export function LineageBadge({ promptExecutionId }: { promptExecutionId?: string }) {
  if (!promptExecutionId) return null;
  return (
    <div
      className="flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full"
      style={{ background: 'rgba(59,130,246,0.1)', color: '#60a5fa', border: '1px solid rgba(59,130,246,0.2)' }}
      title={`Prompt execution: ${promptExecutionId}`}
    >
      <Info className="w-2.5 h-2.5" />
      Prompt-generated
    </div>
  );
}

/** No-data placeholder */
export function NoDataPlaceholder({ message = 'No data available for the selected filters.' }: { message?: string }) {
  return (
    <div className="h-full flex flex-col items-center justify-center gap-3 py-8">
      <BarChart2 className="w-10 h-10 text-zinc-700" />
      <p className="text-sm text-zinc-500 text-center max-w-xs">{message}</p>
    </div>
  );
}
