import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Edit, MapPin, Zap, Building2, Image, Package } from 'lucide-react';
import { type SubmissionItemWithDeps } from '@/lib/submissionItemsService';
import { useIsMobile } from '@/hooks/use-mobile';
import { PhotoSubmissionDisplay } from './PhotoSubmissionDisplay';
import { SubmissionChangesDisplay } from './SubmissionChangesDisplay';
import { ValidationSummary } from './ValidationSummary';
import { useState, useCallback } from 'react';
import { ValidationResult } from '@/lib/entityValidationSchemas';

interface ItemReviewCardProps {
  item: SubmissionItemWithDeps;
  onEdit: () => void;
  onStatusChange: (status: 'approved' | 'rejected') => void;
  submissionId: string;
}

export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: ItemReviewCardProps) {
  const isMobile = useIsMobile();
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [validationKey, setValidationKey] = useState(0);
  
  const handleValidationChange = useCallback((result: ValidationResult) => {
    setValidationResult(result);
  }, []);
  
  const getItemIcon = () => {
    switch (item.item_type) {
      case 'park': return <MapPin className="w-4 h-4" />;
      case 'ride': return <Zap className="w-4 h-4" />;
      case 'manufacturer':
      case 'operator':
      case 'property_owner':
      case 'designer': return <Building2 className="w-4 h-4" />;
      case 'ride_model': return <Package className="w-4 h-4" />;
      case 'photo': return <Image className="w-4 h-4" />;
      default: return null;
    }
  };

  const getStatusColor = () => {
    switch (item.status) {
      case 'approved': return 'default';
      case 'rejected': return 'destructive';
      case 'pending': return 'secondary';
      default: return 'outline';
    }
  };

  const getValidationBadgeVariant = (): "default" | "secondary" | "destructive" | "outline" => {
    if (!validationResult) return 'outline';
    if (validationResult.blockingErrors.length > 0) return 'destructive';
    if (validationResult.warnings.length > 0) return 'outline';
    return 'secondary';
  };

  const getValidationBadgeLabel = () => {
    if (!validationResult) return 'Validating...';
    if (validationResult.blockingErrors.length > 0) return '❌ Errors';
    if (validationResult.warnings.length > 0) return '⚠️ Warnings';
    return '✓ Valid';
  };

  const renderItemPreview = () => {
    // Use detailed view for review manager with photo detection
    return (
      <SubmissionChangesDisplay 
        item={item} 
        view="detailed" 
        showImages={true}
        submissionId={submissionId}
      />
    );
  };

  const hasBlockingErrors = validationResult && validationResult.blockingErrors.length > 0;

  return (
    <Card className={`w-full ${hasBlockingErrors ? 'border-destructive border-2' : ''}`}>
      <CardHeader className={isMobile ? "pb-3 p-4" : "pb-3"}>
        <div className={`flex gap-2 ${isMobile ? 'flex-col' : 'items-start justify-between'}`}>
          <div className="flex items-center gap-2 flex-wrap">
            {getItemIcon()}
            <CardTitle className={isMobile ? "text-sm" : "text-base"}>
              {item.item_type.replace('_', ' ').toUpperCase()}
            </CardTitle>
            {(item.original_data && Object.keys(item.original_data).length > 0 && (
              <Badge variant="secondary" className="text-xs bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300 border border-blue-300 dark:border-blue-700">
                <Edit className="w-3 h-3 mr-1" />
                Moderator Edited
              </Badge>
            )) as React.ReactNode}
            {hasBlockingErrors && (
              <Badge variant="destructive" className="text-xs">
                Blocked
              </Badge>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Badge variant={getStatusColor()} className={isMobile ? "text-xs" : ""}>
              {item.status}
            </Badge>
            <Badge variant={getValidationBadgeVariant()} className={isMobile ? "text-xs" : ""}>
              {getValidationBadgeLabel()}
            </Badge>
            {item.status === 'pending' && (
              <Button
                size={isMobile ? "default" : "sm"}
                variant="ghost"
                onClick={onEdit}
                className={isMobile ? "h-9 px-3" : ""}
              >
                <Edit className={isMobile ? "w-4 h-4" : "w-3 h-3"} />
                {isMobile && <span className="ml-2">Edit</span>}
              </Button>
            )}
          </div>
        </div>
      </CardHeader>
      <CardContent className={isMobile ? "p-4 pt-0" : ""}>
        {renderItemPreview()}
        
        {/* Validation Summary */}
        <div className="border-t pt-4 mt-4">
          <ValidationSummary
            item={{
              item_type: item.item_type,
              item_data: item.item_data as import('@/types/moderation').SubmissionItemData,
              id: item.id,
            }}
            onValidationChange={handleValidationChange}
            compact={false}
            validationKey={validationKey}
          />
        </div>
        
        {item.depends_on && (
          <div className="mt-3 pt-3 border-t">
            <p className={`text-muted-foreground ${isMobile ? 'text-xs' : 'text-xs'}`}>
              Depends on another item in this submission
            </p>
          </div>
        )}

        {item.rejection_reason && (
          <div className="mt-3 pt-3 border-t">
            <p className={`font-medium text-destructive ${isMobile ? 'text-xs' : 'text-xs'}`}>
              Rejection Reason:
            </p>
            <p className={`text-muted-foreground mt-1 ${isMobile ? 'text-xs' : 'text-xs'}`}>
              {item.rejection_reason}
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
