import { createFileRoute, useParams } from "@tanstack/react-router";
import { useQueryData } from "@/hooks/useQueryData";
import { API_ENDPOINTS, BASE_URL } from "@/config/api";
import {
  flexRender,
  getCoreRowModel,
  useReactTable,
  type ColumnDef,
} from "@tanstack/react-table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useQueryClient } from "@tanstack/react-query";
import { useDeviceEvents } from "@/hooks/useDeviceEvents";

export const Route = createFileRoute("/_authenticated/room/$roomName/")({
  head: ({ params }) => ({
    meta: [{ title: `Danh sách thiết bị phòng ${params.roomName}` }],
  }),
  component: RoomDetailComponent,
});

function RoomDetailComponent() {
  const { roomName } = useParams({ from: "/_authenticated/room/$roomName/" });
  const queryClient = useQueryClient();

  const { data: devices = [], isLoading } = useQueryData({
    queryKey: ["devices", roomName],
    url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.GET_DEVICE_FROM_ROOM(roomName),
  });

  // Lắng nghe SSE và update state
  useDeviceEvents({
    onDeviceOnlineInRoom: (deviceId, room) => {
      if (room === roomName) {
        queryClient.setQueryData(
          ["devices", roomName],
          (oldDevices: any[] = []) =>
            oldDevices.map((d) =>
              d.macAddress === deviceId ? { ...d, isOffline: false } : d
            )
        );
      }
    },
    onDeviceOfflineInRoom: (deviceId, room) => {
      if (room === roomName) {
        queryClient.setQueryData(
          ["devices", roomName],
          (oldDevices: any[] = []) =>
            oldDevices.map((d) =>
              d.macAddress === deviceId ? { ...d, isOffline: true } : d
            )
        );
      }
    },
  });

  const columns: ColumnDef<any>[] = [
    {
      header: "STT",
      cell: ({ row }) => row.index + 1,
    },
    {
      header: "MAC Address",
      accessorKey: "macAddress",
    },
    {
      header: "Thời gian thiết bị",
      accessorKey: "deviceTime",
      cell: ({ getValue }) => {
        const date = new Date(getValue() as string);
        return date.toLocaleString();
      },
    },
    {
      header: "Phiên bản",
      accessorKey: "version",
    },
    {
      header: "Địa chỉ IP",
      accessorKey: "ipAddress",
    },
    {
      header: "Trạng thái",
      accessorKey: "isOffline",
      cell: ({ getValue }) =>
        getValue() ? (
          <span className="text-red-500 font-semibold">Offline</span>
        ) : (
          <span className="text-green-500 font-semibold">Online</span>
        ),
    },
  ];

  const table = useReactTable({
    data: devices,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  if (isLoading) return <div>Đang tải thiết bị...</div>;

  return (
    <div className="w-full px-6 space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Phòng: {roomName}</h1>
          <p className="text-muted-foreground mt-2">
            Danh sách thiết bị trong phòng
          </p>
        </div>
      </div>
      <Card>
        <CardHeader>
          <CardTitle>Thiết bị</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableHead key={header.id}>
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                    </TableHead>
                  ))}
                </TableRow>
              ))}
            </TableHeader>
            <TableBody>
              {table.getRowModel().rows.map((row) => (
                <TableRow key={row.id}>
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
