"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { inviteStudentToPortal } from "./invite-actions";

export function InviteButton({
  applicationId,
  alreadyInvited,
}: {
  applicationId: string;
  alreadyInvited: boolean;
}) {
  const [isPending, startTransition] = useTransition();
  const [result, setResult] = useState<{
    email: string;
    tempPassword?: string;
    emailSent?: boolean;
  } | null>(null);

  if (alreadyInvited) {
    return (
      <Badge className="bg-green-100 text-green-800" aria-disabled>
        Portal access active
      </Badge>
    );
  }

  function handleInvite() {
    startTransition(async () => {
      const res = await inviteStudentToPortal(applicationId);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      if (res.ok && res.email) {
        setResult({
          email: res.email,
          tempPassword: res.tempPassword,
          emailSent: res.emailSent,
        });
        toast.success(
          res.emailSent
            ? "Invite email sent to student"
            : "Student invited — share credentials manually",
        );
      }
    });
  }

  return (
    <>
      <Button
        onClick={handleInvite}
        disabled={isPending}
        className="bg-brand-blue text-white hover:bg-brand-blue/90"
      >
        {isPending ? "Inviting…" : "Invite to Portal"}
      </Button>

      <Dialog
        open={!!result}
        onOpenChange={(open) => {
          if (!open) setResult(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Portal access created</DialogTitle>
            <DialogDescription>
              {result?.emailSent
                ? "An email was sent with a link to set a password and complete the student profile."
                : "Resend is not configured. Share these credentials securely with the student."}
            </DialogDescription>
          </DialogHeader>

          {result && (
            <div className="space-y-3 rounded-md border bg-muted/40 p-4 text-sm">
              <div className="flex items-center justify-between gap-4">
                <span className="text-muted-foreground">Email</span>
                <span className="font-mono font-medium">{result.email}</span>
              </div>
              {result.tempPassword ? (
                <div className="flex items-center justify-between gap-4">
                  <span className="text-muted-foreground">Temporary password</span>
                  <span className="font-mono font-medium text-brand-orange">
                    {result.tempPassword}
                  </span>
                </div>
              ) : null}
            </div>
          )}

          <DialogFooter>
            {result?.tempPassword ? (
              <Button
                variant="outline"
                onClick={() => {
                  if (result?.tempPassword) {
                    navigator.clipboard
                      ?.writeText(
                        `Email: ${result.email}\nTemporary password: ${result.tempPassword}`,
                      )
                      .then(
                        () => toast.success("Credentials copied"),
                        () => toast.error("Could not copy"),
                      );
                  }
                }}
              >
                Copy
              </Button>
            ) : null}
            <Button onClick={() => setResult(null)}>Done</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
