import { useState } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Play, Square, Phone, User, Bot, TrendingUp, Clock } from "lucide-react";

interface Message {
  role: "customer" | "ai";
  text: string;
  sentiment: "positive" | "neutral" | "negative";
  confidence: number;
}

const scenarios = {
  banking: {
    name: "Banking Support",
    messages: [
      { role: "customer", text: "Hi, I need help with my account balance.", sentiment: "neutral", confidence: 0.85 },
      { role: "ai", text: "Hello! I'd be happy to help you check your account balance. May I have your account number?", sentiment: "positive", confidence: 0.92 },
      { role: "customer", text: "Sure, it's 1234567890.", sentiment: "neutral", confidence: 0.88 },
      { role: "ai", text: "Thank you. Your current balance is $5,432.18. Is there anything else I can help you with?", sentiment: "positive", confidence: 0.95 },
      { role: "customer", text: "Perfect, that's all I needed. Thanks!", sentiment: "positive", confidence: 0.94 }
    ] as Message[]
  },
  healthcare: {
    name: "Healthcare Appointment",
    messages: [
      { role: "customer", text: "I'd like to schedule an appointment with Dr. Smith.", sentiment: "neutral", confidence: 0.86 },
      { role: "ai", text: "I can help you with that. Dr. Smith has availability on Tuesday at 2 PM or Thursday at 10 AM. Which works better for you?", sentiment: "positive", confidence: 0.91 },
      { role: "customer", text: "Tuesday at 2 PM would be great.", sentiment: "positive", confidence: 0.89 },
      { role: "ai", text: "Perfect! I've scheduled your appointment with Dr. Smith for Tuesday at 2 PM. You'll receive a confirmation text shortly.", sentiment: "positive", confidence: 0.96 },
      { role: "customer", text: "Excellent, thank you so much!", sentiment: "positive", confidence: 0.95 }
    ] as Message[]
  },
  retail: {
    name: "Retail Customer Service",
    messages: [
      { role: "customer", text: "I received a damaged product. What can I do?", sentiment: "negative", confidence: 0.82 },
      { role: "ai", text: "I'm so sorry to hear that! I'd be happy to help you with a replacement or refund. Can you provide your order number?", sentiment: "positive", confidence: 0.93 },
      { role: "customer", text: "Yes, it's ORDER-12345.", sentiment: "neutral", confidence: 0.87 },
      { role: "ai", text: "Thank you. I've initiated a replacement shipment. You'll receive it within 2-3 business days. We've also issued a prepaid return label for the damaged item.", sentiment: "positive", confidence: 0.94 },
      { role: "customer", text: "That was fast! Thank you for your help.", sentiment: "positive", confidence: 0.96 }
    ] as Message[]
  },
  insurance: {
    name: "Insurance Claim",
    messages: [
      { role: "customer", text: "I need to file a claim for a car accident.", sentiment: "negative", confidence: 0.80 },
      { role: "ai", text: "I understand, and I'm here to help you through this process. First, are you and everyone involved safe?", sentiment: "neutral", confidence: 0.90 },
      { role: "customer", text: "Yes, everyone is okay. Just vehicle damage.", sentiment: "neutral", confidence: 0.85 },
      { role: "ai", text: "I'm glad to hear everyone is safe. I've started a claim for you. Your claim number is CLM-789456. An adjuster will contact you within 24 hours.", sentiment: "positive", confidence: 0.92 },
      { role: "customer", text: "Thank you, that helps a lot.", sentiment: "positive", confidence: 0.88 }
    ] as Message[]
  }
};

