import React, { useState, useEffect } 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 { Switch } from '@/components/ui/switch';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Copy, RefreshCw, Globe, Lock, ExternalLink, ShieldAlert } from 'lucide-react';
import { v4 as uuidv4 } from 'uuid';

export function FolderShareDialog({ open, onOpenChange, folder, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [isShared, setIsShared] = useState(false);
  const [password, setPassword] = useState('');
  const [shareToken, setShareToken] = useState('');
  
  useEffect(() => {
    if (folder) {
        setIsShared(folder.is_shared || false);
        setPassword(folder.share_password || '');
        setShareToken(folder.share_token || '');
    }
  }, [folder]);

  const handleShareToggle = (checked) => {
      setIsShared(checked);
      if (checked && !shareToken) {
          setShareToken(uuidv4());
      }
      if (checked && !password) {
          generateRandomPassword();
      }
  };

  const generateRandomPassword = () => {
      const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; 
      let pass = "";
      for(let i=0; i<8; i++) {
          pass += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      setPassword(pass);
  };

  const regenerateToken = () => {
      if (window.confirm("Are you sure? This will invalidate any existing links sent to users.")) {
          setShareToken(uuidv4());
      }
  };

  const handleSave = async () => {
    setLoading(true);
    try {
        if (isShared && !password.trim()) {
            throw new Error("An access code is required to enable secure sharing.");
        }

        const updates = {
            is_shared: isShared,
            share_password: isShared ? password : null,
            share_token: isShared ? shareToken : folder.share_token
        };
        
        const { error } = await supabase
            .from('document_categories')
            .update(updates)
            .eq('id', folder.id);

        if (error) throw error;

        toast({ title: "Settings Saved", description: isShared ? "Folder is now publicly accessible via the link." : "Folder sharing disabled." });
        if (onSuccess) onSuccess();
        onOpenChange(false);
    } catch (err) {
        toast({ variant: "destructive", title: "Error", description: err.message });
    } finally {
        setLoading(false);
    }
  };

  const shareLink = shareToken ? `${window.location.origin}/shared/${shareToken}` : '';

  const copyLink = () => {
      navigator.clipboard.writeText(shareLink);
      toast({ title: "Link Copied!", description: "Share link copied to clipboard." });
  };

  const copyPassword = () => {
      navigator.clipboard.writeText(password);
      toast({ title: "Code Copied!", description: "Access code copied to clipboard." });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Globe className="w-5 h-5 text-primary" />
            Share Folder: {folder?.name}
          </DialogTitle>
          <DialogDescription>
            Generate a secure link for external users.
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-6 py-4">
            <div className="flex items-center justify-between space-x-2 bg-muted p-4 rounded-lg border">
                <div className="space-y-0.5">
                    <Label className="text-base font-semibold">Public Sharing</Label>
                    <p className="text-xs text-muted-foreground">
                        {isShared ? 'Enabled - Folder is accessible with link & code' : 'Disabled - Folder is private'}
                    </p>
                </div>
                <Switch checked={isShared} onCheckedChange={handleShareToggle} />
            </div>

            {isShared && (
                <div className="space-y-5 animate-in fade-in slide-in-from-top-2 duration-300">
                    <div className="space-y-2">
                        <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">1. Share Link</Label>
                        <div className="flex space-x-2">
                            <div className="relative flex-1">
                                <Input 
                                    readOnly 
                                    value={shareLink} 
                                    className="bg-muted font-mono text-xs pr-10"
                                />
                                <div className="absolute inset-y-0 right-0 flex items-center pr-2">
                                     <a href={shareLink} target="_blank" rel="noopener noreferrer" className="text-muted-foreground hover:text-primary" title="Open Link">
                                         <ExternalLink className="w-3 h-3" />
                                     </a>
                                </div>
                            </div>
                            <Button size="icon" variant="outline" onClick={copyLink} className="shrink-0">
                                <Copy className="w-4 h-4" />
                            </Button>
                        </div>
                        <div className="flex justify-end">
                            <button onClick={regenerateToken} className="text-[10px] text-muted-foreground hover:text-destructive underline">
                                Regenerate Link
                            </button>
                        </div>
                    </div>

                    <div className="space-y-2">
                         <div className="flex justify-between items-center">
                            <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">2. Access Code</Label>
                            <Button 
                                variant="ghost" 
                                size="sm" 
                                onClick={generateRandomPassword} 
                                className="h-6 text-[10px] text-primary px-2"
                            >
                                <RefreshCw className="w-3 h-3 mr-1" /> New Code
                            </Button>
                        </div>
                        
                        <div className="bg-amber-50 border border-amber-200 rounded-md p-4 relative overflow-hidden">
                            <div className="absolute top-0 right-0 p-2 opacity-10">
                                <ShieldAlert className="w-24 h-24 text-amber-600" />
                            </div>
                            <div className="relative z-10">
                                <div className="flex items-center space-x-2 mb-3">
                                    <Lock className="w-4 h-4 text-amber-600" />
                                    <span className="text-xs text-amber-800 font-bold uppercase tracking-wide">Authentication Required</span>
                                </div>
                                <div className="flex space-x-2 mb-2">
                                    <Input 
                                        value={password} 
                                        onChange={(e) => setPassword(e.target.value)}
                                        placeholder="Enter secure code"
                                        className="font-mono text-xl font-bold tracking-widest text-center bg-background border-amber-300"
                                    />
                                    <Button size="icon" variant="outline" onClick={copyPassword} className="shrink-0 border-amber-300 text-amber-700 hover:bg-amber-100">
                                        <Copy className="w-4 h-4" />
                                    </Button>
                                </div>
                                <p className="text-[11px] text-amber-700/80 leading-relaxed text-center font-medium">
                                    External users <strong>must</strong> enter this code to view files.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSave} disabled={loading}>
            {loading ? 'Saving...' : 'Save Settings'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
