import { useEffect, useState } from "react";
import { Mic, Volume2, CheckCircle2, Info } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { VoiceCapability } from "../../hooks/useHardwareInfo";

interface VoiceStepProps {
  onEnable: () => void;
  onSkip: () => void;
  voiceCapability?: VoiceCapability;
}

export function VoiceStep({ onEnable, onSkip, voiceCapability }: VoiceStepProps) {
  const [micAvailable, setMicAvailable] = useState<boolean | null>(null);

  useEffect(() => {
    navigator.mediaDevices?.enumerateDevices()
      .then(devices => setMicAvailable(devices.some(d => d.kind === "audioinput")))
      .catch(() => setMicAvailable(false));
  }, []);

  // Determine STT status label
  function whisperStatusLabel(): string {
    if (!voiceCapability) {
      if (micAvailable === false) return "No microphone detected -- unavailable";
      if (micAvailable === true) return "Microphone detected -- speak to your assistant";
      return "Checking microphone...";
    }
    if (voiceCapability.whisperAvailable) return "Whisper detected -- speech recognition ready";
    return "Whisper not found -- install whisper-cpp for voice input";
  }

  function whisperBadge() {
    if (!voiceCapability) return null;
    if (voiceCapability.whisperAvailable) {
      return (
        <Badge variant="outline" className="text-[color:var(--chart-2)] border-[color:var(--chart-2)]/30 bg-[color:var(--chart-2)]/10 text-xs">
          Available
        </Badge>
      );
    }
    return (
      <Badge variant="outline" className="text-[color:var(--chart-4)] border-[color:var(--chart-4)]/30 bg-[color:var(--chart-4)]/10 text-xs">
        Install needed
      </Badge>
    );
  }

  // Determine TTS status label
  function piperStatusLabel(): string {
    if (!voiceCapability) {
      return "Hear responses read aloud. Runs entirely on your device -- no server needed.";
    }
    if (voiceCapability.piperAvailable) return "Piper detected -- text-to-speech ready";
    return "Piper not found -- install piper for voice output";
  }

  function piperBadge() {
    if (!voiceCapability) return null;
    if (voiceCapability.piperAvailable) {
      return (
        <Badge variant="outline" className="text-[color:var(--chart-2)] border-[color:var(--chart-2)]/30 bg-[color:var(--chart-2)]/10 text-xs">
          Available
        </Badge>
      );
    }
    return (
      <Badge variant="outline" className="text-[color:var(--chart-4)] border-[color:var(--chart-4)]/30 bg-[color:var(--chart-4)]/10 text-xs">
        Install needed
      </Badge>
    );
  }

  // Insufficient hardware: show note but still allow enabling
  if (voiceCapability && !voiceCapability.voiceTierSufficient) {
    return (
      <div className="flex flex-col gap-4">
        <div className="flex items-start gap-3 rounded-lg border border-[color:var(--chart-4)]/30 bg-[color:var(--chart-4)]/5 p-4">
          <Info className="h-5 w-5 text-[color:var(--chart-4)] shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-medium">Limited hardware for voice</p>
            <p className="text-sm text-muted-foreground mt-1">
              Voice features require at least 4GB free RAM. Transcription may be slower on your system.
            </p>
          </div>
        </div>

        <div className="flex flex-col gap-2">
          <Button onClick={onEnable} variant="outline" className="w-full">
            Enable voice anyway
          </Button>
          <Button variant="ghost" onClick={onSkip} className="w-full">
            Skip voice setup
          </Button>
        </div>
      </div>
    );
  }

  // Sufficient hardware or unknown -- show full UI
  const neitherBinaryFound =
    voiceCapability &&
    !voiceCapability.whisperAvailable &&
    !voiceCapability.piperAvailable;

  // CPU-only note
  const isCpuOnly = voiceCapability && !voiceCapability.whisperAvailable && !voiceCapability.piperAvailable;

  return (
    <div className="flex flex-col gap-4">
      {/* Install note when tier is sufficient but binaries are missing */}
      {neitherBinaryFound && (
        <div className="flex items-start gap-3 rounded-lg border border-primary/20 bg-primary/5 p-4">
          <Info className="h-5 w-5 text-primary shrink-0 mt-0.5" />
          <p className="text-sm text-muted-foreground">
            Install whisper-cpp and piper for local voice features. You can enable voice now and configure binaries later.
          </p>
        </div>
      )}

      {/* CPU-only note */}
      {voiceCapability?.voiceTierSufficient && !voiceCapability.whisperAvailable && (
        <p className="text-sm text-muted-foreground">
          Works on CPU -- transcription may take a few extra seconds.
        </p>
      )}

      <div className="flex flex-col gap-3">
        <div className="flex items-center gap-3 rounded-lg border border-border p-4">
          <Mic className="h-5 w-5 text-primary shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-medium">Speech-to-Text (Whisper)</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              {whisperStatusLabel()}
            </p>
          </div>
          {whisperBadge()}
        </div>

        <div className="flex items-center gap-3 rounded-lg border border-border p-4">
          <Volume2 className="h-5 w-5 text-primary shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-medium">Text-to-Speech (Piper)</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              {piperStatusLabel()}
            </p>
          </div>
          {piperBadge()}
        </div>
      </div>

      <div className="flex flex-col gap-2">
        <Button
          onClick={onEnable}
          className="w-full"
          variant={neitherBinaryFound ? "outline" : "default"}
        >
          Enable voice
        </Button>
        <Button variant="ghost" onClick={onSkip} className="w-full">
          Skip
        </Button>
      </div>
    </div>
  );
}
