import { useEffect, useState, useMemo } from 'react';
import { AlertCircle, CheckCircle, Info, AlertTriangle, RefreshCw } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { validateEntityData, ValidationResult } from '@/lib/entityValidationSchemas';
import { logger } from '@/lib/logger';

import type { SubmissionItemData } from '@/types/moderation';

interface ValidationSummaryProps {
  item: {
    item_type: string;
    item_data: SubmissionItemData;
    id?: string;
  };
  onValidationChange?: (result: ValidationResult) => void;
  compact?: boolean;
  validationKey?: number;
}

export function ValidationSummary({ item, onValidationChange, compact = false, validationKey }: ValidationSummaryProps) {
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isExpanded, setIsExpanded] = useState(false);
  const [manualTriggerCount, setManualTriggerCount] = useState(0);

  // Helper to extract the correct entity ID based on entity type
  const getEntityId = (itemType: string, itemData: any, fallbackId?: string): string | undefined => {
    // Try entity-specific ID fields first
    const entityIdField = `${itemType}_id`;
    if (itemData[entityIdField]) {
      return itemData[entityIdField];
    }
    
    // For companies, check company_id
    if (['manufacturer', 'designer', 'operator', 'property_owner'].includes(itemType) && itemData.company_id) {
      return itemData.company_id;
    }
    
    // Fall back to generic id field or provided fallback
    return itemData.id || fallbackId;
  };

  // Create stable reference for item_data to prevent unnecessary re-validations
  const itemDataString = useMemo(
    () => JSON.stringify(item.item_data),
    [item.item_data]
  );

  useEffect(() => {
    async function validate() {
      setIsLoading(true);
      try {
        // Type guard for valid entity types
        type ValidEntityType = 'park' | 'ride' | 'manufacturer' | 'operator' | 'designer' | 'property_owner' | 'ride_model' | 'photo' | 'milestone' | 'timeline_event';
        const validEntityTypes: ValidEntityType[] = ['park', 'ride', 'manufacturer', 'operator', 'designer', 'property_owner', 'ride_model', 'photo', 'milestone', 'timeline_event'];
        
        if (!validEntityTypes.includes(item.item_type as ValidEntityType)) {
          setValidationResult({
            isValid: false,
            blockingErrors: [{ field: 'item_type', message: `Invalid entity type: ${item.item_type}`, severity: 'blocking' }],
            warnings: [],
            suggestions: [],
            allErrors: [{ field: 'item_type', message: `Invalid entity type: ${item.item_type}`, severity: 'blocking' }],
          });
          setIsLoading(false);
          return;
        }
        
      const result = await validateEntityData(
        item.item_type as ValidEntityType,
        { 
          ...item.item_data, 
          id: getEntityId(item.item_type, item.item_data, item.id)
        }
      );
        
        setValidationResult(result);
        onValidationChange?.(result);
      } catch (error: unknown) {
        logger.error('Entity validation failed', {
          action: 'validate_entity',
          entityType: item.item_type,
          error: error instanceof Error ? error.message : String(error)
        });
        setValidationResult({
          isValid: false,
          blockingErrors: [{ field: 'validation', message: 'Failed to validate', severity: 'blocking' }],
          warnings: [],
          suggestions: [],
          allErrors: [{ field: 'validation', message: 'Failed to validate', severity: 'blocking' }],
        });
      } finally {
        setIsLoading(false);
      }
    }

    validate();
  }, [item.item_type, itemDataString, item.id, validationKey, manualTriggerCount]);

  // Auto-expand when there are blocking errors or warnings
  useEffect(() => {
    if (validationResult && (validationResult.blockingErrors.length > 0 || validationResult.warnings.length > 0)) {
      setIsExpanded(true);
    }
  }, [validationResult]);

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <div className="animate-spin rounded-full h-4 w-4 border-2 border-primary border-t-transparent" />
        <span>Validating...</span>
      </div>
    );
  }

  if (!validationResult) {
    return null;
  }

  const hasBlockingErrors = validationResult.blockingErrors.length > 0;
  const hasWarnings = validationResult.warnings.length > 0;
  const hasSuggestions = validationResult.suggestions.length > 0;
  const hasAnyIssues = hasBlockingErrors || hasWarnings || hasSuggestions;

  // Compact view (for queue items) - NO HOVER, ALWAYS VISIBLE
  if (compact) {
    return (
      <div className="space-y-2">
        {/* Status Badges */}
        <div className="flex items-center gap-2 flex-wrap">
          {validationResult.isValid && !hasWarnings && !hasSuggestions && (
            <Badge variant="secondary" className="bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 border-green-300 dark:border-green-700">
              <CheckCircle className="w-3 h-3 mr-1" />
              Valid
            </Badge>
          )}
          {hasBlockingErrors && (
            <Badge variant="destructive">
              <AlertCircle className="w-3 h-3 mr-1" />
              {validationResult.blockingErrors.length} Error{validationResult.blockingErrors.length !== 1 ? 's' : ''}
            </Badge>
          )}
          {hasWarnings && (
            <Badge variant="outline" className="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700">
              <AlertTriangle className="w-3 h-3 mr-1" />
              {validationResult.warnings.length} Warning{validationResult.warnings.length !== 1 ? 's' : ''}
            </Badge>
          )}
        </div>

        {/* ALWAYS SHOW ERROR DETAILS - NO HOVER NEEDED */}
        {hasBlockingErrors && (
          <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-2">
            <p className="text-xs font-semibold text-red-800 dark:text-red-300 mb-1">Blocking Errors:</p>
            <ul className="text-xs space-y-0.5 text-red-700 dark:text-red-400">
              {validationResult.blockingErrors.map((error, i) => (
                <li key={i}>
                  • <span className="font-medium">{error.field}:</span> {error.message}
                </li>
              ))}
            </ul>
          </div>
        )}

        {hasWarnings && !hasBlockingErrors && (
          <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded p-2">
            <p className="text-xs font-semibold text-yellow-800 dark:text-yellow-300 mb-1">Warnings:</p>
            <ul className="text-xs space-y-0.5 text-yellow-700 dark:text-yellow-400">
              {validationResult.warnings.slice(0, 3).map((warning, i) => (
                <li key={i}>
                  • <span className="font-medium">{warning.field}:</span> {warning.message}
                </li>
              ))}
              {validationResult.warnings.length > 3 && (
                <li className="italic">... and {validationResult.warnings.length - 3} more</li>
              )}
            </ul>
          </div>
        )}
      </div>
    );
  }

  // Detailed view (for review manager)
  return (
    <div className="space-y-3">
      {/* Summary Badge */}
      <div className="flex items-center gap-2 flex-wrap">
        {validationResult.isValid && !hasWarnings && !hasSuggestions && (
          <Badge variant="secondary" className="bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 border-green-300 dark:border-green-700">
            <CheckCircle className="w-4 h-4 mr-1" />
            All Valid
          </Badge>
        )}
        {hasBlockingErrors && (
          <Badge variant="destructive" className="text-sm">
            <AlertCircle className="w-4 h-4 mr-1" />
            {validationResult.blockingErrors.length} Blocking Error{validationResult.blockingErrors.length !== 1 ? 's' : ''}
          </Badge>
        )}
        {hasWarnings && (
          <Badge variant="outline" className="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700 text-sm">
            <AlertTriangle className="w-4 h-4 mr-1" />
            {validationResult.warnings.length} Warning{validationResult.warnings.length !== 1 ? 's' : ''}
          </Badge>
        )}
        {hasSuggestions && (
          <Badge variant="outline" className="bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 border-blue-300 dark:border-blue-700 text-sm">
            <Info className="w-4 h-4 mr-1" />
            {validationResult.suggestions.length} Suggestion{validationResult.suggestions.length !== 1 ? 's' : ''}
          </Badge>
        )}
        
        <Button
          variant="outline"
          size="sm"
          onClick={() => setManualTriggerCount(prev => prev + 1)}
          className="text-xs h-7"
        >
          <RefreshCw className="w-3 h-3 mr-1" />
          Re-validate
        </Button>
      </div>

      {/* Detailed Issues */}
      {hasAnyIssues && (
        <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
          <CollapsibleTrigger className="text-sm text-muted-foreground hover:text-foreground transition-colors">
            {isExpanded ? 'Hide' : 'Show'} validation details
          </CollapsibleTrigger>
          <CollapsibleContent className="space-y-2 mt-2">
            {/* Blocking Errors */}
            {hasBlockingErrors && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Blocking Errors</AlertTitle>
                <AlertDescription className="space-y-1 mt-2">
                  {validationResult.blockingErrors.map((error, index) => (
                    <div key={index} className="text-sm">
                      <span className="font-medium">{error.field}:</span> {error.message}
                    </div>
                  ))}
                </AlertDescription>
              </Alert>
            )}

            {/* Warnings */}
            {hasWarnings && (
              <Alert className="border-yellow-300 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-900/20">
                <AlertTriangle className="h-4 w-4 text-yellow-800 dark:text-yellow-300" />
                <AlertTitle className="text-yellow-800 dark:text-yellow-300">Warnings</AlertTitle>
                <AlertDescription className="space-y-1 mt-2 text-yellow-800 dark:text-yellow-300">
                  {validationResult.warnings.map((warning, index) => (
                    <div key={index} className="text-sm">
                      <span className="font-medium">{warning.field}:</span> {warning.message}
                    </div>
                  ))}
                </AlertDescription>
              </Alert>
            )}

            {/* Suggestions */}
            {hasSuggestions && (
              <Alert className="border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20">
                <Info className="h-4 w-4 text-blue-800 dark:text-blue-300" />
                <AlertTitle className="text-blue-800 dark:text-blue-300">Suggestions</AlertTitle>
                <AlertDescription className="space-y-1 mt-2 text-blue-800 dark:text-blue-300">
                  {validationResult.suggestions.map((suggestion, index) => (
                    <div key={index} className="text-sm">
                      <span className="font-medium">{suggestion.field}:</span> {suggestion.message}
                    </div>
                  ))}
                </AlertDescription>
              </Alert>
            )}
          </CollapsibleContent>
        </Collapsible>
      )}
    </div>
  );
}
