import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { User } from "@shared/schema";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Loader2, Share2, Search, Users } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useTranslation } from "react-i18next";

interface ShareAccessModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

export function ShareAccessModal({ open, onOpenChange }: ShareAccessModalProps) {
    const { toast } = useToast();
    const { t } = useTranslation();
    const [searchQuery, setSearchQuery] = useState("");
    const [debouncedQuery, setDebouncedQuery] = useState("");

    const { data: users, isLoading } = useQuery<Pick<User, "id" | "username">[]>({
        queryKey: ["/api/users/search", debouncedQuery],
        queryFn: async () => {
            if (debouncedQuery.length < 2) return [];
            const res = await fetch(`/api/users/search?q=${encodeURIComponent(debouncedQuery)}`);
            if (!res.ok) throw new Error("Failed to search users");
            return res.json();
        },
        enabled: debouncedQuery.length >= 2,
    });

    const shareMutation = useMutation({
        mutationFn: async (targetUserId: string) => {
            const res = await apiRequest("POST", `/api/users/share-all`, { targetUserId });
            return res.json();
        },
        onSuccess: () => {
            toast({ title: t('share.successAccess'), description: t('share.successAccessDesc') });
            onOpenChange(false);
        },
        onError: () => {
            toast({ title: t('share.errorAccess'), variant: "destructive" });
        },
    });

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="w-[95vw] max-w-lg sm:max-w-md p-4 sm:p-6">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <Users className="w-5 h-5" />
                        {t('share.allTasksTitle')}
                    </DialogTitle>
                    <DialogDescription>
                        {t('share.allTasksDesc')}
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-4 py-4">
                    <div className="relative">
                        <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                        <Input
                            placeholder={t('share.searchPlaceholder')}
                            className="pl-9"
                            value={searchQuery}
                            onChange={(e) => {
                                setSearchQuery(e.target.value);
                                // Simple manual debounce simulation for UI response, real query uses effect or direct set
                                // For consistency with ShareTaskModal, we'll just set it
                            }}
                            onKeyUp={() => setDebouncedQuery(searchQuery)}
                        />
                    </div>

                    <ScrollArea className="h-[200px] rounded-md border p-2">
                        {isLoading && debouncedQuery.length >= 2 ? (
                            <div className="flex justify-center p-4">
                                <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
                            </div>
                        ) : users && users.length > 0 ? (
                            <div className="space-y-2">
                                {users.map((user) => (
                                    <div key={user.id} className="flex items-center justify-between p-2 hover:bg-muted/50 rounded-lg transition-colors">
                                        <div className="flex items-center gap-3">
                                            <Avatar className="h-8 w-8">
                                                <AvatarFallback>{user.username.substring(0, 2).toUpperCase()}</AvatarFallback>
                                            </Avatar>
                                            <span className="font-medium">{user.username}</span>
                                        </div>
                                        <Button
                                            size="sm"
                                            onClick={() => shareMutation.mutate(user.id)}
                                            disabled={shareMutation.isPending}
                                        >
                                            {shareMutation.isPending ? (
                                                <Loader2 className="w-4 h-4 animate-spin" />
                                            ) : (
                                                <Share2 className="w-4 h-4 mr-2" />
                                            )}
                                            {t('share.grantAccess')}
                                        </Button>
                                    </div>
                                ))}
                            </div>
                        ) : debouncedQuery.length >= 2 ? (
                            <div className="text-center p-4 text-sm text-muted-foreground">
                                {t('share.noUsers')}
                            </div>
                        ) : (
                            <div className="text-center p-4 text-sm text-muted-foreground">
                                {t('share.typeToSearch')}
                            </div>
                        )}
                    </ScrollArea>
                </div>
            </DialogContent>
        </Dialog>
    );
}
