import { Button } from "@xtablo/ui/components/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@xtablo/ui/components/dialog";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { Loader2Icon, UserPlus } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useInviteOrganizationUser } from "../hooks/organization";

const isEmailValid = (email: string) => /\S+@\S+\.\S+/.test(email.trim());

export function InviteOrganizationModal({
  isOpen,
  onOpenChange,
}: {
  isOpen: boolean;
  onOpenChange: (nextOpen: boolean) => void;
}) {
  const { t } = useTranslation(["settings", "common"]);
  const { mutate: inviteOrganizationUser, isPending } = useInviteOrganizationUser();
  const [inviteEmail, setInviteEmail] = useState("");

  const close = () => {
    setInviteEmail("");
    onOpenChange(false);
  };

  const submit = () => {
    const email = inviteEmail.trim();
    if (!isEmailValid(email)) {
      return;
    }

    inviteOrganizationUser(email, {
      onSuccess: () => {
        close();
      },
    });
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="w-5 h-5" />
            {t("settings:teamInvite.title")}
          </DialogTitle>
          <DialogDescription>{t("settings:teamInvite.description")}</DialogDescription>
        </DialogHeader>

        <div className="space-y-2 py-2">
          <Label htmlFor="inviteOrganizationEmail">{t("settings:teamInvite.emailLabel")}</Label>
          <Input
            id="inviteOrganizationEmail"
            type="email"
            value={inviteEmail}
            onChange={(e) => setInviteEmail(e.target.value)}
            placeholder={t("settings:teamInvite.emailPlaceholder")}
          />
          <p className="text-xs text-muted-foreground">{t("settings:teamInvite.hint")}</p>
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button variant="outline" onClick={close} disabled={isPending}>
            {t("common:buttons.cancel")}
          </Button>
          <Button onClick={submit} disabled={isPending || !isEmailValid(inviteEmail)}>
            {isPending ? (
              <>
                <Loader2Icon className="w-4 h-4 mr-1 animate-spin" />
                {t("settings:teamInvite.inviting")}
              </>
            ) : (
              t("settings:teamInvite.invite")
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
