import { useEffect, useState } from 'react';
import { LoaderCircleIcon } from 'lucide-react';
import { Button } from '@rutatiina/ui/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@rutatiina/ui/components/ui/dialog';
import { Input } from '@rutatiina/ui/components/ui/input';
import { Label } from '@rutatiina/ui/components/ui/label';

/**
 * Asks for a name (a new folder, or renaming a file or folder).
 */
export function NameDialog({
  open,
  title,
  initial = '',
  confirmLabel,
  processing,
  error,
  onSubmit,
  onClose,
}: {
  open: boolean;
  title: string;
  initial?: string;
  confirmLabel: string;
  processing: boolean;
  error?: string;
  onSubmit: (name: string) => void;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial);

  useEffect(() => {
    if (open) setName(initial);
  }, [open, initial]);

  return (
    <Dialog open={open} onOpenChange={(value) => !value && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <form
          className="space-y-2"
          onSubmit={(event) => {
            event.preventDefault();
            if (name.trim()) onSubmit(name.trim());
          }}
        >
          <Label htmlFor="media-name">Name</Label>
          <Input
            id="media-name"
            autoFocus
            value={name}
            onChange={(event) => setName(event.target.value)}
          />
          {error && <p className="text-destructive text-sm">{error}</p>}
          <DialogFooter className="pt-3">
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={processing || !name.trim()}>
              {processing && <LoaderCircleIcon className="animate-spin" />}
              {confirmLabel}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
