"use client";

import { CheckCheck, CircleCheck, CircleDot } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";

import { Button } from "@/components/ui/button";
import type { ApiResult } from "@/modules/core/server/api";
import type { IncidentStatus, SystemIncident } from "@/modules/core/types";

type IncidentStatusActionsProps = {
  incident: SystemIncident;
};

type StatusAction = {
  label: string;
  status: IncidentStatus;
  icon: LucideIcon;
};

const STATUS_ACTIONS: Record<IncidentStatus, StatusAction[]> = {
  open: [
    { label: "确认", status: "acknowledged", icon: CircleDot },
    { label: "解决", status: "resolved", icon: CircleCheck },
  ],
  acknowledged: [
    { label: "解决", status: "resolved", icon: CircleCheck },
    { label: "关闭", status: "closed", icon: CheckCheck },
  ],
  resolved: [{ label: "关闭", status: "closed", icon: CheckCheck }],
  closed: [],
};

export function IncidentStatusActions({ incident }: IncidentStatusActionsProps): React.ReactElement {
  const router = useRouter();
  const [message, setMessage] = useState("");
  const [isPending, setIsPending] = useState(false);
  const actions = STATUS_ACTIONS[incident.status];

  async function updateStatus(status: IncidentStatus): Promise<void> {
    setMessage("");
    setIsPending(true);
    const response = await fetch(`/api/system/incidents/${incident.id}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ status }),
    });
    const result = (await response.json()) as ApiResult<{ incident: SystemIncident }>;
    setIsPending(false);

    if (!result.success) {
      setMessage(result.reason);
      return;
    }

    router.refresh();
  }

  if (actions.length === 0) {
    return <span className="block text-right text-xs text-muted-foreground">已关闭</span>;
  }

  return (
    <div className="grid justify-end gap-2">
      <div className="flex items-center justify-end gap-2">
        {actions.map((action) => (
          <Button
            disabled={isPending}
            key={action.status}
            onClick={() => void updateStatus(action.status)}
            size="sm"
            type="button"
            variant="outline"
          >
            <action.icon className="size-4" aria-hidden="true" />
            {action.label}
          </Button>
        ))}
      </div>
      {message ? <p className="text-right text-xs text-destructive">{message}</p> : null}
    </div>
  );
}
