import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Check, Loader2, Clock, AlertCircle, Waves, Settings, GitCompare, ArrowRight, CheckCircle2 } from "lucide-react";
import { cn } from "@/lib/utils";
import type { TransformJob } from "@shared/schema";
import { pipelineStages } from "@shared/schema";

interface ProcessingPipelineProps {
  job?: TransformJob;
}

const stageIcons: Record<string, React.ReactNode> = {
  analyzing_source: <Waves className="h-4 w-4" />,
  analyzing_target: <Waves className="h-4 w-4" />,
  extracting_features: <Settings className="h-4 w-4" />,
  transforming: <ArrowRight className="h-4 w-4" />,
  matching: <GitCompare className="h-4 w-4" />,
  finalizing: <CheckCircle2 className="h-4 w-4" />,
};

export function ProcessingPipeline({ job }: ProcessingPipelineProps) {
  const getStageStatus = (stageId: string) => {
    if (!job) return "pending";
    if (job.status === "error") return "error";
    if (job.status === "completed") return "completed";

    const currentIndex = pipelineStages.findIndex((s) => s.id === job.status);
    const stageIndex = pipelineStages.findIndex((s) => s.id === stageId);

    if (stageIndex < currentIndex) return "completed";
    if (stageIndex === currentIndex) return "active";
    return "pending";
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "completed":
        return <Check className="h-4 w-4 text-green-500" />;
      case "active":
        return <Loader2 className="h-4 w-4 animate-spin text-primary" />;
      case "error":
        return <AlertCircle className="h-4 w-4 text-destructive" />;
      default:
        return <Clock className="h-4 w-4 text-muted-foreground" />;
    }
  };

  const isProcessing = job && job.status !== "pending" && job.status !== "completed" && job.status !== "error";

  return (
    <Card className="overflow-visible">
      <CardHeader className="py-4 px-6">
        <div className="flex items-center justify-between gap-2">
          <CardTitle className="text-lg">Processing Pipeline</CardTitle>
          {isProcessing && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin text-primary" />
              <span>{job.progress}% Complete</span>
            </div>
          )}
          {job?.status === "completed" && (
            <div className="flex items-center gap-2 text-sm text-green-500">
              <Check className="h-4 w-4" />
              <span>Transformation Complete</span>
            </div>
          )}
        </div>
      </CardHeader>
      <CardContent className="px-6 pb-6 pt-0">
        {isProcessing && (
          <Progress value={job.progress} className="mb-6 h-2" />
        )}

        <div className="relative">
          <div className="absolute left-[15px] top-0 bottom-0 w-0.5 bg-border" />

          <div className="space-y-4">
            {pipelineStages.map((stage, index) => {
              const status = getStageStatus(stage.id);
              const isActive = status === "active";
              const isCompleted = status === "completed";

              return (
                <div
                  key={stage.id}
                  className={cn(
                    "relative flex items-start gap-4 pl-10",
                    isActive && "font-medium"
                  )}
                  data-testid={`pipeline-stage-${stage.id}`}
                >
                  <div
                    className={cn(
                      "absolute left-0 flex h-8 w-8 items-center justify-center rounded-full border-2 bg-background z-10 transition-colors",
                      isCompleted && "border-green-500 bg-green-500/10",
                      isActive && "border-primary bg-primary/10",
                      status === "error" && "border-destructive bg-destructive/10",
                      status === "pending" && "border-border bg-background"
                    )}
                  >
                    {getStatusIcon(status)}
                  </div>

                  <div className="flex-1 pt-1">
                    <div className="flex items-center gap-2">
                      <span
                        className={cn(
                          "text-sm",
                          isCompleted && "text-green-500",
                          isActive && "text-primary",
                          status === "pending" && "text-muted-foreground"
                        )}
                      >
                        {stage.label}
                      </span>
                      {isActive && (
                        <span className="text-xs text-muted-foreground animate-pulse">
                          Processing...
                        </span>
                      )}
                    </div>

                    {isActive && job && (
                      <div className="mt-2 text-xs text-muted-foreground">
                        {stage.id === "analyzing_source" && "Extracting pitch, formants, and spectral features from source..."}
                        {stage.id === "analyzing_target" && "Analyzing target voice characteristics..."}
                        {stage.id === "extracting_features" && "Computing MFCC coefficients and harmonic ratios..."}
                        {stage.id === "transforming" && "Applying PSOLA pitch shifting and formant mapping..."}
                        {stage.id === "matching" && "Iteratively matching voice parameters..."}
                        {stage.id === "finalizing" && "Encoding final audio output..."}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {job?.status === "error" && job.errorMessage && (
          <div className="mt-4 p-3 rounded-md bg-destructive/10 text-destructive text-sm" data-testid="text-error-message">
            <div className="flex items-start gap-2">
              <AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
              <span>{job.errorMessage}</span>
            </div>
          </div>
        )}

        {!job && (
          <div className="flex flex-col items-center justify-center py-6 text-muted-foreground">
            <Clock className="h-8 w-8 mb-2 opacity-50" />
            <p className="text-sm">Upload files and start transformation</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
