'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ClassificationResult } from './classification-result';
import { DetectionResultList } from './detection-result';
import { PerformanceMetrics } from './performance-metrics';
import { ConfidenceSlider } from './confidence-slider';
import { VideoProgress } from './video-progress';
import { InferenceOptions } from './inference-options';
import { useInferenceStore } from '@/stores/inference-store';
import { useCameraStore } from '@/stores/camera-store';
import { isClassificationTask } from '@/lib/classification';
import { useTranslation } from '@/lib/i18n';

interface InferencePanelProps {
  deviceId: string;
}

export function InferencePanel({ deviceId }: InferencePanelProps) {
  const { t } = useTranslation();
  const { result, fps, avgLatency, isRunning, confidenceThreshold, batchResults } =
    useInferenceStore();
  const { sourceType, batchSelectedIndex, batchImages, batchProcessedCount } =
    useCameraStore();

  const isVideoMode = sourceType === 'video';
  const isBatchMode = sourceType === 'batch_image';
  const displayResult = isBatchMode
    ? batchResults[batchSelectedIndex]
    : result;
  const classifications = displayResult?.classifications || [];
  const detections = displayResult?.detections || [];
  // Branch on "is classification?" so detection stays the safe fall-through
  // under either taskType spelling (see lib/classification.ts).
  const isClassification = isClassificationTask(displayResult?.taskType);

  return (
    <div className="w-80 space-y-4">
      <PerformanceMetrics fps={fps} avgLatency={avgLatency} isRunning={isRunning} />

      {isVideoMode && isRunning && <VideoProgress />}

      {isBatchMode && batchImages.length > 0 && (
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">{t('inference.batchProgress')}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-1 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t('inference.processed')}</span>
              <span>{batchProcessedCount} / {batchImages.length}</span>
            </div>
            {batchImages[batchSelectedIndex] && (
              <div className="flex justify-between">
                <span className="text-muted-foreground">{t('inference.currentImage')}</span>
                <span className="truncate max-w-32 text-right">
                  {batchImages[batchSelectedIndex].filename}
                </span>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm">{t('inference.confidenceFilter')}</CardTitle>
        </CardHeader>
        <CardContent>
          <ConfidenceSlider />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm">{t('inference.options.title')}</CardTitle>
        </CardHeader>
        <CardContent>
          <InferenceOptions deviceId={deviceId} resultTaskType={displayResult?.taskType} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm">
            {isClassification
              ? t('inference.classificationResults')
              : t('inference.detectionResults')}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isClassification ? (
            <ClassificationResult
              results={classifications}
              confidenceThreshold={confidenceThreshold}
            />
          ) : (
            <DetectionResultList
              results={detections}
              confidenceThreshold={confidenceThreshold}
            />
          )}
        </CardContent>
      </Card>

      {displayResult && (
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">{t('inference.details')}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-1 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t('inference.model')}</span>
              <span>{displayResult.modelId}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t('inference.task')}</span>
              <span>{displayResult.taskType}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t('inference.latency')}</span>
              <span>{displayResult.latencyMs.toFixed(1)} ms</span>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
