import { useEffect, useState } from "react";
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerDescription,
  DrawerFooter,
  DrawerClose,
} from "@/shared/common/ui/drawer";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/shared/common/ui/select";
import { toast } from "sonner";
import {
  useCreateGlobalUnitConfig,
  useGetListOfGlobalUnitConfig,
  useUpdateGlobalUnitConfig,
  useDeleteGlobalUnitConfig,
  useGetOrganizationConfig,
  useCreateOrganizationConfig,
  useUpdateOrganizationConfig,
  useDeleteOrganizationConfig,
} from "@/super-admin/hooks/useConfig";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Loader2, Trash2 } from "lucide-react";
import { useUnit } from "@/user-management/hooks/useUnit";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { RadioGroup, RadioGroupItem } from "@/shared/common/ui/radio-group";
import { Switch } from "@/shared/common/ui/switch";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { prefixSuffixService } from "@/user-management/services/api/prefixSuffixService";
import { useMutation, useQuery } from "@tanstack/react-query";
export default function ManageOrganizationDrawer({
  manageOrgConfigOpen,
  setManageOrgConfigOpen,
  organizationId,
}: any) {
  const { getList } = useUnit();
  const [unit, setUnit] = useState("");
  const [maxUnits, setMaxUnits] = useState("");
  const [employees, setEmployees] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [canReceiveComplaint, setCanReceiveComplaint] = useState(false);
  const [unitConfigurationId, setUnitConfigurationId] = useState<string | null>(
    null,
  );

  const { data: unitsResponse } = organizationId
    ? getList(organizationId, {
        take: 300,
        skip: 0,
      })
    : { data: undefined };
  const localizedName = useLocalizedName();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const unitConfigQuery = useGetListOfGlobalUnitConfig(organizationId);
  const orgConfigQuery = useGetOrganizationConfig(organizationId);
  const [isUnitConfig, setIsUnitConfig] = useState(false);

  const listData = isUnitConfig ? unitConfigQuery.data : orgConfigQuery.data;
  const isLoading = isUnitConfig
    ? unitConfigQuery.isLoading
    : orgConfigQuery.isLoading;
  const refetch = isUnitConfig
    ? unitConfigQuery.refetch
    : orgConfigQuery.refetch;

  const createUnitMutation = useCreateGlobalUnitConfig();
  const updateUnitMutation = useUpdateGlobalUnitConfig();
  const deleteUnitMutation = useDeleteGlobalUnitConfig();
  const createOrgMutation = useCreateOrganizationConfig();
  const updateOrgMutation = useUpdateOrganizationConfig();
  const deleteOrgMutation = useDeleteOrganizationConfig();

  const isSubmitting = isUnitConfig
    ? createUnitMutation.isPending || updateUnitMutation.isPending
    : createOrgMutation.isPending || updateOrgMutation.isPending;
  const deleteMutation = isUnitConfig ? deleteUnitMutation : deleteOrgMutation;

  // Org config is 1-per-organization. Auto-load the existing record into edit
  // mode so submit becomes PUT instead of POST.
  const existingOrgConfig = (() => {
    const items = orgConfigQuery.data?.data?.items ?? [];
    if (!Array.isArray(items)) return null;
    return (
      items.find(
        (it: any) =>
          (it?.organizationId ?? it?.organization_id) === organizationId,
      ) ??
      items[0] ??
      null
    );
  })();

  // Unit config is 1-per-unit. Look up by the selected unit.
  const existingUnitConfig = (() => {
    if (!unit) return null;
    const items = unitConfigQuery.data?.data?.items ?? [];
    if (!Array.isArray(items)) return null;
    return (
      items.find((it: any) => (it?.unitId ?? it?.unit_id) === unit) ?? null
    );
  })();

  const singleUnitId =
    isUnitConfig &&
    unitsResponse?.data?.items &&
    Array.isArray(unitsResponse.data.items) &&
    unitsResponse.data.items.length === 1
      ? unitsResponse.data.items[0].id
      : null;

  useEffect(() => {
    if (!singleUnitId) return;
    if (unit) return; // keep user selection if already set
    setUnit(singleUnitId);
  }, [isUnitConfig, singleUnitId, unit]);

  useEffect(() => {
    if (isUnitConfig) return;
    if (existingOrgConfig?.id && editingId !== existingOrgConfig.id) {
      setEditingId(existingOrgConfig.id);
      setMaxUnits((existingOrgConfig.maximumNumberOfUnits ?? 0).toString());
    }
  }, [isUnitConfig, existingOrgConfig, editingId]);

  useEffect(() => {
    if (!isUnitConfig) return;
    if (existingUnitConfig?.id && editingId !== existingUnitConfig.id) {
      setEditingId(existingUnitConfig.id);
      setMaxUnits((existingUnitConfig.numberOfSubUnits ?? 0).toString());
      setEmployees(
        (existingUnitConfig.numberOfEmployeesPerUnit ?? 0).toString(),
      );
    }
  }, [isUnitConfig, existingUnitConfig, editingId]);

  const handleAddOrUpdate = () => {
    if (isUnitConfig && !unit) {
      toast.warning(t("superAdmin.messages.selectUnitWarning"));
      return;
    }
    if (isUnitConfig ? !maxUnits || !employees : !maxUnits) {
      toast.warning(t("superAdmin.messages.fillAllFields"));
      return;
    }

    if (isUnitConfig) {
      const payload = {
        unitId: unit,
        numberOfSubUnits: Number(maxUnits),
        numberOfEmployeesPerUnit: Number(employees),
      };
      const id = editingId || existingUnitConfig?.id || null;
      if (id) {
        updateUnitMutation.mutate(
          { id, data: payload },
          {
            onSuccess: () => {
              toast.success(t("superAdmin.messages.configUpdated"));
              resetForm();
              refetch();
            },
            onError: handleError,
          },
        );
      } else {
        createUnitMutation.mutate(payload, {
          onSuccess: () => {
            toast.success(t("superAdmin.messages.configAdded"));
            resetForm();
            refetch();
          },
          onError: (error: any) => handleDuplicateOrError(error),
        });
      }
      return;
    }

    // Org config — preserve other fields (e.g. canStartReceivingRecord) from
    // the existing record so we don't clobber the visibility toggle.
    const payload = {
      organizationId,
      maximumNumberOfUnits: Number(maxUnits),
      ...(existingOrgConfig?.canStartReceivingRecord !== undefined && {
        canStartReceivingRecord: existingOrgConfig.canStartReceivingRecord,
      }),
      ...(existingOrgConfig?.canCreateBranchByItself !== undefined && {
        canCreateBranchByItself: existingOrgConfig.canCreateBranchByItself,
      }),
    };
    const id = editingId || existingOrgConfig?.id || null;
    if (id) {
      updateOrgMutation.mutate(
        { id, data: payload },
        {
          onSuccess: () => {
            toast.success(t("superAdmin.messages.configUpdated"));
            resetForm();
            refetch();
          },
          onError: handleError,
        },
      );
    } else {
      createOrgMutation.mutate(payload, {
        onSuccess: () => {
          toast.success(t("superAdmin.messages.configAdded"));
          resetForm();
          refetch();
        },
        onError: (error: any) => handleDuplicateOrError(error),
      });
    }
  };

  const handleDuplicateOrError = (error: any) => {
    const status = error?.response?.status;
    const message: string =
      error?.response?.data?.message ?? error?.message ?? "";
    if (status === 400 && /duplicate/i.test(message)) {
      toast.warning(t("superAdmin.messages.configAlreadyExists"));
      refetch();
      return;
    }
    handleError(error);
  };

  const resetForm = () => {
    setUnit("");
    setMaxUnits("");
    setEmployees("");
    setEditingId(null);
    setCanReceiveComplaint(false);
    setUnitConfigurationId(null);
  };

  const handleEdit = (config: any) => {
    if (isUnitConfig) {
      setEditingId(config.id);
      setUnit(config.unitId ?? "");
      setMaxUnits((config.numberOfSubUnits ?? 0).toString());
      setEmployees((config.numberOfEmployeesPerUnit ?? 0).toString());
    } else {
      setEditingId(config.id);
      setMaxUnits((config.maximumNumberOfUnits ?? 0).toString());
    }
  };

  const handleDelete = (config: any) => {
    if (!config?.id) return;
    deleteMutation.mutate(config.id, {
      onSuccess: () => {
        toast.success(t("superAdmin.messages.configDeleted"));
        if (editingId === config.id) resetForm();
        refetch();
      },
      onError: handleError,
    });
  };

  const configType = isUnitConfig
    ? t("superAdmin.manageConfig.unit")
    : t("superAdmin.manageConfig.organization");

  const configLevel = isUnitConfig
    ? t("superAdmin.manageConfig.unitBased")
    : t("superAdmin.manageConfig.organizationLevel");

  const internalUnitConfigQuery = useQuery({
    queryKey: ["internal-unit-config", unit],
    queryFn: () => prefixSuffixService.getInternalConfig(unit),
    enabled: isUnitConfig && Boolean(unit),
    staleTime: Infinity,
    gcTime: Infinity,
  });

  useEffect(() => {
    if (!isUnitConfig || !unit) {
      setUnitConfigurationId(null);
      setCanReceiveComplaint(false);
      return;
    }
    const internalConfig = internalUnitConfigQuery.data?.data?.items?.[0];
    if (!internalConfig?.id) {
      setUnitConfigurationId(null);
      setCanReceiveComplaint(false);
      return;
    }
    setUnitConfigurationId(internalConfig.id);
    setCanReceiveComplaint(Boolean(internalConfig.canReceiveComplaint));
  }, [internalUnitConfigQuery.data, isUnitConfig, unit]);

  const { mutate: updateCanReceiveComplaint, isPending: isUpdatingComplaint } =
    useMutation({
      mutationFn: async (checked: boolean) => {
        if (!unit) throw new Error("Missing unit id");

        // If no internal unit config exists yet, create it first.
        if (!unitConfigurationId) {
          await prefixSuffixService.createInternalPrefixSuffix({
            unitId: unit,
          });
        }

        const current = await prefixSuffixService.getInternalConfig(unit);
        const internalConfig = current.data?.items?.[0];
        if (!internalConfig?.id) {
          throw new Error("Failed to resolve unit configuration id");
        }

        return prefixSuffixService.updateInternalPrefixSuffix(
          {
            canReceiveComplaint: checked,
            unitId: unit,
          },
          internalConfig.id,
        );
      },
      onSuccess: (_data, checked) => {
        setCanReceiveComplaint(checked);
        internalUnitConfigQuery.refetch();
      },
      onError: (err) => {
        console.error(err);
        handleError(err);
      },
    });

  return (
    <Drawer open={manageOrgConfigOpen} onOpenChange={setManageOrgConfigOpen}>
      <DrawerContent className="max-h-[85vh] overflow-hidden flex flex-col top-1/6 bg-white dark:bg-gray-900">
        <div className="overflow-y-auto flex-1">
          <DrawerHeader className="pb-4">
            <DrawerTitle className="text-lg text-primary-700 dark:text-primary-400">
              {t("superAdmin.manageConfig.title", { type: configType })}
            </DrawerTitle>
            <DrawerDescription className="text-primary-600/80 dark:text-primary-300/80 space-y-3">
              <div>
                {t("superAdmin.manageConfig.description", {
                  level: configLevel,
                })}
              </div>

              {/* Radio Group for Organization/Unit selection */}
              <RadioGroup
                value={isUnitConfig ? "unit" : "org"}
                onValueChange={(value) => {
                  setIsUnitConfig(value === "unit");
                  resetForm();
                }}
                className="inline-flex rounded-md bg-gray-100 dark:bg-gray-800 p-1">
                <RadioGroupItem value="org" id="org-radio" className="hidden" />
                <label
                  htmlFor="org-radio"
                  className={`cursor-pointer px-4 py-1 rounded-md text-sm font-medium transition-all
      ${
        !isUnitConfig
          ? "bg-primary-600 text-white"
          : "text-primary-700 dark:text-primary-300 hover:bg-primary-200 dark:hover:bg-primary-900/30"
      }`}>
                  {t("superAdmin.manageConfig.organization")}
                </label>

                <RadioGroupItem
                  value="unit"
                  id="unit-radio"
                  className="hidden"
                />
                <label
                  htmlFor="unit-radio"
                  className={`cursor-pointer px-4 py-1 rounded-md text-sm font-medium transition-all
      ${
        isUnitConfig
          ? "bg-primary-600 text-white"
          : "text-primary-700 dark:text-primary-300 hover:bg-primary-200 dark:hover:bg-primary-900/30"
      }`}>
                  {t("superAdmin.manageConfig.unit")}
                </label>
              </RadioGroup>

              {/* Unit Selector */}
              {isUnitConfig && unitsResponse?.data?.items?.length > 0 && (
                <div className="pt-2">
                  <label className="block text-sm font-medium text-primary-700 dark:text-primary-300">
                    {t("superAdmin.manageConfig.selectUnit")}
                  </label>
                  <Select
                    value={unit}
                    onValueChange={(value) => setUnit(value)}>
                    <SelectTrigger className="mt-1 border-primary-400 dark:border-primary-700 dark:bg-gray-800 dark:text-gray-100 focus:ring-primary-500">
                      <SelectValue
                        placeholder={t(
                          "superAdmin.manageConfig.selectUnitPlaceholder",
                        )}
                      />
                    </SelectTrigger>
                    <SelectContent>
                      {unitsResponse?.data.items.map((u: UnitDto) => (
                        <SelectItem key={u.id} value={u.id}>
                          {localizedName(u.name)}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
            </DrawerDescription>
          </DrawerHeader>

          <div className="px-6 space-y-4 pb-4">
            {/* Input Fields */}
            <div
              className={`grid gap-4 ${
                isUnitConfig ? "grid-cols-2" : "grid-cols-1"
              }`}>
              <div>
                <label className="text-sm font-medium text-primary-700 dark:text-primary-300">
                  {isUnitConfig
                    ? t("superAdmin.manageConfig.subOrganizations")
                    : t(
                        "superAdmin.manageConfig.maxUnits",
                        "Maximum Number of Units",
                      )}
                </label>
                <Input
                  type="number"
                  min="0"
                  value={maxUnits}
                  onChange={(e) => setMaxUnits(e.target.value)}
                  placeholder={t("superAdmin.manageConfig.subOrgsPlaceholder")}
                  className="border-primary-400 dark:border-primary-700 dark:bg-gray-800 dark:text-gray-100 focus:ring-primary-500"
                />
              </div>

              {isUnitConfig && (
                <div>
                  <label className="text-sm font-medium text-primary-700 dark:text-primary-300">
                    {t("superAdmin.manageConfig.employeesPerOrg")}
                  </label>
                  <Input
                    type="number"
                    min="0"
                    value={employees}
                    onChange={(e) => setEmployees(e.target.value)}
                    placeholder={t(
                      "superAdmin.manageConfig.employeesPlaceholder",
                    )}
                    className="border-primary-400 dark:border-primary-700 dark:bg-gray-800 dark:text-gray-100 focus:ring-primary-500"
                  />
                </div>
              )}

              {isUnitConfig && (
                <div className="col-span-2 mt-1">
                  <div className="flex items-center justify-between rounded-lg border border-primary-200 bg-primary-50/40 px-4 py-3">
                    <div>
                      <div className="text-sm font-semibold text-primary-700 dark:text-primary-300">
                        {t(
                          "superAdmin.manageConfig.canReceiveComplaint",
                          "Can Receive Complaint",
                        )}
                      </div>
                      <div className="text-xs text-primary-600/70">
                        {t(
                          "superAdmin.manageConfig.canReceiveComplaintDescription",
                          "Controls whether this unit can accept complaints.",
                        )}
                      </div>
                    </div>
                    <Switch
                      checked={canReceiveComplaint}
                      onCheckedChange={(checked) =>
                        updateCanReceiveComplaint(checked)
                      }
                      disabled={!unit || isUpdatingComplaint}
                    />
                  </div>
                </div>
              )}
            </div>

            {/* Add / Update Button */}
            <Button
              onClick={handleAddOrUpdate}
              className="w-full flex items-center gap-2 bg-primary-600 hover:bg-primary-700 text-white"
              disabled={isSubmitting}>
              {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
              {editingId ||
              (!isUnitConfig && existingOrgConfig?.id) ||
              (isUnitConfig && existingUnitConfig?.id)
                ? t("superAdmin.manageConfig.updateConfiguration")
                : t("superAdmin.manageConfig.addConfiguration")}
            </Button>

            {/* Configurations List */}
            <div className="border border-primary-300 dark:border-primary-800 rounded-lg p-3 space-y-3 mt-4">
              {isLoading ? (
                <p className="text-sm text-primary-600/70 text-center py-4">
                  {t("superAdmin.manageConfig.loading")}
                </p>
              ) : listData?.data?.items?.length ? (
                <div className="max-h-48 overflow-y-auto">
                  {listData.data.items.map((c: any) => (
                    <div
                      key={c.id}
                      className="flex items-center justify-between border-b border-primary-100 pb-2 last:border-none py-2">
                      <div>
                        {isUnitConfig && (
                          <p className="font-semibold capitalize text-primary-700 text-sm">
                            {localizedName(
                              unitsResponse?.data?.items?.find(
                                (u: UnitDto) => u.id === c.unitId,
                              )?.name,
                            ) || c.unitId}
                          </p>
                        )}
                        <p className="text-xs text-primary-600/80">
                          {isUnitConfig ? (
                            <>
                              {c.numberOfSubUnits}{" "}
                              {t("superAdmin.manageConfig.subOrganizations")} •{" "}
                              {c.numberOfEmployeesPerUnit}{" "}
                              {t("superAdmin.manageConfig.employeesPerOrg")}
                            </>
                          ) : (
                            <>
                              {t(
                                "superAdmin.manageConfig.maxUnits",
                                "Maximum Number of Units",
                              )}
                              : {c.maximumNumberOfUnits ?? 0}
                            </>
                          )}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEdit(c)}
                          className="h-8 px-2 text-xs text-primary-700 dark:text-primary-300 hover:bg-primary-100 dark:hover:bg-primary-900/30">
                          {t("superAdmin.manageConfig.edit")}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(c)}
                          disabled={
                            deleteMutation.isPending &&
                            deleteMutation.variables === c.id
                          }
                          className="h-8 w-8 p-0 text-primary-700 dark:text-primary-300 hover:bg-primary-100 dark:hover:bg-primary-900/30">
                          {deleteMutation.isPending &&
                          deleteMutation.variables === c.id ? (
                            <Loader2 className="h-3.5 w-3.5 animate-spin" />
                          ) : (
                            <Trash2 size={14} />
                          )}
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-primary-600/70 text-center py-4">
                  {t("superAdmin.manageConfig.noConfigurations")}
                </p>
              )}
            </div>
          </div>
        </div>

        <DrawerFooter className="pt-4 border-t border-primary-200 dark:border-primary-800 bg-primary-50/40 dark:bg-primary-900/10">
          <DrawerClose asChild>
            <Button
              variant="outline"
              onClick={resetForm}
              className="w-full border-primary-500 dark:border-primary-700 text-primary-700 dark:text-primary-300 hover:bg-primary-100 dark:hover:bg-primary-900/30">
              {t("superAdmin.manageConfig.close")}
            </Button>
          </DrawerClose>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  );
}
