import React, { useState } from "react";
import { cn } from "@/lib/utils";
import { Button } from "./button";
import { Card } from "./card";
import { Input } from "./input";
import { SendHorizontal } from "lucide-react";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export interface LoanApplicantInviteProps {
  /** Called when the user submits a valid email */
  onInvite?: (email: string) => void;
  loading?: boolean;
  className?: string;
}

export function LoanApplicantInvite({
  onInvite,
  loading = false,
  className,
}: LoanApplicantInviteProps) {
  const [email, setEmail] = useState("");
  const isValid = EMAIL_RE.test(email);

  const handleSend = () => {
    if (!isValid) return;
    onInvite?.(email);
    setEmail("");
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") handleSend();
  };

  return (
    <Card className={cn("flex flex-col gap-3 p-4", className)}>
      <p className="text-sm font-medium text-foreground">
        Create Joint Application
      </p>

      <div className="flex">
        <Input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="Co-applicant email"
          className="flex-1 border-r-0 focus-visible:ring-0 focus-visible:ring-offset-0"
          aria-label="Co-applicant email"
        />
        <Button
          onClick={handleSend}
          disabled={!isValid || loading}
          size="icon"
          className="shrink-0"
          aria-label="Send invite"
        >
          <SendHorizontal className="h-4 w-4" />
        </Button>
      </div>

      {email && !isValid && (
        <p className="text-xs text-destructive">Invalid email address</p>
      )}
    </Card>
  );
}
