"use client";

import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Smartphone } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Pagination } from "@/components/shared/pagination";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { EmptyState, ErrorState, TableSkeleton } from "@/components/shared/states";
import { getPushDevices, revokePushDevice } from "@/services/push";
import { queryKeys } from "@/lib/query-keys";
import { useUrlState } from "@/lib/use-url-state";
import { useI18n, useT } from "@/i18n";
import { formatRelative } from "@/lib/format";
import { friendlyErrorMessage } from "@/lib/errors";
import { useCan } from "@/features/auth/use-can";
import type { PushDevice } from "@/types/push";

export function DevicesTab() {
  const t = useT();
  const { locale } = useI18n();
  const { can } = useCan();
  const queryClient = useQueryClient();
  const canManage = can("push.manage");

  const [page, setPage] = useUrlState("dev_page", 1, (value) => {
    const n = Number(value);
    return Number.isFinite(n) && n >= 1 ? n : null;
  });
  const [removing, setRemoving] = useState<PushDevice | null>(null);

  const filters = useMemo(() => ({ page, rows: 10 }), [page]);
  const query = useQuery({
    queryKey: queryKeys.push.devices(filters),
    queryFn: () => getPushDevices(filters),
  });

  const revokeMutation = useMutation({
    mutationFn: revokePushDevice,
    onSuccess: (response) => {
      toast.success(response.Message || t("push.deviceRemoved"));
      setRemoving(null);
      void queryClient.invalidateQueries({ queryKey: ["push", "devices"] });
    },
    onError: (error) => {
      toast.error(friendlyErrorMessage(error, t));
    },
  });

  const devices = query.data?.Model ?? [];

  return (
    <>
      <Card>
        {query.isPending ? (
          <TableSkeleton rows={8} cols={5} />
        ) : query.isError ? (
          <ErrorState message={friendlyErrorMessage(query.error, t)} onRetry={() => query.refetch()} />
        ) : devices.length === 0 ? (
          <EmptyState title={t("push.emptyDevices")} description={t("push.emptyDevicesHint")} icon={Smartphone} />
        ) : (
          <>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("push.owner")}</TableHead>
                    <TableHead>{t("push.device")}</TableHead>
                    <TableHead>{t("push.lastSeen")}</TableHead>
                    <TableHead>{t("common.createdAt")}</TableHead>
                    <TableHead aria-label={t("common.actions")} />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {devices.map((device) => (
                    <TableRow key={device.uuid}>
                      <TableCell>
                        <p className="max-w-44 truncate font-medium text-foreground">
                          {device.owner?.name ?? "—"}
                        </p>
                      </TableCell>
                      <TableCell>
                        <p className="numeric font-mono text-xs text-muted-foreground" dir="ltr">
                          {device.token}
                        </p>
                        <p className="numeric min-w-28 max-w-56 truncate text-xs text-muted-foreground" dir="ltr">
                          {device.device_id ?? "—"}
                        </p>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatRelative(device.last_seen_at, locale)}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatRelative(device.registered_at, locale)}
                      </TableCell>
                      <TableCell>
                        {canManage ? (
                          <Button variant="outline" size="sm" onClick={() => setRemoving(device)}>
                            {t("push.removeDevice")}
                          </Button>
                        ) : null}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
            <Pagination page={query.data!.Page} totalPages={query.data!.Total} records={query.data!.Records} onPageChange={setPage} />
          </>
        )}
      </Card>

      <ConfirmDialog
        open={removing !== null}
        onOpenChange={(next) => !next && setRemoving(null)}
        title={t("push.removeDeviceTitle")}
        description={t("push.removeDeviceBody")}
        confirmLabel={t("common.delete")}
        destructive
        loading={revokeMutation.isPending}
        onConfirm={() => {
          if (removing) revokeMutation.mutate(removing.uuid);
        }}
      />
    </>
  );
}