"use client";

import * as React from "react";
import { format } from "date-fns";
import { useSession } from "next-auth/react";
import { useGetPasswordResetRequestsQuery } from "@/api/rtk/admin-password-reset-requests-api";
import { useGetProfileQuery, useUpdateUserMutation } from "@/api/rtk";
import { useAuthToken } from "@/hooks/use-auth-token";
import {
  hasPermission,
  type PermissionSource,
} from "@/lib/permissions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Loading } from "@/components/ui/loading";
import {
  ChevronLeft,
  ChevronRight,
  Eye,
  EyeOff,
  KeyRound,
  MapPin,
  ShieldAlert,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";

export default function PasswordResetRequestsPage() {
  const { token } = useAuthToken();
  const { data: session } = useSession();
  const { data: profile } = useGetProfileQuery(undefined, { skip: !token });
  const permissionSource: PermissionSource =
    (session as { backendUser?: PermissionSource } | null)?.backendUser ??
    profile ??
    null;
  const canRead = hasPermission(
    permissionSource,
    "READ",
    "PASSWORD_RESET_REQUEST",
  );
  const canSetUserPassword = hasPermission(permissionSource, "UPDATE", "USER");

  const [updateUser, { isLoading: updatingPassword }] = useUpdateUserMutation();

  const [page, setPage] = React.useState(1);
  const [emailFilter, setEmailFilter] = React.useState("");
  const [appliedEmail, setAppliedEmail] = React.useState("");

  const queryParams = React.useMemo(
    () => ({
      page,
      limit: 25,
      ...(appliedEmail.trim() ? { email: appliedEmail.trim() } : {}),
    }),
    [page, appliedEmail],
  );

  const { data, isLoading, isError, refetch } =
    useGetPasswordResetRequestsQuery(queryParams, { skip: !canRead || !token });

  const applyFilters = () => {
    setAppliedEmail(emailFilter);
    setPage(1);
  };

  const clearFilters = () => {
    setEmailFilter("");
    setAppliedEmail("");
    setPage(1);
  };

  const [setPasswordModal, setSetPasswordModal] = React.useState<{
    userId: string;
    displayName: string;
  } | null>(null);
  const [newPassword, setNewPassword] = React.useState("");
  const [showPassword, setShowPassword] = React.useState(false);

  const handleSubmitSetPassword = async () => {
    if (!setPasswordModal || !newPassword.trim() || newPassword.length < 6) {
      toast.error("Password must be at least 6 characters");
      return;
    }
    try {
      await updateUser({
        id: setPasswordModal.userId,
        body: { password: newPassword },
      }).unwrap();
      toast.success("Password updated");
      setNewPassword("");
      setShowPassword(false);
      setSetPasswordModal(null);
      void refetch();
    } catch (e: unknown) {
      const message =
        e && typeof e === "object" && "data" in e
          ? String((e as { data?: { message?: string } }).data?.message ?? "")
          : "";
      toast.error(message || "Failed to update password");
    }
  };

  if (!token || !canRead) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh] gap-4 p-8 text-center">
        <ShieldAlert className="size-12 text-muted-foreground" />
        <h1 className="text-lg font-semibold font-['Lexend']">
          Access restricted
        </h1>
        <p className="text-sm text-muted-foreground max-w-md">
          You need READ permission on Password reset requests to view this page.
        </p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <Loading
        layout="page"
        message="Loading password reset requests…"
        className="min-h-[40vh]"
      />
    );
  }

  if (isError || !data) {
    return (
      <div className="p-8 text-center text-destructive text-sm">
        Failed to load requests.
        <div className="mt-4">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => void refetch()}
          >
            Retry
          </Button>
        </div>
      </div>
    );
  }

  const rows = data.data;
  const { totalPages } = data;

  return (
    <div className="flex flex-col gap-6 p-4 md:p-6 animate-in fade-in duration-300">
      <div className="flex items-start gap-3">
        <div className="size-11 rounded-2xl bg-accent/10 flex items-center justify-center shrink-0">
          <KeyRound className="size-5 text-accent" />
        </div>
        <div>
          <h1 className="text-xl font-bold font-['Lexend'] tracking-tight">
            Password reset requests
          </h1>

        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card shadow-sm p-4 md:p-5 space-y-4">
        <div className="max-w-md space-y-2">
          <Label
            htmlFor="prr-email"
            className="text-xs font-medium text-muted-foreground"
          >
            User email contains
          </Label>
          <Input
            id="prr-email"
            className="h-9"
            value={emailFilter}
            onChange={(e) => setEmailFilter(e.target.value)}
            placeholder="Filter by email"
          />
        </div>
        <div className="flex flex-wrap gap-2">
          <Button type="button" size="sm" onClick={applyFilters}>
            Apply filters
          </Button>
          <Button
            type="button"
            size="sm"
            variant="outline"
            onClick={clearFilters}
          >
            Clear
          </Button>
        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card shadow-sm overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="font-['Lexend'] whitespace-nowrap">
                Requested
              </TableHead>
              <TableHead className="font-['Lexend']">User</TableHead>
              <TableHead className="font-['Lexend']">Email</TableHead>
              <TableHead className="font-['Lexend'] whitespace-nowrap">
                Request IP
              </TableHead>
              <TableHead className="font-['Lexend'] whitespace-nowrap">
                Browser IP
              </TableHead>
              <TableHead className="font-['Lexend'] min-w-[180px]">
                Location
              </TableHead>
              <TableHead className="font-['Lexend'] whitespace-nowrap">
                Status
              </TableHead>
              {canSetUserPassword ? (
                <TableHead className="font-['Lexend'] text-right whitespace-nowrap">
                  Actions
                </TableHead>
              ) : null}
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={canSetUserPassword ? 8 : 7}
                  className="text-center py-12 text-muted-foreground"
                >
                  No password reset requests yet.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((row) => (
                <TableRow key={row.id}>
                  <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
                    {format(new Date(row.createdAt), "MMM d, yyyy · h:mm a")}
                  </TableCell>
                  <TableCell className="font-medium text-sm">
                    {row.user?.name ?? "—"}
                  </TableCell>
                  <TableCell className="text-sm">
                    {row.user?.email ?? "—"}
                  </TableCell>
                  <TableCell>
                    <code className="text-xs bg-muted/60 px-2 py-0.5 rounded-md">
                      {row.ipAddress ?? "—"}
                    </code>
                  </TableCell>
                  <TableCell>
                    {row.browserReportedIp ? (
                      <code
                        className="text-xs bg-accent/10 text-accent px-2 py-0.5 rounded-md"
                        title="WAN from browser probe (ipify)"
                      >
                        {row.browserReportedIp}
                      </code>
                    ) : (
                      <span className="text-sm text-muted-foreground/60">
                        —
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="max-w-[320px]">
                    {row.location ? (
                      <span className="flex items-start gap-1.5 text-sm text-muted-foreground">
                        <MapPin className="size-3.5 shrink-0 mt-0.5" />
                        <span
                          className="line-clamp-2 leading-snug"
                          title={row.location}
                        >
                          {row.location}
                        </span>
                      </span>
                    ) : (
                      <span className="text-sm text-muted-foreground/60">
                        —
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="whitespace-nowrap">
                    {row.completedAt ? (
                      <Badge
                        variant="secondary"
                        className="font-normal text-xs font-['Lexend']"
                        title={`Completed ${format(new Date(row.completedAt), "MMM d, yyyy · h:mm a")}`}
                      >
                        Completed
                      </Badge>
                    ) : (
                      <Badge
                        variant="outline"
                        className="font-normal text-xs font-['Lexend'] border-amber-200/80 bg-amber-50 text-amber-950"
                      >
                        Pending
                      </Badge>
                    )}
                  </TableCell>
                  {canSetUserPassword ? (
                    <TableCell className="text-right">
                      <Button
                        type="button"
                        variant="outlineToolbarClear"
                        disabled={!row.userId || !!row.completedAt}
                        onClick={() => {
                          setSetPasswordModal({
                            userId: row.userId,
                            displayName:
                              row.user?.name || row.user?.email || "this user",
                          });
                          setNewPassword("");
                          setShowPassword(false);
                        }}
                      >
                        Set password
                      </Button>
                    </TableCell>
                  ) : null}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog
        open={setPasswordModal != null}
        onOpenChange={(open) => {
          if (!open) {
            setSetPasswordModal(null);
            setNewPassword("");
            setShowPassword(false);
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Set new password</DialogTitle>
          </DialogHeader>
          {setPasswordModal ? (
            <>
              <p className="text-sm text-muted-foreground">
                Set a new password for{" "}
                <span className="font-medium text-foreground">
                  {setPasswordModal.displayName}
                </span>
                .
              </p>
              <div className="grid gap-2 py-2">
                <Label htmlFor="prr-new-password">New password</Label>
                <div className="relative">
                  <Input
                    id="prr-new-password"
                    type={showPassword ? "text" : "password"}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    placeholder="Min 6 characters"
                    className="pr-10"
                    autoComplete="new-password"
                  />
                  <Button
                    type="button"
                    variant="inputTrailingIcon"
                    onClick={() => setShowPassword((p) => !p)}
                    aria-label={
                      showPassword ? "Hide password" : "Show password"
                    }
                  >
                    {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                  </Button>
                </div>
              </div>
            </>
          ) : null}
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setSetPasswordModal(null);
                setNewPassword("");
                setShowPassword(false);
              }}
            >
              Cancel
            </Button>
            <Button
              type="button"
              onClick={() => void handleSubmitSetPassword()}
              disabled={
                !newPassword.trim() ||
                newPassword.length < 6 ||
                updatingPassword
              }
            >
              {updatingPassword ? "Updating…" : "Update password"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-4">
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={page <= 1}
            onClick={() => setPage((p) => Math.max(1, p - 1))}
          >
            <ChevronLeft className="size-4" />
          </Button>
          <span className="text-sm text-muted-foreground tabular-nums">
            Page {page} of {totalPages}
          </span>
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={page >= totalPages}
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
          >
            <ChevronRight className="size-4" />
          </Button>
        </div>
      )}
    </div>
  );
}
