import { useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ArrowDown, AlertCircle } from 'lucide-react';
import { type SubmissionItemWithDeps } from '@/lib/submissionItemsService';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useIsMobile } from '@/hooks/use-mobile';
import { DependencyTreeView } from './DependencyTreeView';

interface DependencyVisualizerProps {
  items: SubmissionItemWithDeps[];
  selectedIds: Set<string>;
}

export function DependencyVisualizer({ items, selectedIds }: DependencyVisualizerProps) {
  const isMobile = useIsMobile();
  
  const dependencyLevels = useMemo(() => {
    const levels: SubmissionItemWithDeps[][] = [];
    const visited = new Set<string>();

    const getRootItems = () => items.filter(item => !item.depends_on);
    
    const addLevel = (currentItems: SubmissionItemWithDeps[]) => {
      if (currentItems.length === 0) return;
      
      const nextLevel: SubmissionItemWithDeps[] = [];
      currentItems.forEach(item => {
        if (!visited.has(item.id)) {
          visited.add(item.id);
          if (item.dependents) {
            nextLevel.push(...item.dependents);
          }
        }
      });

      levels.push(currentItems);
      addLevel(nextLevel);
    };

    addLevel(getRootItems());
    return levels;
  }, [items]);

  const hasCircularDependency = items.length > 0 && dependencyLevels.flat().length !== items.length;

  return (
    <div className="space-y-6">
      {/* Compact dependency tree view */}
      <DependencyTreeView items={items} />
      
      {hasCircularDependency && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            Circular dependency detected! This submission needs admin review.
          </AlertDescription>
        </Alert>
      )}

      {dependencyLevels.length === 0 && (
        <Alert>
          <AlertDescription>
            No dependencies found in this submission
          </AlertDescription>
        </Alert>
      )}

      {dependencyLevels.map((level, levelIdx) => (
        <div key={levelIdx} className="space-y-3">
          <div className="flex items-center gap-2">
            <h4 className={`font-medium text-muted-foreground ${isMobile ? 'text-xs' : 'text-sm'}`}>
              Level {levelIdx + 1}
            </h4>
            <div className="flex-1 h-px bg-border" />
          </div>

          <div className={`grid gap-3 ${isMobile ? 'grid-cols-1' : 'grid-cols-1 md:grid-cols-2'}`}>
            {level.map((item) => (
              <Card 
                key={item.id}
                className={`${
                  selectedIds.has(item.id) 
                    ? 'ring-2 ring-primary' 
                    : ''
                } ${isMobile ? 'touch-manipulation' : ''}`}
              >
                <CardHeader className={isMobile ? "pb-2 p-4" : "pb-2"}>
                  <div className="flex items-center justify-between gap-2">
                    <CardTitle className={isMobile ? "text-xs" : "text-sm"}>
                      {item.item_type.replace('_', ' ').toUpperCase()}
                    </CardTitle>
                    <Badge 
                      variant={
                        item.status === 'approved' ? 'default' :
                        item.status === 'rejected' ? 'destructive' :
                        'secondary'
                      }
                      className={isMobile ? "text-xs shrink-0" : ""}
                    >
                      {item.status}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className={isMobile ? "p-4 pt-0" : ""}>
                  <p className={`font-medium ${isMobile ? 'text-sm' : 'text-sm'}`}>
                    {typeof item.item_data === 'object' && item.item_data !== null && !Array.isArray(item.item_data) && 'name' in item.item_data
                      ? String((item.item_data as Record<string, unknown>).name)
                      : 'Unnamed'}
                  </p>
                  {item.dependents && item.dependents.length > 0 && (
                    <p className={`text-muted-foreground mt-1 ${isMobile ? 'text-xs' : 'text-xs'}`}>
                      Has {item.dependents.length} dependent(s)
                    </p>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>

          {levelIdx < dependencyLevels.length - 1 && (
            <div className="flex justify-center py-2">
              <ArrowDown className={isMobile ? "w-4 h-4 text-muted-foreground" : "w-5 h-5 text-muted-foreground"} />
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
