import { useState } from "react";
import { useQuery, useMutation, useQueryClient } 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 { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2, Plus, RefreshCw, Trash2, Edit, Check, X, Server, Globe, Plug } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";

interface FreePBXConnection {
  id: string;
  name: string;
  host: string;
  ami_port?: number;
  ami_username?: string;
  rest_api_url?: string;
  auto_sync: boolean;
  sync_interval_minutes?: number;
  is_active: boolean;
  connection_status: string;
  extension_count?: number;
  last_sync_at?: string;
  created_at: string;
}

export default function SIPConnections() {
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [testDialogOpen, setTestDialogOpen] = useState(false);
  const [selectedConnection, setSelectedConnection] = useState<FreePBXConnection | null>(null);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: connections, isLoading } = useQuery<FreePBXConnection[]>({
    queryKey: ["/api/admin/sip/connections"],
  });

  // Create connection mutation
  const createMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest("POST", "/api/admin/sip/connections", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/admin/sip/connections"] });
      setAddDialogOpen(false);
      toast({ title: "Connection created", description: "FreePBX connection added successfully" });
    },
    onError: (error: any) => {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    },
  });

  // Update connection mutation
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: any }) => {
      return apiRequest("PUT", `/api/admin/sip/connections/${id}`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/admin/sip/connections"] });
      setEditDialogOpen(false);
      toast({ title: "Connection updated", description: "FreePBX connection updated successfully" });
    },
    onError: (error: any) => {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    },
  });

  // Delete connection mutation
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      return apiRequest("DELETE", `/api/admin/sip/connections/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/admin/sip/connections"] });
      toast({ title: "Connection deleted", description: "FreePBX connection removed" });
    },
    onError: (error: any) => {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    },
  });

  // Sync extensions mutation
  const syncMutation = useMutation({
    mutationFn: async (id: string) => {
      return apiRequest("POST", `/api/admin/sip/connections/${id}/sync`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/admin/sip/connections"] });
      toast({ title: "Sync complete", description: "Extensions synced from FreePBX" });
    },
    onError: (error: any) => {
      toast({ title: "Sync failed", description: error.message, variant: "destructive" });
    },
  });

  const getStatusColor = (status: string) => {
    switch (status) {
      case "connected": return "bg-green-500";
      case "disconnected": return "bg-gray-400";
      case "error": return "bg-red-500";
      case "syncing": return "bg-yellow-500 animate-pulse";
      default: return "bg-gray-400";
    }
  };

  const ConnectionForm = ({ mode, connection, onSubmit }: { mode: "add" | "edit"; connection?: FreePBXConnection; onSubmit: (data: any) => void }) => {
    const [formData, setFormData] = useState({
      name: connection?.name || "",
      host: connection?.host || "",
      ami_port: connection?.ami_port || 5038,
      ami_username: connection?.ami_username || "",
      ami_secret: "",
      rest_api_url: connection?.rest_api_url || "",
      rest_api_token: "",
      auto_sync: connection?.auto_sync ?? true,
      sync_interval_minutes: connection?.sync_interval_minutes || 60,
      is_active: connection?.is_active ?? true,
    });

    const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault();
      onSubmit(formData);
    };

    return (
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div className="col-span-2">
            <Label>Connection Name *</Label>
            <Input value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} placeholder="Main PBX" required />
          </div>
          <div className="col-span-2">
            <Label>Host / IP Address *</Label>
            <Input value={formData.host} onChange={e => setFormData({ ...formData, host: e.target.value })} placeholder="pbx.example.com" required />
          </div>
          <div>
            <Label>AMI Port</Label>
            <Input type="number" value={formData.ami_port} onChange={e => setFormData({ ...formData, ami_port: parseInt(e.target.value) })} />
          </div>
          <div>
            <Label>AMI Username</Label>
            <Input value={formData.ami_username} onChange={e => setFormData({ ...formData, ami_username: e.target.value })} />
          </div>
          <div className="col-span-2">
            <Label>AMI Secret {mode === "edit" && "(leave empty to keep current)"}</Label>
            <Input type="password" value={formData.ami_secret} onChange={e => setFormData({ ...formData, ami_secret: e.target.value })} placeholder={mode === "edit" ? "••••••••" : ""} />
          </div>
          <div className="col-span-2">
            <Label>REST API URL</Label>
            <Input value={formData.rest_api_url} onChange={e => setFormData({ ...formData, rest_api_url: e.target.value })} placeholder="https://pbx.example.com/api" />
          </div>
          <div className="col-span-2">
            <Label>REST API Token {mode === "edit" && "(leave empty to keep current)"}</Label>
            <Input type="password" value={formData.rest_api_token} onChange={e => setFormData({ ...formData, rest_api_token: e.target.value })} placeholder={mode === "edit" ? "••••••••" : ""} />
          </div>
        </div>

        <div className="flex items-center justify-between p-4 border rounded-lg">
          <div>
            <p className="font-medium">Auto Sync Extensions</p>
            <p className="text-sm text-muted-foreground">Automatically sync extensions from FreePBX</p>
          </div>
          <Switch checked={formData.auto_sync} onCheckedChange={checked => setFormData({ ...formData, auto_sync: checked })} />
        </div>

        {formData.auto_sync && (
          <div>
            <Label>Sync Interval (minutes)</Label>
            <Input type="number" value={formData.sync_interval_minutes} onChange={e => setFormData({ ...formData, sync_interval_minutes: parseInt(e.target.value) })} min="1" />
          </div>
        )}

        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => mode === "add" ? setAddDialogOpen(false) : setEditDialogOpen(false)}>Cancel</Button>
          <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
            {(createMutation.isPending || updateMutation.isPending) && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {mode === "add" ? "Create Connection" : "Update Connection"}
          </Button>
        </DialogFooter>
      </form>
    );
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">FreePBX Connections</h2>
          <p className="text-muted-foreground">Manage SIP servers and sync extensions</p>
        </div>
        <Button onClick={() => setAddDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" /> Add Connection
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Connections</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{connections?.length || 0}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Connected</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{connections?.filter(c => c.connection_status === "connected").length || 0}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Extensions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{connections?.reduce((sum, c) => sum + (c.extension_count || 0), 0) || 0}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Auto-Sync Enabled</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{connections?.filter(c => c.auto_sync).length || 0}</div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Host</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Extensions</TableHead>
                <TableHead>Auto Sync</TableHead>
                <TableHead>Last Sync</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>
              ) : !connections?.length ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    No connections found. Add a FreePBX server to get started.
                  </TableCell>
                </TableRow>
              ) : (
                connections.map((conn) => (
                  <TableRow key={conn.id}>
                    <TableCell className="font-medium">{conn.name}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Server className="h-4 w-4 text-muted-foreground" />
                        {conn.host}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <div className={`h-2 w-2 rounded-full ${getStatusColor(conn.connection_status)}`} />
                        <span className="capitalize">{conn.connection_status}</span>
                      </div>
                    </TableCell>
                    <TableCell>{conn.extension_count || 0}</TableCell>
                    <TableCell>
                      {conn.auto_sync ? <Check className="h-4 w-4 text-green-500" /> : <X className="h-4 w-4 text-muted-foreground" />}
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {conn.last_sync_at ? new Date(conn.last_sync_at).toLocaleDateString() : "Never"}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => syncMutation.mutate(conn.id)}
                          disabled={syncMutation.isPending}
                        >
                          <RefreshCw className={`h-4 w-4 ${syncMutation.isPending ? "animate-spin" : ""}`} />
                        </Button>
                        <Button size="sm" variant="ghost" onClick={() => { setSelectedConnection(conn); setEditDialogOpen(true); }}>
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => { if (confirm("Delete this connection?")) deleteMutation.mutate(conn.id); }}
                          disabled={deleteMutation.isPending}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Add Dialog */}
      <Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Add FreePBX Connection</DialogTitle>
            <DialogDescription>Connect to a FreePBX server to sync SIP extensions</DialogDescription>
          </DialogHeader>
          <ConnectionForm mode="add" onSubmit={(data) => createMutation.mutate(data)} />
        </DialogContent>
      </Dialog>

      {/* Edit Dialog */}
      <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Edit Connection</DialogTitle>
            <DialogDescription>Update FreePBX connection settings</DialogDescription>
          </DialogHeader>
          {selectedConnection && (
            <ConnectionForm mode="edit" connection={selectedConnection} onSubmit={(data) => updateMutation.mutate({ id: selectedConnection.id, data })} />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
