import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { PositionTypeDto } from "@/user-management/dto/positions/positionType";

import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuItem,
} from "@/shared/common/ui/dropdown-menu";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";

import { Button } from "@/shared/common/ui/button";
import { MoreVertical, Edit, Eye, Trash2, Pencil } from "lucide-react";
import { t } from "i18next";
import PositionTypeMigrationModal from "./PostionTypeMigration";
import { CreatePositionForm } from "./CreatePositionForm";
import { useLocalizedName } from "@/shared/common/localizedName";
import { usePositionTypes } from "@/user-management/hooks/usePositionTypes";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";

interface PositionTypeResponse {
  items: PositionTypeDto[];
  count: number;
}

type ActionsCellProps = {
  row: PositionTypeDto;
  globalPositionTypes?: PositionTypeResponse;
  onDelete?: () => void | Promise<void>;
  onEdit?: () => void | Promise<void>;
};

/*
 * TODO(record-toggles): this menu used to carry CanReceiveRecord /
 * CanAssignRecord / CanCreateBankRecord switches. They never worked. IAM's
 * PositionTypeConfiguration entity only has { id, organizationId,
 * positionTypeId, timeframe } — verified against every local build (0.7.4
 * through 0.7.12) and the live swagger. canAssignRecord and
 * canCreateBankRecord do not exist anywhere in the IAM package, and the global
 * ValidationPipe runs with forbidNonWhitelisted, so every write 400'd. The
 * reads were broken too: the list route filters on organizationId (the repo is
 * built as TExtraCrudRepository(repo, "organizationId")) while the UI passed a
 * positionTypeId, so it always came back empty.
 *
 * The flag that does exist is PositionConfiguration.canReceiveRecord, keyed by
 * positionId — a per-position setting served by /api/position-configurations,
 * not a per-position-type one. Restoring this needs either that endpoint and a
 * position-level UI, or new columns on PositionTypeConfiguration in IAM.
 */
const PositionTypeActionsCell: React.FC<ActionsCellProps> = ({
  row,
  globalPositionTypes,
  onDelete,
  onEdit,
}) => {
  const navigate = useNavigate();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showMigrateDialog, setShowMigrateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const localizedName = useLocalizedName();
  const { deletePositionType } = usePositionTypes();

  // Create position type options from globalPositionTypes - only those WITHOUT unitId
  const positionTypeOptions =
    globalPositionTypes?.items
      .filter((item) => !item.unitId)
      .map((item) => ({
        label: localizedName(item.name),
        value: item.id,
      })) || [];

  // Only show migrate/delete actions if current row has a unitId
  const canBeModified = !!row.unitId;

  const handleView = () => {
    navigate(`/user-management/position-management/edit/${row.id}`);
  };

  const handleMigrate = (e: Event) => {
    e.preventDefault();
    setDropdownOpen(false);
    setShowMigrateDialog(true);
  };

  const handleEdit = (e: Event) => {
    e.preventDefault();
    setDropdownOpen(false);
    setShowEditDialog(true);
  };

  // Goes through the mutation rather than the service directly, so the cache is
  // invalidated and IAM's 403 for built-in types reaches the user.
  const handleDelete = async () => {
    try {
      await deletePositionType.mutateAsync(row.id);
      setShowDeleteDialog(false);
      await onDelete?.();
    } catch {
      // reported by the mutation's onError
    }
  };

  return (
    <>
      <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0">
            <MoreVertical className="h-4 w-4" />
            <span className="sr-only">Open actions menu</span>
          </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent
          align="end"
          onInteractOutside={(e) => {
            const target = e.target as HTMLElement;
            if (!target.closest('[role="dialog"]')) {
              setDropdownOpen(false);
            }
          }}>
          <DropdownMenuLabel>{t("userRecord.Actions")}</DropdownMenuLabel>

          {canBeModified && (
            <DropdownMenuItem
              onSelect={handleMigrate}
              className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200">
              <Edit className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
              <span> {t("common.Migrate")}</span>
            </DropdownMenuItem>
          )}

          {canBeModified && (
            <DropdownMenuItem
              onSelect={handleEdit}
              className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200">
              <Pencil className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
              <span>{t("common.Edit")}</span>
            </DropdownMenuItem>
          )}

          <DropdownMenuItem
            onSelect={handleView}
            className="cursor-pointer hover:!text-primary-700 !bg-transparent !transition-colors duration-200">
            <Eye className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
            <span>{t("common.View")}</span>
          </DropdownMenuItem>

          {canBeModified && (
            <DropdownMenuItem
              onSelect={() => {
                setDropdownOpen(false);
                setShowDeleteDialog(true);
              }}
              className="cursor-pointer hover:!text-red-500 !bg-transparent !transition-colors duration-200">
              <Trash2 className="mr-2 h-4 w-4 group-hover:text-white transition-colors duration-200" />
              <span>{t("common.Delete")}</span>
            </DropdownMenuItem>
          )}
        </DropdownMenuContent>
      </DropdownMenu>

      {showMigrateDialog && (
        <PositionTypeMigrationModal
          isOpen={showMigrateDialog}
          onClose={() => {
            setShowMigrateDialog(false);
          }}
          toId={row.id}
          toName={localizedName(row.name)}
          positionTypeOptions={positionTypeOptions}
        />
      )}

      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="sm:max-w-3xl max-h-[90vh] flex flex-col p-6">
          <DialogHeader className="pb-4">
            <DialogTitle>{t("common.Edit")}</DialogTitle>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto pr-2 min-h-0">
            {showEditDialog && (
              <CreatePositionForm
                key={row.id + "-edit"}
                mode="edit"
                positionTypeId={row.id}
                initialValues={{
                  nameAm: row.name.am,
                  nameEn: row.name.en,
                  unitId: row.unitId ?? "",
                  key: row.key,
                }}
                onSuccess={async () => {
                  setShowEditDialog(false);
                  if (onEdit) {
                    await onEdit();
                  }
                }}
                onCancel={() => setShowEditDialog(false)}
              />
            )}
          </div>
        </DialogContent>
      </Dialog>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("common.ConfirmDelete")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("common.DeleteConfirmationMessage", {
                name: localizedName(row.name),
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deletePositionType.isPending}>
              {t("common.Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deletePositionType.isPending}
              className="bg-red-500 hover:bg-red-600">
              {deletePositionType.isPending
                ? t("common.Deleting")
                : t("common.Delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default PositionTypeActionsCell;
