"use client";

import * as React from "react";
import {
  KeyRound,
  CheckCircle2,
  XCircle,
  Clock,
  ShieldCheck,
  AlertTriangle,
  RefreshCw,
} from "lucide-react";

interface ResetRequestItem {
  id: string;
  userId: string;
  name: string;
  email: string;
  status: "PENDING" | "APPROVED" | "REJECTED" | "EXPIRED";
  requestedAt: string;
  handledAt: string | null;
  handledBy: string | null;
  handlingReason: string | null;
  expiresAt: string;
}

export function ResetRequestsPanel() {
  const [requests, setRequests] = React.useState<ResetRequestItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [actionLoading, setActionLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const fetchRequests = React.useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch("/api/admin/security/reset-requests");
      if (res.status === 403) {
        setError("Access Denied: Main Administrator authority required.");
        return;
      }
      if (!res.ok) throw new Error("Failed to load reset requests");
      const data = await res.json();
      setRequests(data.requests || []);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchRequests();
  }, [fetchRequests]);

  const handleAction = async (requestId: string, action: "APPROVE" | "REJECT") => {
    const isApprove = action === "APPROVE";
    const promptMessage = isApprove
      ? "Approve password reset? This will terminate all active sessions for this sub-admin and send a new temporary access key to their email."
      : "Reject password reset request?";

    if (!confirm(promptMessage)) return;

    setActionLoading(true);
    try {
      const res = await fetch("/api/admin/security/reset-requests", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          requestId,
          action,
          reason: isApprove ? "Approved by Main Admin" : "Rejected by Main Admin",
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to process reset request");

      alert(data.message);
      fetchRequests();
    } catch (e) {
      alert((e as Error).message);
    } finally {
      setActionLoading(false);
    }
  };

  const pendingCount = requests.filter((r) => r.status === "PENDING").length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
              Password Reset Requests
            </h1>
            {pendingCount > 0 && (
              <span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-[10px] font-bold text-amber-800 dark:bg-amber-950 dark:text-amber-300">
                {pendingCount} Pending Review
              </span>
            )}
          </div>
          <p className="mt-0.5 text-xs text-neutral-500">
            Sub-administrator forgot-password queue. Review requests, authorize credential resets, and terminate compromised sessions.
          </p>
        </div>

        <button
          type="button"
          onClick={fetchRequests}
          disabled={loading}
          className="flex h-8 items-center gap-1.5 rounded-lg border border-neutral-200 px-3 text-xs font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          <span>Refresh Queue</span>
        </button>
      </div>

      {error && (
        <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-300">
          <div className="flex items-center gap-2 font-semibold">
            <AlertTriangle className="h-4 w-4" />
            <span>Authorization Error</span>
          </div>
          <p className="mt-1">{error}</p>
        </div>
      )}

      {/* Requests Table */}
      <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead>
              <tr className="border-b border-neutral-200 bg-neutral-50/75 text-[11px] font-semibold text-neutral-500 uppercase dark:border-neutral-800 dark:bg-neutral-950/50">
                <th className="px-5 py-3">Sub-administrator</th>
                <th className="px-5 py-3">Requested At</th>
                <th className="px-5 py-3">Status</th>
                <th className="px-5 py-3">Resolution Details</th>
                <th className="px-5 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
              {loading ? (
                <tr>
                  <td colSpan={5} className="px-5 py-8 text-center text-neutral-400">
                    Loading requests queue...
                  </td>
                </tr>
              ) : requests.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-5 py-8 text-center text-neutral-400">
                    No password reset requests found. The review queue is clear.
                  </td>
                </tr>
              ) : (
                requests.map((r) => {
                  const isPending = r.status === "PENDING";
                  return (
                    <tr
                      key={r.id}
                      className="transition hover:bg-neutral-50/50 dark:hover:bg-neutral-800/30"
                    >
                      <td className="px-5 py-3.5">
                        <div className="font-semibold text-neutral-900 dark:text-white">
                          {r.name}
                        </div>
                        <div className="text-[11px] text-neutral-500">{r.email}</div>
                      </td>

                      <td suppressHydrationWarning className="px-5 py-3.5 text-neutral-500">
                        {new Date(r.requestedAt).toLocaleString("en-US", {
                          dateStyle: "medium",
                          timeStyle: "short",
                        })}
                      </td>

                      <td className="px-5 py-3.5">
                        <span
                          className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-bold tracking-wider uppercase ${
                            r.status === "PENDING"
                              ? "bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300"
                              : r.status === "APPROVED"
                              ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"
                              : "bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300"
                          }`}
                        >
                          {r.status === "PENDING" && <Clock className="h-3 w-3" />}
                          {r.status === "APPROVED" && <CheckCircle2 className="h-3 w-3" />}
                          {r.status === "REJECTED" && <XCircle className="h-3 w-3" />}
                          <span>{r.status}</span>
                        </span>
                      </td>

                      <td className="px-5 py-3.5 text-[11px] text-neutral-500">
                        {r.handledAt ? (
                          <div>
                            <div>Handled by {r.handledBy}</div>
                            <div suppressHydrationWarning className="text-[10px] text-neutral-400">
                              {new Date(r.handledAt).toLocaleString("en-US", {
                                dateStyle: "short",
                                timeStyle: "short",
                              })}
                            </div>
                          </div>
                        ) : (
                          <span className="text-amber-600 dark:text-amber-400">Awaiting Main Admin review</span>
                        )}
                      </td>

                      <td className="px-5 py-3.5 text-right">
                        {isPending ? (
                          <div className="flex items-center justify-end gap-2">
                            <button
                              type="button"
                              onClick={() => handleAction(r.id, "REJECT")}
                              disabled={actionLoading}
                              className="rounded-lg border border-neutral-200 px-2.5 py-1 text-xs font-medium text-neutral-600 hover:bg-neutral-100 disabled:opacity-50 dark:border-neutral-800 dark:text-neutral-400 dark:hover:bg-neutral-800"
                            >
                              Reject
                            </button>
                            <button
                              type="button"
                              onClick={() => handleAction(r.id, "APPROVE")}
                              disabled={actionLoading}
                              className="rounded-lg bg-neutral-900 px-3 py-1 text-xs font-semibold text-white hover:bg-neutral-800 disabled:opacity-50 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-100"
                            >
                              Approve & Reset
                            </button>
                          </div>
                        ) : (
                          <span className="text-[11px] text-neutral-400">Archived</span>
                        )}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default ResetRequestsPanel;
