import { useState } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Phone, PhoneOff, Volume2, VolumeX, User, Bot, AlertCircle } from "lucide-react";

interface ActiveCall {
  id: string;
  customer: string;
  phone: string;
  duration: number;
  sentiment: "positive" | "neutral" | "negative";
  confidence: number;
  scenario: string;
  status: "active" | "on-hold" | "transferring";
  transcript: { role: "customer" | "ai"; text: string; timestamp: string }[];
}

export default function LiveCalls() {
  const [selectedCall, setSelectedCall] = useState<string | null>(null);

  // TODO: Remove mock data
  const activeCalls: ActiveCall[] = [
    {
      id: "1",
      customer: "Sarah Johnson",
      phone: "+1 (555) 123-4567",
      duration: 124,
      sentiment: "positive",
      confidence: 0.92,
      scenario: "Banking Support",
      status: "active",
      transcript: [
        { role: "customer", text: "Hi, I need to check my account balance.", timestamp: "14:32:15" },
        { role: "ai", text: "Hello! I'd be happy to help you with that. May I have your account number?", timestamp: "14:32:18" },
        { role: "customer", text: "Sure, it's 9876543210.", timestamp: "14:32:25" },
        { role: "ai", text: "Thank you. Let me pull that up for you. Your current balance is $5,432.18.", timestamp: "14:32:30" }
      ]
    },
    {
      id: "2",
      customer: "Michael Chen",
      phone: "+1 (555) 234-5678",
      duration: 87,
      sentiment: "neutral",
      confidence: 0.85,
      scenario: "Healthcare Appointment",
      status: "active",
      transcript: [
        { role: "customer", text: "I need to reschedule my appointment.", timestamp: "14:33:02" },
        { role: "ai", text: "I can help you with that. What date works better for you?", timestamp: "14:33:05" }
      ]
    },
    {
      id: "3",
      customer: "Emily Rodriguez",
      phone: "+1 (555) 345-6789",
      duration: 201,
      sentiment: "negative",
      confidence: 0.78,
      scenario: "Retail Customer Service",
      status: "on-hold",
      transcript: [
        { role: "customer", text: "I received a damaged product and I'm very frustrated.", timestamp: "14:30:45" },
        { role: "ai", text: "I sincerely apologize for that experience. Let me help you resolve this right away.", timestamp: "14:30:50" }
      ]
    }
  ];

  const selected = activeCalls.find(call => call.id === selectedCall);

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <DashboardLayout pageTitle="Live Calls">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[calc(100vh-12rem)]">
        <Card className="lg:col-span-1">
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle>Active Calls</CardTitle>
              <Badge variant="default" className="bg-green-600">
                {activeCalls.length} Live
              </Badge>
            </div>
            <CardDescription>Currently ongoing conversations</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {activeCalls.map((call) => (
              <div
                key={call.id}
                className={`p-3 rounded-md cursor-pointer hover-elevate border ${selectedCall === call.id ? 'border-indigo-600/50 bg-indigo-600/5' : 'border-border'}`}
                onClick={() => setSelectedCall(call.id)}
                data-testid={`call-${call.id}`}
              >
                <div className="flex items-start justify-between gap-2 mb-2">
                  <div className="flex-1 min-w-0">
                    <div className="font-medium truncate">{call.customer}</div>
                    <div className="text-sm text-muted-foreground truncate">{call.phone}</div>
                  </div>
                  <div className="flex items-center gap-1">
                    <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
                    <span className="text-sm font-mono">{formatDuration(call.duration)}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={call.sentiment === "positive" ? "default" : call.sentiment === "negative" ? "destructive" : "secondary"} className="text-xs">
                    {call.sentiment}
                  </Badge>
                  <Badge variant={call.status === "active" ? "default" : "secondary"} className="text-xs">
                    {call.status}
                  </Badge>
                  <span className="text-xs text-muted-foreground">{Math.round(call.confidence * 100)}%</span>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>

        <Card className="lg:col-span-2">
          {selected ? (
            <>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>{selected.customer}</CardTitle>
                    <CardDescription>{selected.scenario} • {selected.phone}</CardDescription>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button size="sm" variant="outline" data-testid="button-mute">
                      <Volume2 className="w-4 h-4 mr-2" />
                      Mute
                    </Button>
                    <Button size="sm" variant="destructive" data-testid="button-end-call">
                      <PhoneOff className="w-4 h-4 mr-2" />
                      End Call
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-6">
                  <div className="grid grid-cols-3 gap-4 p-4 rounded-md bg-muted/50">
                    <div>
                      <div className="text-sm text-muted-foreground">Duration</div>
                      <div className="text-lg font-bold" data-testid="call-duration">{formatDuration(selected.duration)}</div>
                    </div>
                    <div>
                      <div className="text-sm text-muted-foreground">Sentiment</div>
                      <div className="text-lg font-bold capitalize" data-testid="call-sentiment">{selected.sentiment}</div>
                    </div>
                    <div>
                      <div className="text-sm text-muted-foreground">Confidence</div>
                      <div className="text-lg font-bold" data-testid="call-confidence">{Math.round(selected.confidence * 100)}%</div>
                    </div>
                  </div>

                  <div>
                    <h3 className="text-sm font-medium mb-3">Live Transcript</h3>
                    <div className="space-y-3 max-h-[400px] overflow-y-auto">
                      {selected.transcript.map((message, index) => (
                        <div
                          key={index}
                          className={`flex items-start gap-3 ${message.role === "ai" ? "" : "flex-row-reverse"}`}
                          data-testid={`transcript-${index}`}
                        >
                          <div className={`w-8 h-8 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-4 h-4 text-indigo-400" /> : <User className="w-4 h-4 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>
                              <span className="text-xs text-muted-foreground mt-1 block">{message.timestamp}</span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {selected.sentiment === "negative" && (
                    <div className="flex items-center gap-3 p-3 rounded-md bg-destructive/10 border border-destructive/20">
                      <AlertCircle className="w-5 h-5 text-destructive shrink-0" />
                      <div className="flex-1">
                        <div className="text-sm font-medium">Escalation Recommended</div>
                        <div className="text-xs text-muted-foreground">Customer sentiment is negative. Consider transferring to a human agent.</div>
                      </div>
                      <Button size="sm" variant="destructive" data-testid="button-escalate">
                        Escalate
                      </Button>
                    </div>
                  )}
                </div>
              </CardContent>
            </>
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Phone className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
                <p className="text-muted-foreground">Select a call to view details</p>
              </div>
            </div>
          )}
        </Card>
      </div>
    </DashboardLayout>
  );
}
