import { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";

import { useUnit } from "@/user-management/hooks/useUnit";
import { useAuth } from "@/shared/context/AuthContext";
import { positionTypePermissionService } from "@/user-management/services/api/positionTypePermissionService";
import { usePositionTypes } from "@/user-management/hooks/usePositionTypes";
import { useApplications } from "@/user-management/hooks/useApplications";
import { PermissionSearch } from "./PermissionSearch";
import { useLocalizedName } from "@/shared/common/localizedName";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { t } from "i18next";

export const EditPositionForm = ({ id }: { id: string }) => {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { getList } = useUnit();
  const localizedName = useLocalizedName();

  const { positionType, isLoadingSingle, isErrorSingle } = usePositionTypes({
    id,
  });

  const organizationId =
    user?.employee && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  const { applications, isLoading: isLoadingApplications } = useApplications();

  const { data: unitsResponse } = getList(organizationId || "", {
    take: 300,
    skip: 0,
  });

  const [selectedApplicationId, setSelectedApplicationId] =
    useState<string>("");

  // Shares the cache key CreatePositionForm writes under, so editing a position
  // type's permissions refreshes this view too.
  const {
    data: assignedResponse,
    isLoading: isLoadingPermissions,
    isError: isErrorPermissions,
  } = useQuery({
    queryKey: ["position-type-permissions", id],
    queryFn: () =>
      positionTypePermissionService.getPermissionsByPositionTypeId(id),
    enabled: !!id,
  });

  const assignedPermissions = assignedResponse?.data?.items ?? [];

  if (isLoadingSingle) {
    return (
      <p className="py-8 text-center text-muted-foreground">
        {t("common.loading")}
      </p>
    );
  }

  if (isErrorSingle || !positionType) {
    return (
      <div className="space-y-4">
        <p className="py-8 text-center text-red-500">
          {t("contentManagement.positionTypeNotFound")}
        </p>
        <div className="flex justify-end">
          <Button
            type="button"
            variant="outline"
            onClick={() => navigate("/user-management/position-management")}>
            {t("common.Back")}
          </Button>
        </div>
      </div>
    );
  }

  const unit = unitsResponse?.data?.items?.find(
    (u: UnitDto) => u.id === positionType.unitId,
  );
  const unitName = unit ? unit.name.en || unit.name.am : positionType.unitId;

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <Label>{t("contentManagement.englishName")}</Label>
        <Input value={positionType.name.en} disabled readOnly />
      </div>

      <div className="space-y-2">
        <Label>{t("contentManagement.amharicName")}</Label>
        <Input value={positionType.name.am} disabled readOnly />
      </div>

      <div className="space-y-2">
        <Label>{t("contentManagement.key")}</Label>
        <Input value={positionType.key} disabled readOnly />
      </div>

      <div className="space-y-2">
        <Label>{t("organization.selectUnit")}</Label>
        <Input value={unitName ?? ""} disabled readOnly />
      </div>

      <div className="space-y-2">
        <Label>{t("contentManagement.selectApplication")}</Label>
        <Select
          value={selectedApplicationId}
          onValueChange={setSelectedApplicationId}
          disabled={isLoadingApplications}>
          <SelectTrigger className="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
            <SelectValue
              placeholder={
                isLoadingApplications
                  ? t("common.loading")
                  : t("contentManagement.selectApplication")
              }
            />
          </SelectTrigger>
          <SelectContent className="max-h-60 overflow-y-auto">
            {applications?.map((app) => (
              <SelectItem key={app.id} value={app.id}>
                {localizedName(app.name)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-2">
        <Label>{t("contentManagement.permission")}</Label>
        {selectedApplicationId ? (
          <PermissionSearch
            selectedPermissions={assignedPermissions.map((perm) => perm.id)}
            onPermissionChange={() => {
              // view-only mode in edit form
            }}
            applicationId={selectedApplicationId}
            disabled
          />
        ) : (
          <div className="border rounded-md p-4 bg-background max-h-96 overflow-y-auto">
            {isLoadingPermissions ? (
              <div className="text-center py-4 text-gray-500">
                {t("common.loading")}
              </div>
            ) : isErrorPermissions ? (
              <div className="text-center py-4 text-red-500">
                {t("contentManagement.failedToLoadPermissions")}
              </div>
            ) : assignedPermissions.length === 0 ? (
              <div className="text-center py-4 text-gray-500">
                {t("contentManagement.noPermissionsAvailable")}
              </div>
            ) : (
              <ul className="grid grid-cols-1 md:grid-cols-2 gap-2">
                {assignedPermissions.map((perm) => (
                  <li
                    key={perm.id}
                    className="capitalize text-sm py-1 px-2 rounded bg-muted/40">
                    {localizedName(perm.name)}
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}
      </div>

      <div className="flex justify-end">
        <Button
          type="button"
          variant="outline"
          onClick={() => navigate("/user-management/position-management")}>
          {t("common.Back")}
        </Button>
      </div>
    </div>
  );
};
