import { useState, useMemo } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Loader2 } from 'lucide-react';

type BugReportDialogProps = {
  open: boolean;
  capturing: boolean;
  submitting: boolean;
  screenshot: Blob | null;
  onClose: () => void;
  onSubmit: (description: string) => void;
};

export const BugReportDialog = ({
  open,
  capturing,
  submitting,
  screenshot,
  onClose,
  onSubmit,
}: BugReportDialogProps) => {
  const [description, setDescription] = useState('');

  const previewUrl = useMemo(() => (screenshot ? URL.createObjectURL(screenshot) : null), [screenshot]);

  const handleSubmit = () => {
    onSubmit(description);
    setDescription('');
  };

  const canSubmit = description.trim().length > 0 && !capturing && !submitting;

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>Report a Bug</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="overflow-hidden rounded-md border bg-muted">
            {capturing ? (
              <div className="flex h-40 items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : previewUrl ? (
              <img src={previewUrl} alt="Screenshot" className="max-h-48 w-full object-contain" />
            ) : (
              <div className="flex h-40 items-center justify-center text-sm text-muted-foreground">
                No screenshot captured
              </div>
            )}
          </div>

          <Textarea
            placeholder="Describe what went wrong..."
            value={description}
            onChange={(ev) => setDescription(ev.target.value)}
            rows={4}
            autoFocus
          />

          <p className="text-xs text-muted-foreground">
            Console logs, browser info, and recent API errors are collected automatically.
          </p>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={submitting}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} disabled={!canSubmit}>
            {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
            Submit
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
