import { useState } from "react";
import { Input } from "@/shared/common/ui/input";
import { Search } from "lucide-react";
import { OrganizationList } from "./lists/OrganizationList";
import { UnitList } from "./lists/UnitList";
import { DepartmentList } from "./lists/DepartmentList";
import { PositionServicesList } from "./lists/PositionServicesList";
import { useOrganizationsData } from "@/user-management/userManagement/hooks/useOrganizationsData";
import { useUnitsData } from "@/user-management/userManagement/hooks/useUnitsData";
import { useDepartmentsData } from "@/user-management/userManagement/hooks/useDepartmentsData";
import { useSelectionHandlers } from "@/user-management/userManagement/handlers/useSelectionHandlers";
import { Breadcrumb } from "@/user-management/userManagement/components/Breadcrumb";
import { useAuth } from "@/shared/context/AuthContext";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";
import { AssignServiceDialog } from "./dialogs/AssignServiceDialog";

const ServiceAssignmentPage = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [unitSearchQuery, setUnitSearchQuery] = useState("");
  const [departmentSearchQuery, setDepartmentSearchQuery] = useState("");
  const { user } = useAuth();
  const localizedName = useLocalizedName();

  // Dialog state for service assignment
  const [isAssignDialogOpen, setIsAssignDialogOpen] = useState(false);
  const [selectedPositionId, setSelectedPositionId] = useState<string>("");
  const [selectedPositionName, setSelectedPositionName] = useState<string>("");

  // Get organization ID from user
  const organizationId =
    user?.employee && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  // Hooks for data loading
  const { organizations, isLoading: orgsLoading } = useOrganizationsData({
    currentOrgId: organizationId,
  });

  const {
    selectedOrgId,
    selectedUnitId,
    selectedDepartmentId,
    breadcrumb,
    handleSelectOrganization,
    handleSelectUnit,
    handleSelectDepartment,
  } = useSelectionHandlers(organizations, localizedName);

  const [take] = useState(100);
  const [skip] = useState(0);

  const {
    units,
    isLoading: unitsLoading,
    setUnits,
  } = useUnitsData(selectedOrgId, { take, skip });

  const {
    departments,
    isLoading: deptsLoading,
    setDepartments,
    positions,
  } = useDepartmentsData(selectedUnitId);

  // Handle assign service action
  const handleAssignService = (positionId: string, positionName: string) => {
    setSelectedPositionId(positionId);
    setSelectedPositionName(positionName);
    setIsAssignDialogOpen(true);
  };

  return (
    <div className="h-full flex flex-col">
      <div className="p-4 border-b">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-xl font-semibold text-gray-800">
            {t("organization.serviceAssignment", "Service Assignment")}
          </h1>
        </div>

        <div className="flex gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
            <Input
              placeholder="Search organizations, units, departments..."
              className="pl-8"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>

        <div className="mt-4">
          <Breadcrumb breadcrumb={breadcrumb} hasTeamMembers={false} />
        </div>
      </div>

      {/* Position Services List */}
      <div className="px-4 pb-4">
        <PositionServicesList positionId={selectedDepartmentId} />
      </div>

      {/* Desktop view - grid layout */}
      <div className="flex-1 p-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <div className="border rounded-md p-3 bg-white shadow-sm">
          <h3 className="font-medium text-gray-700 mb-3 border-b pb-2">
            {t("organization.organizations")}
          </h3>
          <OrganizationList
            selectedOrgId={selectedOrgId}
            organizations={organizations}
            isLoading={orgsLoading}
            searchQuery={searchQuery}
            onSelectOrganization={(id: string) => {
              setUnits([]);
              setDepartments([]);
              handleSelectOrganization(id);
            }}
          />
        </div>

        <div className="border rounded-md p-3 bg-white shadow-sm">
          <h3 className="font-medium text-gray-700 mb-3 border-b pb-2">
            {t("contentManagement.Units")}
          </h3>
          <div className="mb-3">
            <div className="relative">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                placeholder={t("search.searchUnits", "Search units...")}
                className="pl-8 text-sm"
                value={unitSearchQuery}
                onChange={(e) => setUnitSearchQuery(e.target.value)}
              />
            </div>
          </div>
          <UnitList
            organizationId={selectedOrgId}
            selectedUnitId={selectedUnitId}
            onSelectUnit={(id: string) => {
              setDepartments([]);
              handleSelectUnit(id, units);
            }}
            units={units}
            isLoading={unitsLoading}
            searchQuery={unitSearchQuery}
          />
        </div>

        <div className="border rounded-md p-3 bg-white shadow-sm">
          <h3 className="font-medium text-gray-700 mb-3 border-b pb-2">
            {t("userIncoming.Departments")}
          </h3>
          <div className="mb-3">
            <div className="relative">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                placeholder={t(
                  "search.searchDepartments",
                  "Search departments..."
                )}
                className="pl-8 text-sm"
                value={departmentSearchQuery}
                onChange={(e) => setDepartmentSearchQuery(e.target.value)}
              />
            </div>
          </div>
          <DepartmentList
            unitId={selectedUnitId}
            selectedDepartmentId={selectedDepartmentId}
            onSelectDepartment={(id: string) => {
              handleSelectDepartment(id, departments);
            }}
            departments={departments}
            positions={positions}
            isLoading={deptsLoading}
            searchQuery={departmentSearchQuery}
            onAssignService={handleAssignService}
          />
        </div>
      </div>

      {/* Assign Service Dialog */}
      <AssignServiceDialog
        isOpen={isAssignDialogOpen}
        onClose={() => {
          setIsAssignDialogOpen(false);
          setSelectedPositionId("");
          setSelectedPositionName("");
        }}
        positionId={selectedPositionId}
        positionName={selectedPositionName}
        organizationId={selectedOrgId}
      />
    </div>
  );
};

export default ServiceAssignmentPage;
