import React, { useState, useMemo } from "react";
import { toast } from "sonner";
import { usePositionTypes } from "@/user-management/hooks/usePositionTypes";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogTrigger,
} from "@/shared/common/ui/alert-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { Search, X, ArrowLeftRight } from "lucide-react";
import { Badge } from "@/shared/common/ui/badge";
interface PositionTypeMigrationModalProps {
  isOpen: boolean;
  onClose: () => void;
  fromId?: string; // Optional - can be selected if not provided
  fromName?: string;
  toId?: string; // Optional - can be selected if not provided
  toName?: string;
  unitId?: string;
  positionTypeOptions?: { label: string; value: string }[]; // For dropdown selection
}

const PositionTypeMigrationModal: React.FC<PositionTypeMigrationModalProps> = ({
  isOpen,
  onClose,
  fromId: initialFromId,
  fromName: initialFromName,
  toId: initialToId,
  toName: initialToName,
  unitId,
  positionTypeOptions = [],
}) => {
  const [selectedPositions, setSelectedPositions] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const pageSize = 20;
  
  // State for from/to selection
  const [fromId, setFromId] = useState<string>(initialFromId || "");
  const [toId, setToId] = useState<string>(initialToId || "");

  const { updatePositionTypeFromTo, migratePositionsByPositions } =
    usePositionTypes();
  const { allScopedDepartments } = useSettings();
  const localizedName = useLocalizedName();
  const { handleError } = useErrorHandler(t);

  // Combined options so the preset (initial) from/to are also selectable on either side.
  const combinedOptions = useMemo(() => {
    const merged = [...positionTypeOptions];
    const ensure = (value?: string, label?: string) => {
      if (!value) return;
      if (!merged.some((opt) => opt.value === value)) {
        merged.push({ value, label: label || value });
      }
    };
    ensure(initialFromId, initialFromName);
    ensure(initialToId, initialToName);
    return merged;
  }, [positionTypeOptions, initialFromId, initialFromName, initialToId, initialToName]);

  // Get names from combined options if not provided
  const fromName =
    combinedOptions.find((opt) => opt.value === fromId)?.label ||
    initialFromName ||
    fromId;
  const toName =
    combinedOptions.find((opt) => opt.value === toId)?.label ||
    initialToName ||
    toId;

  const handleSwap = () => {
    setFromId(toId);
    setToId(fromId);
  };

  // Map positions from allScopedDepartments
  const positions = useMemo(() => {
    return Array.isArray(allScopedDepartments)
      ? allScopedDepartments.map((pos) => ({
          id: pos.id,
          name: localizedName(pos.name) || "N/A",
        }))
      : [];
  }, [allScopedDepartments, localizedName]);


  // Filter positions based on search query
  const filteredPositions = useMemo(() => {
    if (!searchQuery.trim()) return positions;

    return positions.filter((pos) =>
      pos.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [positions, searchQuery]);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 5) {
      if (page * pageSize < filteredPositions.length) {
        setPage((prev) => prev + 1);
      }
    }
  };

  const handleSelectPosition = (positionId: string) => {
    if (!selectedPositions.includes(positionId)) {
      setSelectedPositions((prev) => [...prev, positionId]);
      setSearchQuery(""); // Clear search after selection
      setPage(1); // Reset page
    }
  };

  const handleRemovePosition = (positionId: string) => {
    setSelectedPositions((prev) => prev.filter((id) => id !== positionId));
  };

  const handleMigrateAll = () => {
    if (!fromId || !toId) {
      toast.error(t("migration.selectBothPositionTypes"));
      return;
    }

    updatePositionTypeFromTo.mutate(
      { toId, fromId },
      {
        onSuccess: () => {
          toast.success(t("migration.allPositionsMigratedSuccess"));
          onClose();
        },
        onError: (error) => {
          handleError(error);
        },
      }
    );
  };

  const handleMigrateSelected = () => {
    if (!fromId || !toId) {
      toast.error(t("migration.selectBothPositionTypes"));
      return;
    }

    if (selectedPositions.length === 0) {
      toast.error(t("migration.selectAtLeastOnePosition"));
      return;
    }

    migratePositionsByPositions.mutate(
      {
        id: toId,
        data: { positionIds: selectedPositions },
      },
      {
        onSuccess: () => {
          toast.success(
            t("migration.selectedPositionsMigratedSuccess", { count: selectedPositions.length })
          );
          onClose();
        },
        onError: (error) => {
          handleError(error);
        },
      }
    );
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white dark:bg-gray-800 dark:border dark:border-gray-700 rounded-lg shadow-lg w-[700px] max-h-[80vh] overflow-y-auto p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">{t("migration.title")}</h2>
          <button
            type="button"
            onClick={onClose}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* From / To Selection with Swap */}
        {combinedOptions.length > 0 && (
          <div className="mb-4 flex items-end gap-2">
            <div className="flex-1">
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">{t("migration.fromPositionType")}</Label>
              <Select value={fromId} onValueChange={setFromId}>
                <SelectTrigger className="w-full mt-1">
                  <SelectValue placeholder={t("migration.selectSourcePositionType")} />
                </SelectTrigger>
                <SelectContent>
                  {combinedOptions
                    .filter((opt) => opt.value !== toId)
                    .map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>

            <button
              type="button"
              onClick={handleSwap}
              disabled={!fromId && !toId}
              title={t("migration.swap") || "Swap"}
              aria-label={t("migration.swap") || "Swap from and to"}
              className="mb-0.5 p-2 rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ArrowLeftRight className="h-4 w-4 text-gray-600 dark:text-gray-300" />
            </button>

            <div className="flex-1">
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">{t("migration.toPositionType")}</Label>
              <Select value={toId} onValueChange={setToId}>
                <SelectTrigger className="w-full mt-1">
                  <SelectValue placeholder={t("migration.selectTargetPositionType")} />
                </SelectTrigger>
                <SelectContent>
                  {combinedOptions
                    .filter((opt) => opt.value !== fromId)
                    .map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        )}

        {/* Display selected from/to */}
        {fromId && toId && (
          <p className="mb-4 p-3 bg-primary-50 dark:bg-primary-950/30 rounded border border-primary-200 dark:border-primary-800">
            <span className="text-sm text-gray-600 dark:text-gray-300">{t("migration.migrationPath")}:</span>
            <br />
            <strong className="text-primary-700 dark:text-primary-400">{fromName}</strong>
            <span className="mx-2">→</span>
            <strong className="text-primary-700 dark:text-primary-400">{toName}</strong>
          </p>
        )}

        {/* Option 1: Migrate all */}
        <div className="mb-4">
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <button
                className="w-full bg-primary-600 text-white px-4 py-2 rounded hover:bg-primary-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={updatePositionTypeFromTo.isPending || !fromId || !toId}
              >
                {t("migration.migrateAllPositions")}
              </button>
            </AlertDialogTrigger>

            <AlertDialogContent className="bg-white dark:bg-gray-800 dark:border-gray-700">
              <AlertDialogHeader>
                <AlertDialogTitle className="text-gray-900 dark:text-white">{t("migration.confirmMigration")}</AlertDialogTitle>
                <AlertDialogDescription className="text-gray-600 dark:text-gray-300">
                  {t("migration.migrateAllDescription", { fromName, toName })}
                </AlertDialogDescription>
              </AlertDialogHeader>

              <AlertDialogFooter>
                <AlertDialogCancel className="bg-white dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600">{t("common.Cancel")}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleMigrateAll}
                  className="bg-primary-600 hover:bg-primary-700 text-white"
                >
                  {t("migration.yesMigrateAll")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>

        {/* Option 2: Migrate selected */}
        <div>
          <Label className="mb-2 font-medium text-gray-700 dark:text-gray-300">{t("migration.migrateSelectedPositions")}</Label>
          
          {/* Selected Positions Display */}
          {selectedPositions.length > 0 && (
            <div className="flex flex-wrap gap-2 mb-3 p-2 border rounded bg-gray-50 dark:bg-gray-900 dark:border-gray-700">
              {selectedPositions.map((posId) => {
                const position = positions.find((p) => p.id === posId);
                return (
                  <Badge
                    key={posId}
                    variant="secondary"
                    className="flex items-center gap-1 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                  >
                    {position?.name || posId}
                    <X
                      className="h-3 w-3 cursor-pointer hover:text-red-600"
                      onClick={() => handleRemovePosition(posId)}
                    />
                  </Badge>
                );
              })}
            </div>
          )}

          {/* Position Select Dropdown with Search */}
          <Select onValueChange={handleSelectPosition}>
            <SelectTrigger>
              <SelectValue placeholder={t("migration.selectPositionsToMigrate")} />
            </SelectTrigger>
            <SelectContent
              style={{ maxHeight: "300px", overflowY: "auto" }}
              onScroll={handleScroll}
            >
              {/* Search Input inside Dropdown */}
              <div className="sticky top-0 z-10 bg-background p-2 border-b">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    type="text"
                    placeholder={t("migration.searchPositions")}
                    value={searchQuery}
                    onChange={(e) => {
                      e.stopPropagation();
                      setSearchQuery(e.target.value);
                      setPage(1);
                    }}
                    onClick={(e) => e.stopPropagation()}
                    className="pl-10 h-9 text-sm"
                  />
                </div>
              </div>

              {/* Position List */}
              {filteredPositions.length > 0 ? (
                filteredPositions.slice(0, page * pageSize).map((pos) => (
                  <SelectItem
                    key={pos.id}
                    value={pos.id}
                    disabled={selectedPositions.includes(pos.id)}
                  >
                    <div className="flex items-center justify-between w-full">
                      <span>{pos.name}</span>
                      {selectedPositions.includes(pos.id) && (
                        <span className="text-xs text-primary-600 ml-2">
                          ✓ {t("migration.selected")}
                        </span>
                      )}
                    </div>
                  </SelectItem>
                ))
              ) : (
                <div className="text-center py-4 text-sm text-muted-foreground">
                  {searchQuery
                    ? t("migration.noPositionsFound")
                    : t("migration.noPositionsAvailable")}
                </div>
              )}
            </SelectContent>
          </Select>

          <AlertDialog>
            <AlertDialogTrigger asChild>
              <button
                className="w-full mt-3 bg-primary-600 text-white px-4 py-2 rounded hover:bg-primary-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={
                  migratePositionsByPositions.isPending ||
                  selectedPositions.length === 0 ||
                  !fromId ||
                  !toId
                }
              >
                {t("migration.migrateSelectedButton", { count: selectedPositions.length })}
              </button>
            </AlertDialogTrigger>

            <AlertDialogContent className="bg-white dark:bg-gray-800 dark:border-gray-700">
              <AlertDialogHeader>
                <AlertDialogTitle className="text-gray-900 dark:text-white">{t("migration.confirmSelectedMigration")}</AlertDialogTitle>
                <AlertDialogDescription className="text-gray-600 dark:text-gray-300">
                  {t("migration.migrateSelectedDescription", { count: selectedPositions.length, fromName, toName })}
                </AlertDialogDescription>
              </AlertDialogHeader>

              <AlertDialogFooter>
                <AlertDialogCancel className="bg-white dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600">{t("common.Cancel")}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleMigrateSelected}
                  className="bg-primary-600 hover:bg-primary-700 text-white"
                >
                  {t("common.Confirm")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>


      </div>
    </div>
  );
};

export default PositionTypeMigrationModal;