import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2, Phone, PhoneIncoming, PhonePhoneOutgoing, FileText, Clock, Search, Play } from "lucide-react";
import { format } from "date-fns";

interface SIPCall {
  id: string;
  extension_id?: string;
  extension_number?: string;
  caller_id: string;
  caller_name?: string;
  direction: "inbound" | "outbound";
  status: string;
  duration_seconds?: number;
  initiated_at: string;
  answered_at?: string;
  ended_at?: string;
  recording_url?: string;
  transcript?: string;
  ai_summary?: string;
}

export default function SIPCalls() {
  const [selectedCall, setSelectedCall] = useState<SIPCall | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [directionFilter, setDirectionFilter] = useState("all");

  const { data: calls, isLoading } = useQuery<SIPCall[]>({
    queryKey: ["/api/sip/calls", { search: searchQuery, status: statusFilter === "all" ? undefined : statusFilter, direction: directionFilter === "all" ? undefined : directionFilter }],
  });

  const getStatusColor = (status: string) => {
    switch (status) {
      case "completed": return "bg-green-500";
      case "answered": return "bg-blue-500";
      case "ringing": return "bg-yellow-500 animate-pulse";
      case "failed": return "bg-red-500";
      case "busy": return "bg-orange-500";
      default: return "bg-gray-400";
    }
  };

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

  const inboundCalls = calls?.filter(c => c.direction === "inbound") || [];
  const outboundCalls = calls?.filter(c => c.direction === "outbound") || [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">SIP Call History</h2>
          <p className="text-muted-foreground">View your SIP extension call history and transcripts</p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Calls</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{calls?.length || 0}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Inbound</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{inboundCalls.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Outbound</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{outboundCalls.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Minutes</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {Math.floor((calls?.reduce((sum, c) => sum + (c.duration_seconds || 0), 0) || 0) / 60)}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search by caller ID or name..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-[150px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="completed">Completed</SelectItem>
                <SelectItem value="answered">Answered</SelectItem>
                <SelectItem value="ringing">Ringing</SelectItem>
                <SelectItem value="failed">Failed</SelectItem>
                <SelectItem value="busy">Busy</SelectItem>
              </SelectContent>
            </Select>
            <Select value={directionFilter} onValueChange={setDirectionFilter}>
              <SelectTrigger className="w-full sm:w-[150px]">
                <SelectValue placeholder="Direction" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Directions</SelectItem>
                <SelectItem value="inbound">Inbound</SelectItem>
                <SelectItem value="outbound">Outbound</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Calls Table */}
      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Direction</TableHead>
                <TableHead>Caller</TableHead>
                <TableHead>Extension</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Duration</TableHead>
                <TableHead>Date</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    <Loader2 className="h-6 w-6 animate-spin mx-auto" />
                  </TableCell>
                </TableRow>
              ) : !calls?.length ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    No calls found. Make a call to see history here.
                  </TableCell>
                </TableRow>
              ) : (
                calls.map((call) => (
                  <TableRow key={call.id}>
                    <TableCell>
                      {call.direction === "inbound" ? (
                        <Badge variant="outline" className="text-blue-600 border-blue-600">
                          <PhoneIncoming className="mr-1 h-3 w-3" /> Inbound
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="text-green-600 border-green-600">
                          <PhoneOutgoing className="mr-1 h-3 w-3" /> Outbound
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <div>
                        <div className="font-medium">{call.caller_id}</div>
                        {call.caller_name && (
                          <div className="text-sm text-muted-foreground">{call.caller_name}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      {call.extension_number ? (
                        <div className="flex items-center gap-2">
                          <Phone className="h-4 w-4 text-muted-foreground" />
                          {call.extension_number}
                        </div>
                      ) : "-"}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <div className={`h-2 w-2 rounded-full ${getStatusColor(call.status)}`} />
                        <span className="capitalize">{call.status}</span>
                      </div>
                    </TableCell>
                    <TableCell>{formatDuration(call.duration_seconds)}</TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {format(new Date(call.initiated_at), "MMM d, HH:mm")}
                    </TableCell>
                    <TableCell className="text-right">
                      {(call.transcript || call.recording_url) && (
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => setSelectedCall(call)}
                        >
                          <FileText className="h-4 w-4" />
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Call Detail Dialog */}
      <Dialog open={!!selectedCall} onOpenChange={() => setSelectedCall(null)}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          {selectedCall && (
            <>
              <DialogHeader>
                <DialogTitle>Call Details</DialogTitle>
                <DialogDescription>
                  {format(new Date(selectedCall.initiated_at), "PPpp, MMM d, yyyy")}
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">Direction</p>
                    <p className="font-medium capitalize">{selectedCall.direction}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Status</p>
                    <p className="font-medium capitalize">{selectedCall.status}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Caller ID</p>
                    <p className="font-medium">{selectedCall.caller_id}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Duration</p>
                    <p className="font-medium">{formatDuration(selectedCall.duration_seconds)}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Extension</p>
                    <p className="font-medium">{selectedCall.extension_number || "-"}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Recording</p>
                    {selectedCall.recording_url ? (
                      <a href={selectedCall.recording_url} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline flex items-center gap-1">
                        <Play className="h-4 w-4" /> Play
                      </a>
                    ) : (
                      <p className="text-muted-foreground">No recording</p>
                    )}
                  </div>
                </div>

                {selectedCall.transcript && (
                  <div>
                    <h4 className="font-medium mb-2">Transcript</h4>
                    <div className="bg-muted/50 rounded-lg p-4 text-sm max-h-48 overflow-y-auto">
                      {selectedCall.transcript}
                    </div>
                  </div>
                )}

                {selectedCall.ai_summary && (
                  <div>
                    <h4 className="font-medium mb-2">AI Summary</h4>
                    <div className="bg-muted/50 rounded-lg p-4 text-sm">
                      {selectedCall.ai_summary}
                    </div>
                  </div>
                )}
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
