/**
 * AiSuggestionBadge Component
 *
 * Displays an AI suggestion with accept/dismiss actions.
 * Used for inline validation suggestions on Name and Description fields.
 *
 * For description fields, starts collapsed (just icon + count) and expands on click.
 * For name fields, uses compact inline mode with an editable suggestion.
 */

import { useState, useEffect } from 'react';
import { Check, X, Sparkles, AlertCircle, ChevronDown, ChevronUp, Info, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';

interface AiSuggestionBadgeProps {
  /** The suggested value */
  suggestion: string;
  /** List of issues found (optional) */
  issues?: string[];
  /** Called when user accepts the suggestion (receives the possibly-edited value) */
  onAccept: (editedValue: string) => void;
  /** Called when user dismisses the suggestion */
  onDismiss: () => void;
  /** Called to refresh (re-run) the AI validation */
  onRevalidate?: () => void;
  /** Whether re-validation is in progress */
  isRevalidating?: boolean;
  /** Additional CSS classes */
  className?: string;
  /** Whether to show the suggestion as compact (inline) - used for name field */
  compact?: boolean;
  /** Whether to start in collapsible mode (icon + count) - used for description field */
  collapsible?: boolean;
}

export function AiSuggestionBadge({
  suggestion,
  issues = [],
  onAccept,
  onDismiss,
  onRevalidate,
  isRevalidating = false,
  className,
  compact = false,
  collapsible = false
}: AiSuggestionBadgeProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [editedValue, setEditedValue] = useState(suggestion);

  // Reset edited value when suggestion changes (e.g. after refresh)
  useEffect(() => {
    setEditedValue(suggestion);
  }, [suggestion]);

  // Compact mode for name fields - inline editable suggestion with accept/dismiss
  if (compact) {
    return (
      <div
        className={cn(
          'flex items-center justify-between gap-1.5 px-2 py-1 rounded-md text-xs',
          'bg-purple-50 border border-purple-200',
          'dark:bg-purple-950/30 dark:border-purple-800',
          className
        )}
      >
        <div className="flex items-start gap-1.5 flex-1 min-w-0">
        <Sparkles className="h-3 w-3 text-purple-500 flex-shrink-0 mt-0.5" />

        <input
          type="text"
          value={editedValue}
          onChange={(e) => setEditedValue(e.target.value)}
          className="flex-1 min-w-0 bg-transparent text-purple-700 dark:text-purple-300 text-xs outline-none border-b border-transparent focus:border-purple-300 dark:focus:border-purple-600 transition-colors"
        />
        </div>
        <div className="flex items-center gap-[0px] flex-shrink-0">
          <TooltipProvider>
            <Tooltip delayDuration={200}>
              <TooltipTrigger asChild>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-4 w-4 p-0 [&_svg]:size-3.5 text-green-600 hover:text-green-700 hover:bg-green-100"
                  onClick={(e) => {
                    e.stopPropagation();
                    onAccept(editedValue);
                  }}
                >
                  <Check className="h-3 w-3" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="top">
                <p>Accept suggestion</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
          <TooltipProvider>
            <Tooltip delayDuration={200}>
              <TooltipTrigger asChild>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-4 w-4 p-0 [&_svg]:size-3.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100"
                  onClick={(e) => {
                    e.stopPropagation();
                    onDismiss();
                  }}
                >
                  <X className="h-3 w-3" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="top">
                <p>Ignore</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
          {/* Refresh button */}
          {onRevalidate && (
            <TooltipProvider>
              <Tooltip delayDuration={200}>
                <TooltipTrigger asChild>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-4 w-4 p-0 mr-[1px] [&_svg]:size-3 text-purple-400 hover:text-purple-600 hover:bg-purple-100"
                    disabled={isRevalidating}
                    onClick={(e) => {
                      e.stopPropagation();
                      onRevalidate();
                    }}
                  >
                    <RefreshCw className={cn(isRevalidating && "animate-spin")} />
                  </Button>
                </TooltipTrigger>
                <TooltipContent side="top">
                  <p>Refresh suggestion</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
          {/* Info icon with issues tooltip */}
        {issues.length > 0 && (
          <TooltipProvider>
            <Tooltip delayDuration={200}>
              <TooltipTrigger asChild>
                <Button 
                  variant="ghost" 
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                  className="h-4 w-4 p-0 [&_svg]:size-3.5 text-purple-400 hover:text-purple-600 hover:bg-purple-100"
                >
                  <Info className="h-3.5 w-3.5" />
                </Button>
              </TooltipTrigger>  
              <TooltipContent
                side="top"
                align="start"
                className="max-w-[300px] p-2"
              >
                <div className="flex flex-col gap-1">
                  <div className="text-xs font-medium text-purple-300 mb-1">
                    Issues found:
                  </div>
                  {issues.map((issue, index) => (
                    <div
                      key={index}
                      className="flex items-start gap-1.5 text-xs"
                    >
                      <AlertCircle className="h-3 w-3 mt-0.5 flex-shrink-0 text-purple-300" />
                      <span>{issue}</span>
                    </div>
                  ))}
                </div>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        )}
        </div>
      </div>
    );
  }

  // Collapsible mode for description fields
  if (collapsible && !isExpanded) {
    return (
      <button
        type="button"
        onClick={(e) => {
          e.stopPropagation();
          setIsExpanded(true);
        }}
        className={cn(
          'flex items-center gap-1.5 px-2 py-1 rounded-md text-xs',
          'bg-purple-50 border border-purple-200 hover:bg-purple-100',
          'dark:bg-purple-950/30 dark:border-purple-800 dark:hover:bg-purple-900/40',
          'transition-colors cursor-pointer',
          className
        )}
        title="Click to see AI suggestion"
      >
        <Sparkles className="h-3.5 w-3.5 text-purple-500" />
        <span className="text-purple-600 dark:text-purple-400 font-medium">
          {issues.length} {issues.length === 1 ? 'issue' : 'issues'}
        </span>
        <ChevronDown className="h-3 w-3 text-purple-400" />
      </button>
    );
  }

  // Expanded view (default for non-compact, or when collapsible is expanded)
  return (
    <div
      className={cn(
        'flex flex-col gap-2 p-3 rounded-md',
        'bg-purple-50 border border-purple-200',
        'dark:bg-purple-950/30 dark:border-purple-800',
        className
      )}
    >
      {/* Header with collapse button if collapsible */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Sparkles className="h-3.5 w-3.5 text-purple-500 flex-shrink-0" />
          <span className="text-xs font-medium text-purple-600 dark:text-purple-400">
            AI Suggestion
          </span>
          {issues.length > 0 && (
            <span className="text-xs text-purple-500 dark:text-purple-400">
              ({issues.length} {issues.length === 1 ? 'issue' : 'issues'})
            </span>
          )}
        </div>
        {collapsible && (
          <Button
            size="sm"
            variant="ghost"
            className="h-5 w-5 p-0 text-purple-400 hover:text-purple-600"
            onClick={(e) => {
              e.stopPropagation();
              setIsExpanded(false);
            }}
            title="Collapse"
          >
            <ChevronUp className="h-3.5 w-3.5" />
          </Button>
        )}
      </div>

      {/* Issues list */}
      {issues.length > 0 && (
        <div className="flex flex-col gap-1 text-xs">
          {issues.map((issue, index) => (
            <div
              key={index}
              className="flex items-start gap-1.5 text-purple-600 dark:text-purple-400"
            >
              <AlertCircle className="h-3 w-3 mt-0.5 flex-shrink-0 text-purple-400" />
              <span>{issue}</span>
            </div>
          ))}
        </div>
      )}

      {/* Suggested description */}
      <div className="mt-1">
        <div className="text-xs text-purple-500 dark:text-purple-400 mb-1 font-medium">
          Suggested:
        </div>
        <div className="text-sm text-purple-700 dark:text-purple-300 leading-relaxed bg-white/50 dark:bg-black/20 rounded p-2 border border-purple-100 dark:border-purple-800">
          {suggestion}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 mt-1">
        <Button
          size="sm"
          variant="outline"
          className="h-7 px-3 text-xs bg-white border-green-300 text-green-700 hover:bg-green-50 hover:border-green-400 dark:bg-green-950/30 dark:border-green-700 dark:text-green-400"
          onClick={(e) => {
            e.stopPropagation();
            onAccept(suggestion);
          }}
        >
          <Check className="h-3 w-3 mr-1" />
          Accept
        </Button>
        <Button
          size="sm"
          variant="ghost"
          className="h-7 px-3 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400"
          onClick={(e) => {
            e.stopPropagation();
            onDismiss();
          }}
        >
          Dismiss
        </Button>
      </div>
    </div>
  );
}

/**
 * Loading state for AI validation
 */
export function AiValidationLoading({ className }: { className?: string }) {
  return (
    <div
      className={cn(
        'flex items-center gap-2 px-2 py-1 rounded-md text-xs',
        'bg-purple-50 border border-purple-200',
        'dark:bg-purple-950/30 dark:border-purple-800',
        className
      )}
    >
      <div className="h-3 w-3 border-2 border-purple-500 border-t-transparent rounded-full animate-spin" />
      <span className="text-purple-600 dark:text-purple-400">
        Validating with AI...
      </span>
    </div>
  );
}
