import { useEffect, useState, useMemo, useCallback } from "react";
import { Button } from "@/shared/common/ui/button";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";

import { Link } from "react-router-dom";
import { Plus } from "lucide-react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { usePositionTypes } from "@/user-management/hooks/usePositionTypes";
import { createPositionTypeColumns } from "./PositionTypeColumnDefn";
import { positionTypeService } from "@/user-management/services/api/positionTypesService";
import { t } from "i18next";
import { toast } from "sonner";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useAuth } from "@/shared/context/AuthContext";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { PositionTypeDto } from "@/user-management/dto/positions/positionType";

export default function PositionManagement() {
  const [pageIndex, setPageIndex] = useState(0);
  const pageSize = 10;
  const [isExporting, setIsExporting] = useState<boolean>(false);
  const [searchTerm, setSearchTerm] = useState("");

  const { user } = useAuth();

  const { getAccessibleList } = useUnit();

  const organizationId = user?.employee?.[0]?.organizationId;

  const { data: unitsResponse, isError: isUnitsError } = getAccessibleList(
    organizationId ?? "",
    {
      take: 300,
      skip: 0,
    },
  );

  // Add state for selected unitId
  // Default: if super_admin => "All", otherwise wait for units
  const [selectedUnitId, setSelectedUnitId] = useState<string>("All");

  useEffect(() => {
    // If there’s no selectedUnitId yet, default to first unit (if any), otherwise keep "All"
    if (!selectedUnitId) {
      if (unitsResponse?.data?.items?.length) {
        setSelectedUnitId(unitsResponse.data.items[0].id);
      } else {
        setSelectedUnitId("All");
      }
    }
  }, [unitsResponse, selectedUnitId]);

  // Reset to first page whenever the search term or unit changes so users
  // land on the first page of matches instead of an empty later page.
  useEffect(() => {
    setPageIndex(0);
  }, [searchTerm, selectedUnitId]);

  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  const showingAllUnits = selectedUnitId === "All";

  const {
    positionTypeResponse,
    isLoading,
    isError,
    positionTypeByUnitId,
    isLoadingPosition,
    isErrorPosition,
    refetch,
    refetchPosition,
  } = usePositionTypes({
    params: {
      take: 1000,
      skip: 0,
      orderBy: "updatedAt:DESC",
    },
    unitId: showingAllUnits ? undefined : selectedUnitId,
  });

  // Refresh whichever list is on screen. `positionTypeResponse` is the
  // unscoped fetch, so it doubles as the migration-target source — no second
  // usePositionTypes() call needed (its cache key ignores unitId, so a second
  // call returned the very same query).
  const handlePositionTypeChanged = useCallback(async () => {
    await (showingAllUnits ? refetch() : refetchPosition());
  }, [showingAllUnits, refetch, refetchPosition]);

  const columns = useMemo(
    () =>
      createPositionTypeColumns(
        positionTypeResponse,
        handlePositionTypeChanged,
        handlePositionTypeChanged,
      ),
    [positionTypeResponse, handlePositionTypeChanged],
  );

  const allItems = useMemo(
    () =>
      (showingAllUnits
        ? positionTypeResponse?.items
        : positionTypeByUnitId?.items) || [],
    [showingAllUnits, positionTypeResponse?.items, positionTypeByUnitId?.items],
  );

  const filteredItems = useMemo(() => {
    const trimmed = searchTerm.trim().toLowerCase();
    if (!trimmed) return allItems;
    return allItems.filter((item: PositionTypeDto) => {
      const en = (item?.name?.en || "").toLowerCase();
      const am = (item?.name?.am || "").toLowerCase();
      const key = (item?.key || "").toLowerCase();
      return (
        en.includes(trimmed) || am.includes(trimmed) || key.includes(trimmed)
      );
    });
  }, [allItems, searchTerm]);

  const paginatedItems = useMemo(() => {
    const start = pageIndex * pageSize;
    return filteredItems.slice(start, start + pageSize);
  }, [filteredItems, pageIndex, pageSize]);

  // Track whichever query is actually feeding the table — picking a unit used
  // to leave the previous unit's rows on screen with no loading state.
  const isLoadingList = showingAllUnits ? isLoading : isLoadingPosition;
  const isErrorList = showingAllUnits ? isError : isErrorPosition;

  const exportTypes = () => {
    setIsExporting(true);
    positionTypeService
      .getAll({ take: 3000 })
      .then((allPositionKeys) => {
        const positionTypeKeys = allPositionKeys.data?.items?.map((p) => p.key);

        if (!positionTypeKeys?.length) {
          toast.error(t("contentManagement.exportFailed"));
          return;
        }

        // One key per line, downloaded as a plain text file.
        const blob = new Blob([positionTypeKeys.join("\n")], {
          type: "text/plain",
        });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "position_keys.txt";
        link.click();
        URL.revokeObjectURL(link.href);
      })
      .catch(() => {
        toast.error(t("contentManagement.exportFailed"));
      })
      .finally(() => {
        setIsExporting(false);
      });
  };

  return (
    <div className="p-6 space-y-6">
      <Card className="py-0 col-span-2 shadow-none border-none bg-transparent px-0">
        <CardHeader className="flex flex-row justify-between items-center px-0">
          <CardTitle className="text-xl font-semibold ">
            {t("contentManagement.permissionType")}
          </CardTitle>
          <Button onClick={exportTypes} disabled={isExporting}>
            {isExporting
              ? t("contentManagement.exporting")
              : t("contentManagement.exportTypes")}
          </Button>
        </CardHeader>
        {!!unitsResponse?.data?.items?.length && (
          <div className="mb-4 w-1/2">
            <label className="block text-sm font-medium text-gray-700">
              {t("organization.selectUnit")}
            </label>
            <Select
              value={selectedUnitId}
              onValueChange={(value) => setSelectedUnitId(value)}>
              <SelectTrigger className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm [&>span]:truncate">
                <SelectValue placeholder={t("organization.selectUnit")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem key="all" value="All">
                  {t("common.all")}
                </SelectItem>
                {unitsResponse.data.items.map((unit: UnitDto) => (
                  <SelectItem key={unit.id} value={unit.id}>
                    <span className="block truncate max-w-70">
                      {unit.name.en || unit.name.am}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}
        {isUnitsError && (
          <p className="mb-4 text-sm text-red-500">
            {t("organization.errorLoadingUnits")}
          </p>
        )}
        <CardContent className="px-0">
          {isLoadingList ? (
            <div className="py-10 text-center text-muted-foreground">
              {t("common.loading")}
            </div>
          ) : isErrorList ? (
            <div className="py-10 text-center text-red-500">
              {t("contentManagement.failedToLoadPositionTypes")}
            </div>
          ) : (
            <AdvancedTable
              columns={columns}
              data={paginatedItems}
              tableName="Positions"
              toolBarPosition="right"
              itemCount={filteredItems.length}
              onGlobalFilterChange={setSearchTerm}
              extraToolbar={
                <Link to="/user-management/position-management/new">
                  <Button className="px-5 py-2 rounded-md text-sm font-medium shadow-md">
                    <Plus className="w-4 h-4 mr-2" />
                    {t("contentManagement.newPermission")}
                  </Button>
                </Link>
              }
              pageIndex={pageIndex}
              onPageChange={handlePageChange}
              nextFunction={() => handlePageChange(pageIndex + 1)}
              prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
            />
          )}
        </CardContent>
      </Card>
    </div>
  );
}
