"use client";

import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { X, Loader2, Phone, BadgeCheck, Wallet } from "lucide-react";
import { useRouter } from "@/i18n/routing";
import { apiGet } from "@/lib/api/client";
import { formatCurrency } from "@/lib/format";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

type EmployeeSummary = {
  id: string;
  name: string;
  phone: string;
  role: string;
  baseSalary: number;
};

const KNOWN_ROLES = ["Owner", "Manager", "Cashier", "Waiter", "Chef", "Delivery"];

/**
 * Lightweight modal showing one employee's details, opened by clicking an actor
 * in the audit log. Fetches GET /employees/{id}; if the staff member was removed
 * it shows a "no longer active" note with the name we already have.
 */
export function EmployeeDetailsDialog({
  cafeId,
  employeeId,
  fallbackName,
  onClose,
}: {
  cafeId: string;
  employeeId: string | null;
  fallbackName?: string | null;
  onClose: () => void;
}) {
  const t = useTranslations("hr");
  const tCommon = useTranslations("common");
  const router = useRouter();
  const open = !!employeeId;

  // Close on Escape.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const { data, isLoading, isError } = useQuery({
    queryKey: ["employee", cafeId, employeeId],
    queryFn: () => apiGet<EmployeeSummary>(`/api/cafes/${cafeId}/employees/${employeeId}`),
    enabled: open,
  });

  if (!open) return null;

  const roleLabel = (r: string) => (KNOWN_ROLES.includes(r) ? t(`roles.${r}`) : r);
  const notFound = isError || (!isLoading && !data);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm rounded-xl border border-border bg-card p-5 shadow-lg"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
      >
        <div className="mb-3 flex items-start justify-between gap-2">
          <h2 className="text-base font-semibold">{t("employeeDetails")}</h2>
          <button
            type="button"
            onClick={onClose}
            aria-label={tCommon("close")}
            className="rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
          >
            <X className="size-4" />
          </button>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center py-8 text-muted-foreground">
            <Loader2 className="size-5 animate-spin" />
          </div>
        ) : notFound ? (
          <div className="space-y-2 py-2">
            <p className="text-sm font-medium">{fallbackName ?? employeeId}</p>
            <p className="text-sm text-muted-foreground">{t("employeeNotFound")}</p>
          </div>
        ) : (
          <div className="space-y-3">
            <div className="flex items-center justify-between gap-2">
              <p className="text-lg font-semibold">{data!.name}</p>
              <Badge variant="outline" className="gap-1">
                <BadgeCheck className="size-3.5" />
                {roleLabel(data!.role)}
              </Badge>
            </div>
            <div className="space-y-1.5 text-sm">
              <p className="flex items-center gap-2 text-muted-foreground">
                <Phone className="size-3.5 shrink-0" />
                <span dir="ltr" className="font-mono">{data!.phone}</span>
              </p>
              {data!.baseSalary > 0 ? (
                <p className="flex items-center gap-2 text-muted-foreground">
                  <Wallet className="size-3.5 shrink-0" />
                  <span>{formatCurrency(data!.baseSalary)}</span>
                </p>
              ) : null}
            </div>
            <div className="border-t border-border/80 pt-3">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  onClose();
                  router.push("/hr");
                }}
              >
                {t("openInHr")}
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
