import React, { useMemo } from "react";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Search, UserCircle, AlertCircle, X } from "lucide-react";
import {
  useOrganizationEmployeeSearch,
  OrganizationEmployee,
} from "../../hooks/useOrganizationEmployeeSearch";
import { t } from "i18next";
import i18n from "@/i18n";
import { toast } from "sonner";
import { TeamMembers } from "../TeamMembers";
import { TeamMemberDto } from "../../dto/teamMember/teamMember";
import { resendVerificationCode } from "@/shared/services/authService";

interface OrganizationEmployeeSearchProps {
  organizationId?: string;
  isOpen: boolean;
  onClose: () => void;
}

// Convert EmployeeWithUnitDto to TeamMemberDto format
const convertToTeamMember = (
  employee: OrganizationEmployee,
  organizationId: string
): TeamMemberDto => {
  const primaryPosition = employee.employeePositions?.[0];
  const userName = employee.user?.name ?? { en: "", am: "" };
  const positionName = primaryPosition?.position?.name ?? { en: "", am: "" };

  return {
    organizationId,
    status: "Active",
    id: employee.id,
    isCurrent: true,
    name: primaryPosition
      ? `${userName.en || userName.am} - ${positionName.en || positionName.am}`
      : (userName.en || userName.am || null),
    employeePositions: employee.employeePositions || [],
    user: {
      id: employee.user.id,
      name: userName,
      username: employee.user.email.split("@")[0],
      email: employee.user.email,
      userType: "employee",
      sharepointId: null,
      status: "pending",
      phoneNumber: "",
      hasSetPassword: false,
    },
  };
};

export const OrganizationEmployeeSearch: React.FC<
  OrganizationEmployeeSearchProps
> = ({ organizationId, isOpen, onClose }) => {
  const {
    filteredEmployees,
    totalCount,
    filteredCount,
    searchQuery,
    setSearchQuery,
    isLoading,
    error,
  } = useOrganizationEmployeeSearch(organizationId);
  // Convert filtered employees to TeamMemberDto format
  const convertedEmployees = useMemo(() => {
    if (!organizationId) return [];
    return filteredEmployees.map((employee) =>
      convertToTeamMember(employee, organizationId)
    );
  }, [filteredEmployees, organizationId]);

  // Action handlers for TeamMembers
  const handleInviteEmployee = async (employee: TeamMemberDto) => {
    const lang = i18n.language;
    try {
      // A member who already set a password is being sent a fresh set-password
      // code — that is a reset, not an invite. Keyed off hasSetPassword (the
      // same fact the menu label uses) rather than the looser `status` field,
      // so the wording cannot disagree with the menu the operator clicked.
      const isReset = employee.user.hasSetPassword;

      toast.loading(
        isReset
          ? t("search.sendingPasswordReset")
          : t("search.resendingVerification"),
      );

      await resendVerificationCode({
        email: employee.user.email,
        phoneNumber: employee.user.phoneNumber,
      });

      // Show success notification with more specific message for resend
      const userName =
        lang === "en" ? employee.user.name.en : employee.user.name.am;

      if (isReset) {
        toast.success(t("search.passwordResetSent"), {
          description: t("search.passwordResetSentTo", { name: userName }),
          duration: 4000,
        });
      } else {
        toast.success(t("search.verificationCodeResent"), {
          description: t("search.verificationCodeSentTo", { name: userName }),
          duration: 4000,
        });
      }

      // Refresh the employee list to update statuses
      // Note: We could add a refetch function here if needed
    } catch (error: unknown) {
      // Show error notification
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error";
      const failureMessage =
        employee.user.status === "pending"
          ? t("search.failedToResend")
          : t("search.failedToSendInvitation");

      toast.error("Error", {
        description: `${failureMessage}: ${errorMessage}`,
        duration: 4000,
      });
    }
  };

  const handleDeleteEmployee = (
    departmentId: string,
    departmentName: string,
    teamMemberId: string,
    teamMemberName: string
  ) => {
    // Simple confirmation for remove action
    const confirmed = window.confirm(
      t("search.confirmRemoveEmployee", { name: teamMemberName })
    );

    if (confirmed) {

      toast.info(t("search.removeFunctionalityNotImplemented"));
    }
  };

  const renderContent = () => {
    if (isLoading) {
      return (
        <div className="flex justify-center py-12">
          <div className="flex flex-col items-center">
            <div className="w-8 h-8 border-4 border-t-primary-500 border-primary-200 rounded-full animate-spin mb-2"></div>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t("search.searchingEmployees")}
            </p>
          </div>
        </div>
      );
    }

    if (error) {
      return (
        <div className="text-center py-12 text-red-500 dark:text-red-400">
          <AlertCircle className="h-12 w-12 mx-auto mb-2" />
          <p className="text-sm font-medium">
            {t("search.errorLoadingEmployees")}
          </p>
          <p className="text-xs mt-1 dark:text-gray-400">
            {error instanceof Error ? error.message : "Unknown error"}
          </p>
        </div>
      );
    }

    if (filteredEmployees.length === 0 && searchQuery.trim()) {
      return (
        <div className="text-center py-12 text-gray-500 dark:text-gray-400">
          <Search className="h-12 w-12 mx-auto mb-2 text-gray-300 dark:text-gray-600" />
          <p className="text-sm font-medium">{t("search.noEmployeesFound")}</p>
          <p className="text-xs mt-1 text-gray-400 dark:text-gray-500">
            {t("search.tryDifferentKeywords")}
          </p>
        </div>
      );
    }

    if (filteredEmployees.length === 0) {
      return (
        <div className="text-center py-12 text-gray-500 dark:text-gray-400">
          <UserCircle className="h-12 w-12 mx-auto mb-2 text-gray-300 dark:text-gray-600" />
          <p className="text-sm font-medium">
            {t("search.startTypingToSearch")}
          </p>
          <p className="text-xs mt-1 text-gray-400 dark:text-gray-500">
            {t("search.searchByNameEmailPhone")}
          </p>
        </div>
      );
    }

    // Use TeamMembers component for consistent UI and actions
    return (
      <TeamMembers
        departmentId="" // Not applicable for organization-wide search
        departmentName={t("search.allEmployees")}
        employees={convertedEmployees}
        isLoading={false}
        searchQuery="" // We handle search at this level
        onInviteEmployee={handleInviteEmployee}
        onDeleteEmployee={handleDeleteEmployee}
      />
    );
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden dark:bg-gray-800">
        <DialogHeader className="flex flex-row items-center justify-between">
          <DialogTitle className="flex items-center gap-2 dark:text-white">
            <Search className="h-5 w-5 dark:text-gray-400" />
            {t("search.searchAllEmployees")}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Search Input */}
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400 dark:text-gray-500" />
            <Input
              placeholder={t("search.searchByNameEmailPhonePosition")}
              className="pl-10 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              autoFocus
            />
          </div>

          {/* Results Count */}
          {searchQuery.trim() && (
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {t("search.showingResults", {
                count: filteredCount,
                total: totalCount,
                query: searchQuery,
              })}
            </div>
          )}

          {/* Results */}
          <div className="max-h-96 overflow-y-auto">{renderContent()}</div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
