import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Badge } from "@/components/ui/badge";
import { Monitor, Wifi, WifiOff, Loader2, Maximize2, X } from "lucide-react";
import { useState } from "react";
import { cn } from "@/lib/utils";
import { FolderStatusPopover } from "../folder-status-popover";
import { useGetClientFolderStatusForDevice } from "@/hooks/queries";
import type { ClientFolderStatus } from "@/types/folder";
import { Button } from "@/components/ui/button";
import { getRemoteDesktopUrl } from "@/services/remote-control.service";
import { BASE_URL } from "@/config/api";
import { toast } from "sonner";
export function ComputerCard({
  device,
  position,
  folderStatus,
  isCheckingFolder,
}: {
  device: any | undefined;
  position: number;
  folderStatus?: ClientFolderStatus;
  isCheckingFolder?: boolean;
}) {
  const [isConnecting, setIsConnecting] = useState(false);
  const [showRemote, setShowRemote] = useState(false);
  const [proxyUrl, setProxyUrl] = useState<string | null>(null);

  if (!device) {
    return (
      <div className="relative flex flex-col items-center justify-center w-24 h-24 rounded-lg border-2 border-dashed border-muted-foreground/30 bg-muted/20">
        <div className="absolute -top-2 -left-2 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold bg-muted text-muted-foreground">
          {position}
        </div>
        <Monitor className="h-8 w-8 mb-1 text-muted-foreground/40" />
        <span className="text-xs text-muted-foreground">Trống</span>
      </div>
    );
  }

  const isOffline = device.isOffline;
  const firstNetworkInfo = device.networkInfos?.[0];
  const agentVersion = device.version;

  const handleConnect = async () => {
    if (!device?.id) {
      toast.error("Không tìm thấy nodeID của thiết bị.");
      return;
    }

    try {
      setIsConnecting(true);
      const response = await getRemoteDesktopUrl(device.id);
      const originalUrl = new URL(response.url);
      const pathAndQuery = originalUrl.pathname + originalUrl.search;
      const cleanPath = pathAndQuery.startsWith("/")
        ? pathAndQuery.substring(1)
        : pathAndQuery;
      const baseWithoutApi = BASE_URL.replace("/api", "");
      const proxyUrlFull = `${baseWithoutApi}/api/meshcentral/proxy/${cleanPath}`;

      setProxyUrl(proxyUrlFull);
      setShowRemote(true);
    } catch (error: any) {
      toast.error(
        error?.response?.data?.message || "Không thể kết nối remote cho thiết bị này."
      );
    } finally {
      setIsConnecting(false);
    }
  };

  const handleCloseRemote = () => {
    setShowRemote(false);
    setProxyUrl(null);
  };

  const handleFullscreen = () => {
    const iframe = document.getElementById(`mesh-iframe-${device.id}`) as HTMLIFrameElement;
    if (iframe?.requestFullscreen) {
      iframe.requestFullscreen();
    }
  };

  function DeviceFolderCheck() {
    const deviceId = device.id;
    const room = device.room;
    const [checking, setChecking] = useState(false);

    const { data: status, isLoading } = useGetClientFolderStatusForDevice(
      deviceId,
      room,
      checking
    );

    const handleCheck = () => setChecking((s) => !s);

    return (
      <div>
        <button
          onClick={handleCheck}
          className="inline-flex items-center gap-2 px-3 py-1 rounded border bg-background text-sm"
        >
          {isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          Kiểm tra thư mục Setup
        </button>

        {checking && isLoading && (
          <div className="text-xs text-muted-foreground mt-2">Đang kiểm tra...</div>
        )}

        {checking && !isLoading && status && (
          <div className="text-xs mt-2">
            <div className="font-medium">Các file trong thư mục Setup({status.currentFiles?.length ?? 0})</div>
            <div className="mt-1 max-h-36 overflow-auto space-y-1">
              {(status.currentFiles ?? []).length === 0 ? (
                <div className="text-muted-foreground">Không có file hiện tại</div>
              ) : (
                (status.currentFiles ?? []).map((f: any) => (
                  <div key={f.fileName} className="font-mono text-xs">
                    <div className="truncate">{f.fileName}</div>
                    {f.lastModified && (
                      <div className="text-muted-foreground text-[10px]">
                        {new Date(f.lastModified).toLocaleString()}
                      </div>
                    )}
                  </div>
                ))
              )}
            </div>
          </div>
        )}

        {checking && !isLoading && !status && (
          <div className="text-xs text-muted-foreground mt-2">Không có dữ liệu</div>
        )}
      </div>
    );
  }

  const DeviceInfo = () => (
    <div className="space-y-3 min-w-[280px]">
      <div>
        <div className="text-xs text-muted-foreground mb-1">Thời gian thiết bị</div>
        <div className="text-sm">
          <div className="font-medium">{new Date(device.deviceTime).toLocaleDateString("vi-VN")}</div>
          <div className="text-muted-foreground text-xs">
            {new Date(device.deviceTime).toLocaleTimeString("vi-VN")}
          </div>
        </div>
      </div>

      <div>
        <div className="text-xs text-muted-foreground mb-1">Phiên bản</div>
        <Badge variant="secondary" className="font-mono text-xs">
          v{device.version}
        </Badge>
      </div>

      <div>
        <div className="text-xs text-muted-foreground mb-1">Phòng</div>
        <div className="text-sm font-medium">{device.room}</div>
      </div>

      {device.networkInfos?.length > 0 && (
        <div>
          <div className="text-xs text-muted-foreground mb-1">Thông tin mạng</div>
          <div className="space-y-1">
            {device.networkInfos.map((info: any, idx: number) => (
              <div key={idx} className="text-xs font-mono bg-muted/50 p-2 rounded">
                <div>MAC: {info.macAddress ?? "-"}</div>
                <div>IP: {info.ipAddress ?? "-"}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div>
        <div className="text-xs text-muted-foreground mb-1">Kết nối</div>
        <Button
          type="button"
          size="sm"
          onClick={handleConnect}
          disabled={isOffline || isConnecting}
          className="w-full"
        >
          {isConnecting ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              Đang kết nối...
            </>
          ) : (
            "Connect"
          )}
        </Button>
      </div>

      <div>
        <div className="text-xs text-muted-foreground mb-1">Kiểm tra thư mục</div>
        <DeviceFolderCheck />
      </div>

      <div>
        <div className="text-xs text-muted-foreground mb-1">Trạng thái</div>
        <Badge
          variant={isOffline ? "destructive" : "default"}
          className={`flex items-center gap-1 w-fit ${
            isOffline ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"
          }`}
        >
          {isOffline ? <WifiOff className="h-3 w-3" /> : <Wifi className="h-3 w-3" />}
          {isOffline ? "Offline" : "Online"}
        </Badge>
      </div>
    </div>
  );

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div
            className={cn(
              "relative flex flex-col items-center justify-center w-24 h-24 rounded-lg border-2 transition-all hover:scale-105 cursor-pointer",
              isOffline
                ? "bg-red-50 border-red-300 hover:border-red-400 hover:shadow-lg"
                : "bg-green-50 border-green-300 hover:border-green-400 hover:shadow-lg"
            )}
          >
            <div
              className={cn(
                "absolute -top-2 -left-2 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold",
                isOffline ? "bg-red-500 text-white" : "bg-green-500 text-white"
              )}
            >
              {position}
            </div>

            {/* Folder Status Icon */}
            {device && !isOffline && (
              <div className="absolute -top-2 -right-2">
                <FolderStatusPopover
                  deviceId={device.networkInfos?.[0]?.macAddress || device.id}
                  status={folderStatus}
                  isLoading={isCheckingFolder}
                />
              </div>
            )}

            <Monitor className={cn("h-6 w-6 mb-1", isOffline ? "text-red-600" : "text-green-600")} />
            {firstNetworkInfo?.ipAddress && (
              <div className="text-[10px] font-mono text-center mb-1 px-1 truncate w-full">
                {firstNetworkInfo.ipAddress}
                {agentVersion && (
                  <div className="text-[10px] font-mono text-center mb-1 px-1 truncate w-full">
                    v{agentVersion}
                  </div>
                )}
              </div>
            )}
            <div className="flex items-center gap-1">
              <span
                className={cn(
                  "text-xs font-medium",
                  isOffline ? "text-red-700" : "text-green-700"
                )}
              >
                {isOffline ? "Off" : "On"}
              </span>
            </div>
          </div>
        </PopoverTrigger>
        <PopoverContent className="w-auto" side="top" align="center">
          <DeviceInfo />
        </PopoverContent>
      </Popover>

      {showRemote && proxyUrl && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 p-4">
          <div className="relative h-[90vh] w-[90vw] overflow-hidden rounded-lg border bg-background shadow-2xl">
            <div className="flex items-center justify-between border-b bg-muted/50 px-3 py-2">
              <p className="text-sm font-medium">Remote Session - {device.id}</p>
              <div className="flex gap-1">
                <Button
                  variant="ghost"
                  size="icon"
                  type="button"
                  onClick={handleFullscreen}
                  title="Fullscreen"
                >
                  <Maximize2 className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  type="button"
                  onClick={handleCloseRemote}
                  aria-label="Đóng"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
            <iframe
              id={`mesh-iframe-${device.id}`}
              title="Remote Desktop"
              src={proxyUrl}
              className="h-[calc(90vh-44px)] w-full border-0"
              allowFullScreen
              allow="clipboard-read; clipboard-write; camera; microphone"
            />
          </div>
        </div>
      )}
    </>
  );
}
