"use client";

import { useCallback, useEffect, useState } from "react";

import { NoPermissionState } from "@/components/auth/no-permission-state";
import { useSuperAdminSession } from "@/components/auth/session-context";
import { PageHeader } from "@/components/dashboard/page-header";
import { PaginationControls } from "@/components/dashboard/pagination-controls";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { getItems, getPagination } from "@/lib/api/core";
import {
  getSuperAdminCases,
  getSuperAdminOps,
  restoreSuperAdminComment,
  restoreSuperAdminPost,
  updateSuperAdminCase,
} from "@/lib/api/superadmin";
import { formatDateTime } from "@/lib/format";
import { useToast } from "@/components/ui/toast";
import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions";
import type {
  SuperAdminCase,
  SuperAdminCasesResponse,
  SuperAdminOpsResponse,
} from "@/types/api";

const EMPTY_CASES: SuperAdminCasesResponse = { items: [], data: [] };
const EMPTY_OPS: SuperAdminOpsResponse = {
  services: {
    mongodb: { status: "unknown" },
    redis: { enabled: false, status: "unknown" },
    queue: { enabled: false },
    storage: {},
    email: { enabled: false },
    websocket: { redisAdapterEnabled: false },
  },
  queues: {
    outbox: { pending: 0, failed: 0 },
  },
  workload: {
    openCasesCount: 0,
    activeSuperAdminSessionsCount: 0,
  },
};

export default function OrdersPage() {
  const { permissions, session } = useSuperAdminSession();
  const [casesResponse, setCasesResponse] = useState<SuperAdminCasesResponse | null>(null);
  const [ops, setOps] = useState<SuperAdminOpsResponse | null>(null);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  const canManageCases = hasPermission(permissions, SUPERADMIN_PERMISSIONS.CASES_MANAGE);
  const canReadOps = hasPermission(permissions, SUPERADMIN_PERMISSIONS.OPS_READ);
  const canModerateContent = hasPermission(
    permissions,
    SUPERADMIN_PERMISSIONS.CONTENT_MODERATE,
  );

  const loadQueue = useCallback(async () => {
    if (!canManageCases && !canReadOps) {
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const [casesPayload, opsPayload] = await Promise.all([
        canManageCases
          ? getSuperAdminCases({ page, limit: 12, sortOrder: "desc" })
          : Promise.resolve(EMPTY_CASES),
        canReadOps ? getSuperAdminOps() : Promise.resolve(EMPTY_OPS),
      ]);
      setCasesResponse(casesPayload);
      setOps(opsPayload);
    } catch (error) {
      toast({ title: "Failed to load operations queue", description: String(error), variant: "danger" });
    } finally {
      setLoading(false);
    }
  }, [canManageCases, canReadOps, page, toast]);

  useEffect(() => {
    void loadQueue();
  }, [loadQueue]);

  const items = getItems(casesResponse) as SuperAdminCase[];

  if (!canManageCases && !canReadOps) {
    return (
      <div className="space-y-5 pb-8">
        <PageHeader
          title="Operations queue"
          subtitle="Moderation and operational cases, assignment workflow, and restore actions."
        />
        <NoPermissionState description="This page needs cases.manage, ops.read, or both." />
      </div>
    );
  }

  return (
    <div className="space-y-5 pb-8">
      <PageHeader
        title="Operations queue"
        subtitle="Moderation and operational cases, assignment workflow, and restore actions."
      />

      {canReadOps ? (
        <section className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader>
              <CardTitle>Open cases</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">{ops?.workload.openCasesCount ?? 0}</CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Outbox pending</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">{ops?.queues.outbox.pending ?? 0}</CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Outbox failed</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">{ops?.queues.outbox.failed ?? 0}</CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Live sessions</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {ops?.workload.activeSuperAdminSessionsCount ?? 0}
            </CardContent>
          </Card>
        </section>
      ) : null}

      {canManageCases ? (
        <Card>
          <CardHeader>
            <CardTitle>Case queue</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!items.length && !loading ? (
              <EmptyState title="No open queue items" description="Cases will appear here as actions are recorded." />
            ) : (
              <div className="space-y-3">
                {items.map((item) => (
                  <div key={item._id} className="rounded-xl border border-border/70 bg-secondary/20 p-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="space-y-2">
                        <div className="text-sm font-medium text-foreground">{item.title}</div>
                        <div className="text-xs text-muted-foreground">
                          {item.resourceType} / {item.resourceId || "-"} / {formatDateTime(item.updatedAt ?? item.createdAt)}
                        </div>
                        <div className="flex flex-wrap gap-2">
                          <Badge variant={item.status === "resolved" ? "success" : item.status === "in_review" ? "warning" : "muted"}>
                            {item.status}
                          </Badge>
                          <Badge variant={item.priority === "critical" || item.priority === "high" ? "danger" : "muted"}>
                            {item.priority}
                          </Badge>
                          {item.assignedTo ? <Badge variant="muted">{item.assignedTo}</Badge> : null}
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={async () => {
                            try {
                              await updateSuperAdminCase(item._id, {
                                assignedTo: session?.superAdmin.email ?? "superadmin",
                                status: "in_review",
                                note: "Claimed from operations queue",
                              });
                              await loadQueue();
                            } catch (error) {
                              toast({ title: "Claim failed", description: String(error), variant: "danger" });
                            }
                          }}
                        >
                          Claim
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={async () => {
                            try {
                              await updateSuperAdminCase(item._id, {
                                status: "resolved",
                                note: "Resolved from operations queue",
                              });
                              await loadQueue();
                            } catch (error) {
                              toast({ title: "Resolve failed", description: String(error), variant: "danger" });
                            }
                          }}
                        >
                          Resolve
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={async () => {
                            try {
                              await updateSuperAdminCase(item._id, {
                                status: "open",
                                note: "Reopened from operations queue",
                              });
                              await loadQueue();
                            } catch (error) {
                              toast({ title: "Reopen failed", description: String(error), variant: "danger" });
                            }
                          }}
                        >
                          Reopen
                        </Button>
                        {canModerateContent &&
                        (item.resourceType === "post" || item.resourceType === "comment") &&
                        item.resourceId ? (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={async () => {
                              try {
                                const resourceId = item.resourceId;
                                if (!resourceId) {
                                  return;
                                }
                                if (item.resourceType === "post") {
                                  await restoreSuperAdminPost(resourceId);
                                } else {
                                  await restoreSuperAdminComment(resourceId);
                                }
                                await updateSuperAdminCase(item._id, {
                                  status: "resolved",
                                  note: "Resource restored from operations queue",
                                });
                                await loadQueue();
                                toast({ title: "Resource restored", description: resourceId, variant: "success" });
                              } catch (error) {
                                toast({ title: "Restore failed", description: String(error), variant: "danger" });
                              }
                            }}
                          >
                            Restore resource
                          </Button>
                        ) : null}
                      </div>
                    </div>

                    {item.description ? (
                      <p className="mt-3 text-sm text-muted-foreground">{item.description}</p>
                    ) : null}
                  </div>
                ))}
              </div>
            )}

            <PaginationControls pagination={getPagination(casesResponse)} loading={loading} onPageChange={setPage} />
          </CardContent>
        </Card>
      ) : null}
    </div>
  );
}
