import { useState, useMemo } from "react";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { Input } from "@/shared/common/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { toast } from "sonner";
import {
  useMovePosition,
  usePositions,
} from "@/user-management/hooks/usePosition";
import { t } from "i18next";
import i18n from "@/i18n";
import { Search, X } from "lucide-react";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";

interface MoveDepartmentFormProps {
  unitId: string;
  organizationId: string;
  departmentId: string;
  onSuccess: (departmentId: string) => void;
  onCancel: () => void;
}

export function MoveDepartmentForm({
  unitId,
  departmentId,
  organizationId,
  onSuccess,
  onCancel,
}: MoveDepartmentFormProps) {
  const { usePositionListByUnitId } = usePositions({
    take: 1000, // Increased to get more departments for search
    skip: 0,
  });
  const [selectedDepartmentId, setSelectedDepartmentId] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [error, setError] = useState("");
  const {
    data: departments,
    isError,
    isLoading,
  } = usePositionListByUnitId(unitId, {
    take: 1000,
    skip: 0,
  });
  const lang = i18n.language;
  const { mutate: moveDept, isPending } = useMovePosition();
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const isApprovalRequiredForPositionChange =
    unitConfigData?.data?.items?.[0]?.isApprovalRequiredForPositionChange ??
    false;

  // Filter departments based on search query
  const filteredDepartments = useMemo(() => {
    if (!departments?.items) return [];

    if (!searchQuery.trim()) return departments.items;

    const query = searchQuery.toLowerCase();
    return departments.items.filter((dept: any) => {
      const nameEn = dept.name?.en?.toLowerCase() || "";
      const nameAm = dept.name?.am?.toLowerCase() || "";
      const description = dept.description?.toLowerCase() || "";

      return (
        nameEn.includes(query) ||
        nameAm.includes(query) ||
        description.includes(query)
      );
    });
  }, [departments?.items, searchQuery]);
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedDepartmentId) {
      setError(t("addRecord.Select Department"));
      toast.error(t("contentManagement.departmentRequired"));
      return;
    }
    moveDept(
      {
        positionId: departmentId,
        newParentId: selectedDepartmentId,
      },
      {
        onSuccess: () => {
          toast.success(
            isApprovalRequiredForPositionChange
              ? t(
                  "contentManagement.positionChangeApprovalRequiredSuccess",
                  "Department moved successfully. Approval is required for position changes.",
                )
              : t("contentManagement.departmentSuccess"),
          );
          onSuccess(selectedDepartmentId);
        },
      }
    );
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="department"> {t("addRecord.Select Department")}</Label>
        <Select
          onValueChange={(value) => {
            setSelectedDepartmentId(value);
            setError("");
          }}
          value={selectedDepartmentId}
        >
          <SelectTrigger>
            <SelectValue placeholder={t("addRecord.Select Department")} />
          </SelectTrigger>
          <SelectContent className="p-0">
            <div className="flex flex-col h-60">
              {/* Fixed search header */}
              <div className="flex-shrink-0 bg-white border-b p-2 z-10">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                  <Input
                    placeholder="Search departments..."
                    value={searchQuery}
                    onChange={(e) => {
                      setSearchQuery(e.target.value);
                      setSelectedDepartmentId(""); // Clear selection when searching
                    }}
                    className="pl-10 pr-10 h-8"
                  />
                  {searchQuery && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0"
                      onClick={() => {
                        setSearchQuery("");
                        setSelectedDepartmentId("");
                      }}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  )}
                </div>
              </div>

              {/* Scrollable content area */}
              <div className="flex-1 overflow-y-auto">
                {isLoading ? (
                  <div className="px-2 py-2">
                    <p className="text-gray-500">
                      {t("contentManagement.loading")}
                    </p>
                  </div>
                ) : filteredDepartments.length === 0 ? (
                  <div className="px-2 py-2">
                    <p className="text-gray-500">
                      {searchQuery
                        ? "No departments found matching your search."
                        : "No departments available."}
                    </p>
                  </div>
                ) : (
                  filteredDepartments.map((dept: any) => (
                    <SelectItem key={dept.id} value={dept.id}>
                      <div className="flex flex-col">
                        <span className="font-medium">
                          {lang === "en" ? dept.name.en : dept.name.am}
                        </span>
                        {dept.description && (
                          <span className="text-xs text-gray-500">
                            {dept.description}
                          </span>
                        )}
                      </div>
                    </SelectItem>
                  ))
                )}
              </div>

              {/* Fixed footer with results count */}
              {searchQuery && filteredDepartments.length > 0 && (
                <div className="flex-shrink-0 bg-gray-50 border-t px-2 py-1">
                  <p className="text-xs text-gray-500">
                    Found {filteredDepartments.length} department(s)
                  </p>
                </div>
              )}
            </div>
          </SelectContent>
        </Select>
        {error && <p className="text-red-500 text-sm">{error}</p>}
      </div>

      <div className="flex justify-end gap-2">
        <Button type="button" variant="outline" onClick={onCancel}>
          {t("common.Cancel")}
        </Button>
        <Button type="submit" disabled={!selectedDepartmentId || isPending}>
          {isPending ? "Moving..." : t("contentManagement.moveDepartement")}
        </Button>
      </div>
    </form>
  );
}
