"use client";

import { useState } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { updateUserEmail } from "@/lib/actions/admin";

export function EditUserEmailDialog({
  userId,
  currentEmail,
  open,
  onOpenChange,
  onSaved,
}: {
  userId: string;
  currentEmail: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSaved: (email: string) => void;
}) {
  const [email, setEmail] = useState(currentEmail);
  const [error, setError] = useState<string | undefined>();
  const [pending, setPending] = useState(false);

  function handleOpenChange(next: boolean) {
    if (next) {
      setEmail(currentEmail);
      setError(undefined);
    }
    onOpenChange(next);
  }

  async function handleSave() {
    const trimmed = email.trim();
    if (!trimmed) return;
    setPending(true);
    setError(undefined);
    const result = await updateUserEmail(userId, trimmed);
    setPending(false);
    if (result?.error) {
      setError(result.error);
      return;
    }
    onSaved(trimmed);
    onOpenChange(false);
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Edit email</DialogTitle>
        </DialogHeader>
        <div className="space-y-2">
          <Label htmlFor={`edit-email-${userId}`}>Email</Label>
          <Input
            id={`edit-email-${userId}`}
            type="email"
            value={email}
            autoFocus
            onChange={(e) => setEmail(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSave()}
          />
          {error && <p className="text-sm text-destructive">{error}</p>}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={pending || !email.trim()}>
            {pending ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
