import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Download, CheckCircle, XCircle, Clock, Loader2, Files } from "lucide-react";
import { cn } from "@/lib/utils";
import type { TransformJob, BatchJob } from "@shared/schema";

interface BatchJobPanelProps {
  batchJob: BatchJob | null;
  jobs: TransformJob[];
  onDownload: (jobId: string, fileName: string) => void;
  onDownloadAll: () => void;
}

export function BatchJobPanel({
  batchJob,
  jobs,
  onDownload,
  onDownloadAll,
}: BatchJobPanelProps) {
  if (!batchJob) {
    return null;
  }

  const overallProgress = batchJob.totalJobs > 0 
    ? Math.round(((batchJob.completedJobs + batchJob.failedJobs) / batchJob.totalJobs) * 100)
    : 0;

  const hasCompletedJobs = jobs.some(job => job.status === "completed");

  const getStatusIcon = (status: TransformJob["status"]) => {
    switch (status) {
      case "completed":
        return <CheckCircle className="h-4 w-4 text-green-500" />;
      case "error":
        return <XCircle className="h-4 w-4 text-red-500" />;
      case "pending":
        return <Clock className="h-4 w-4 text-muted-foreground" />;
      default:
        return <Loader2 className="h-4 w-4 animate-spin text-primary" />;
    }
  };

  const getStatusBadge = (status: TransformJob["status"]) => {
    switch (status) {
      case "completed":
        return <Badge variant="outline" className="bg-green-500/10 text-green-600 border-green-500/30">Completed</Badge>;
      case "error":
        return <Badge variant="outline" className="bg-red-500/10 text-red-600 border-red-500/30">Failed</Badge>;
      case "pending":
        return <Badge variant="outline" className="bg-muted text-muted-foreground">Pending</Badge>;
      default:
        return <Badge variant="outline" className="bg-primary/10 text-primary border-primary/30">Processing</Badge>;
    }
  };

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Files className="h-5 w-5 text-primary" />
            <CardTitle className="text-lg">Batch Processing</CardTitle>
          </div>
          {hasCompletedJobs && (
            <Button
              size="sm"
              onClick={onDownloadAll}
              data-testid="button-download-all"
            >
              <Download className="h-4 w-4 mr-2" />
              Download All
            </Button>
          )}
        </div>
      </CardHeader>
      
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">Overall Progress</span>
            <span className="font-medium">
              {batchJob.completedJobs + batchJob.failedJobs} / {batchJob.totalJobs} completed
            </span>
          </div>
          <Progress value={overallProgress} className="h-2" />
        </div>

        <div className="flex items-center gap-4 text-sm">
          <div className="flex items-center gap-1">
            <CheckCircle className="h-4 w-4 text-green-500" />
            <span>{batchJob.completedJobs} Success</span>
          </div>
          <div className="flex items-center gap-1">
            <XCircle className="h-4 w-4 text-red-500" />
            <span>{batchJob.failedJobs} Failed</span>
          </div>
          <div className="flex items-center gap-1">
            <Loader2 className={cn("h-4 w-4", batchJob.status === "processing" && "animate-spin text-primary")} />
            <span>
              {batchJob.totalJobs - batchJob.completedJobs - batchJob.failedJobs} Remaining
            </span>
          </div>
        </div>

        <ScrollArea className="h-[250px]">
          <div className="space-y-2 pr-4">
            {jobs.map((job, index) => (
              <div
                key={job.id}
                className="flex items-center gap-3 p-3 rounded-md bg-accent/30"
                data-testid={`batch-job-item-${index}`}
              >
                {getStatusIcon(job.status)}
                
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">
                    {job.targetFileName}
                  </p>
                  <div className="flex items-center gap-2 mt-1">
                    {getStatusBadge(job.status)}
                    {job.status !== "pending" && job.status !== "completed" && job.status !== "error" && (
                      <span className="text-xs text-muted-foreground">
                        {job.progress}%
                      </span>
                    )}
                    {job.matchScore !== undefined && job.status === "completed" && (
                      <span className="text-xs text-muted-foreground">
                        Match: {job.matchScore.toFixed(1)}%
                      </span>
                    )}
                  </div>
                </div>

                {job.status === "completed" && job.resultUrl && (
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => onDownload(job.id, job.targetFileName)}
                    className="h-8 w-8"
                    data-testid={`button-download-${job.id}`}
                  >
                    <Download className="h-4 w-4" />
                  </Button>
                )}
              </div>
            ))}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
