
'use client';
import * as React from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Copy } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface ShareDialogProps {
    isOpen: boolean;
    onOpenChange: (isOpen: boolean) => void;
    itemName: string;
    itemPath: string;
    itemType: 'file' | 'folder';
}

function urlSafeBtoa(str: string): string {
    return btoa(str)
        .replace(/\+/g, '-') // Convert '+' to '-'
        .replace(/\//g, '_') // Convert '/' to '_'
        .replace(/=+$/, ''); // Remove ending '='
}

export function ShareDialog({ isOpen, onOpenChange, itemName, itemPath, itemType }: ShareDialogProps) {
    const [generatedLink, setGeneratedLink] = React.useState<string | null>(null);
    const { toast } = useToast();

    const handleCreateLink = () => {
        try {
            const encodedPath = urlSafeBtoa(itemPath);
            const fullLink = `${window.location.origin}/share/${encodedPath}`;
            setGeneratedLink(fullLink);
        } catch (error) {
            console.error('Error encoding path:', error);
            toast({
                variant: 'destructive',
                title: 'Error Creating Link',
                description: 'Could not create the share link.',
            });
        }
    };
    
    const handleCopyToClipboard = () => {
        if (!generatedLink) return;
        navigator.clipboard.writeText(generatedLink);
        toast({ title: 'Link Copied!', description: 'The share link has been copied to your clipboard.' });
    };

    React.useEffect(() => {
        // Reset state when dialog opens
        if (isOpen) {
            setGeneratedLink(null);
        }
    }, [isOpen]);

    return (
        <Dialog open={isOpen} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Share "{itemName}"</DialogTitle>
                    <DialogDescription>
                        Generate a public link to share this {itemType}.
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-4 py-4">
                    {generatedLink ? (
                        <div className="space-y-2">
                           <Label htmlFor="share-link">Generated Link</Label>
                           <div className="flex items-center gap-2">
                              <Input id="share-link" readOnly value={generatedLink} className="bg-muted" />
                              <Button size="icon" onClick={handleCopyToClipboard}><Copy className="h-4 w-4" /></Button>
                           </div>
                        </div>
                    ) : (
                        <div className="flex justify-center">
                           <Button onClick={handleCreateLink}>
                               Generate Link
                           </Button>
                        </div>
                    )}
                </div>

                <DialogFooter>
                    {generatedLink && (
                         <Button variant="outline" onClick={handleCreateLink}>
                            Regenerate
                         </Button>
                    )}
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