export default function Simulation() {
  const { toast } = useToast();
  const [selectedScenario, setSelectedScenario] = useState<keyof typeof scenarios | "">("");
  const [isRunning, setIsRunning] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [stats, setStats] = useState({ duration: 0, avgSentiment: 0, avgConfidence: 0 });

  const speakText = (text: string) => {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = 0.85;
    utterance.pitch = 1.0;
    utterance.volume = 0.9;
    window.speechSynthesis.speak(utterance);
  };

  const startSimulation = () => {
    if (!selectedScenario) {
      toast({
        title: "Select a scenario",
        description: "Please choose a scenario to simulate.",
        variant: "destructive"
      });
      return;
    }

    setIsRunning(true);
    setMessages([]);
    setCurrentIndex(0);

    const scenarioMessages = scenarios[selectedScenario].messages;
    let index = 0;
    const startTime = Date.now();

    const interval = setInterval(() => {
      if (index >= scenarioMessages.length) {
        clearInterval(interval);
        setIsRunning(false);
        
        const duration = Math.floor((Date.now() - startTime) / 1000);
        const avgSentiment = scenarioMessages.reduce((acc, msg) => {
          return acc + (msg.sentiment === "positive" ? 1 : msg.sentiment === "negative" ? -1 : 0);
        }, 0) / scenarioMessages.length;
        const avgConfidence = scenarioMessages.reduce((acc, msg) => acc + msg.confidence, 0) / scenarioMessages.length;
        
        setStats({ duration, avgSentiment, avgConfidence });
        
        toast({
          title: "Simulation complete",
          description: `Duration: ${duration}s | Avg confidence: ${(avgConfidence * 100).toFixed(0)}%`,
        });
        return;
      }

      const message = scenarioMessages[index];
      setMessages(prev => [...prev, message]);
      setCurrentIndex(index + 1);
      
      if (message.role === "ai") {
        speakText(message.text);
      }
      
      index++;
    }, 2500);
  };

  const stopSimulation = () => {
    setIsRunning(false);
    window.speechSynthesis.cancel();
  };

  return (
    <DashboardLayout pageTitle="Voice Simulation">
      <div className="max-w-6xl mx-auto space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <Card>
            <CardHeader>
              <CardTitle>Select Scenario</CardTitle>
              <CardDescription>Choose an industry scenario to simulate</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Select value={selectedScenario} onValueChange={(value) => setSelectedScenario(value as keyof typeof scenarios)}>
                <SelectTrigger data-testid="select-scenario">
                  <SelectValue placeholder="Choose a scenario..." />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="banking">Banking Support</SelectItem>
                  <SelectItem value="healthcare">Healthcare Appointment</SelectItem>
                  <SelectItem value="retail">Retail Customer Service</SelectItem>
                  <SelectItem value="insurance">Insurance Claim</SelectItem>
                </SelectContent>
              </Select>

              <div className="flex gap-3">
                {!isRunning ? (
                  <Button
                    className="flex-1 bg-gradient-to-r from-indigo-600 to-cyan-600 hover:from-indigo-500 hover:to-cyan-500"
                    onClick={startSimulation}
                    disabled={!selectedScenario}
                    data-testid="button-start"
                  >
                    <Play className="w-4 h-4 mr-2" />
                    Start Simulation
                  </Button>
                ) : (
                  <Button
                    className="flex-1"
                    variant="destructive"
                    onClick={stopSimulation}
                    data-testid="button-stop"
                  >
                    <Square className="w-4 h-4 mr-2" />
                    Stop
                  </Button>
                )}
              </div>

              {stats.duration > 0 && (
                <div className="grid grid-cols-3 gap-3 pt-4 border-t border-border">
                  <div>
                    <div className="text-xs text-muted-foreground">Duration</div>
                    <div className="text-lg font-bold" data-testid="stat-duration">{stats.duration}s</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground">Sentiment</div>
                    <div className="text-lg font-bold" data-testid="stat-sentiment">
                      {stats.avgSentiment > 0 ? "Positive" : stats.avgSentiment < 0 ? "Negative" : "Neutral"}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground">Confidence</div>
                    <div className="text-lg font-bold" data-testid="stat-confidence">{(stats.avgConfidence * 100).toFixed(0)}%</div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Simulation Info</CardTitle>
              <CardDescription>How the simulation works</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3 text-sm text-muted-foreground">
              <p>• Messages appear every 2.5 seconds to simulate a real conversation</p>
              <p>• AI responses are spoken using browser voice synthesis</p>
              <p>• Sentiment and confidence scores are analyzed in real-time</p>
              <p>• Billing is calculated based on call duration</p>
              <p>• All simulations are logged for analytics</p>
            </CardContent>
          </Card>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Conversation</CardTitle>
            <CardDescription>
              {isRunning ? "Simulation in progress..." : messages.length > 0 ? "Simulation complete" : "Start a simulation to begin"}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3 min-h-[400px]">
              {messages.map((message, index) => (
                <div
                  key={index}
                  className={`flex items-start gap-3 ${message.role === "ai" ? "" : "flex-row-reverse"}`}
                  data-testid={`message-${index}`}
                >
                  <div className={`w-10 h-10 rounded-full flex items-center justify-center shrink-0 ${message.role === "ai" ? "bg-gradient-to-br from-indigo-600/20 to-cyan-600/20" : "bg-muted"}`}>
                    {message.role === "ai" ? <Bot className="w-5 h-5 text-indigo-400" /> : <User className="w-5 h-5 text-muted-foreground" />}
                  </div>
                  <div className={`flex-1 ${message.role === "customer" ? "text-right" : ""}`}>
                    <div className={`inline-block p-3 rounded-md ${message.role === "ai" ? "bg-card border border-border" : "bg-muted"}`}>
                      <p className="text-sm">{message.text}</p>
                      <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
                        <Badge variant={message.sentiment === "positive" ? "default" : message.sentiment === "negative" ? "destructive" : "secondary"} className="text-xs">
                          {message.sentiment}
                        </Badge>
                        <span>{(message.confidence * 100).toFixed(0)}% confident</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
