import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@shared/schema';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import { X, UserPlus, Users } from 'lucide-react';

interface ShareLabelModalProps {
    label: Label | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    currentUser: any;
}

interface LabelShare {
    userId: string;
    username: string;
    permission: 'read' | 'write' | 'admin';
}

export function ShareLabelModal({ label, open, onOpenChange, currentUser }: ShareLabelModalProps) {
    const { t } = useTranslation();
    const { toast } = useToast();
    const [newUsername, setNewUsername] = useState('');
    const [newPermission, setNewPermission] = useState<'read' | 'write'>('read');

    const { data: shares = [], isLoading } = useQuery<LabelShare[]>({
        queryKey: [`/api/labels/${label?.id}/share`],
        enabled: !!label && open,
    });

    const shareMutation = useMutation({
        mutationFn: (data: { username: string; permission: string }) =>
            apiRequest('POST', `/api/labels/${label?.id}/share`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [`/api/labels/${label?.id}/share`] });
            setNewUsername('');
            toast({ title: t('settings.labels.shareSuccess') });
        },
        onError: (e: Error) => {
            toast({
                title: t('settings.labels.shareFailed'),
                description: e.message,
                variant: 'destructive'
            });
        }
    });

    const unshareMutation = useMutation({
        mutationFn: (userId: string) =>
            apiRequest('DELETE', `/api/labels/${label?.id}/share/${userId}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [`/api/labels/${label?.id}/share`] });
            toast({ title: t('settings.labels.unshareSuccess') });
        },
    });

    const handleShare = (e: React.FormEvent) => {
        e.preventDefault();
        if (!newUsername.trim()) return;
        shareMutation.mutate({ username: newUsername, permission: newPermission });
    };

    if (!label) return null;

    // Only creator can share (enforced by backend, but UI check is good too)
    const isCreator = label.creatorId === currentUser?.id;
    const isSystem = label.creatorId === null;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <Users className="w-5 h-5" />
                        {t('settings.labels.shareLabel')}: {label.name}
                    </DialogTitle>
                    <DialogDescription>
                        {t('settings.labels.shareDescription')}
                    </DialogDescription>
                </DialogHeader>

                {isSystem ? (
                    <div className="p-4 bg-muted rounded-md text-center text-sm text-muted-foreground">
                        {t('settings.labels.systemLabelNoShare')}
                    </div>
                ) : !isCreator ? (
                    <div className="p-4 bg-yellow-500/10 text-yellow-500 border border-yellow-500/20 rounded-md text-center text-sm">
                        {t('settings.labels.onlyOwnerCanShare')}
                        <p className="text-xs text-muted-foreground mt-1">
                            {t('settings.labels.owner')}: {t('common.unknown')}
                        </p>
                    </div>
                ) : (
                    <div className="space-y-6">
                        {/* Add Collaborator Form */}
                        <form onSubmit={handleShare} className="flex gap-2 items-end">
                            <div className="flex-1 space-y-2">
                                <label className="text-sm font-medium">{t('settings.labels.addCollaborator')}</label>
                                <div className="flex gap-2">
                                    <Input
                                        placeholder={t('settings.labels.usernamePlaceholder')}
                                        value={newUsername}
                                        onChange={(e) => setNewUsername(e.target.value)}
                                    />
                                    <Select
                                        value={newPermission}
                                        onValueChange={(v: 'read' | 'write') => setNewPermission(v)}
                                    >
                                        <SelectTrigger className="w-[110px]">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="read">{t('settings.labels.permRead')}</SelectItem>
                                            <SelectItem value="write">{t('settings.labels.permWrite')}</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <Button type="submit" disabled={!newUsername || shareMutation.isPending}>
                                <UserPlus className="w-4 h-4" />
                            </Button>
                        </form>

                        <div className="space-y-3">
                            <h4 className="text-sm font-medium text-muted-foreground">{t('settings.labels.accessList')}</h4>

                            {isLoading ? (
                                <div className="text-sm text-center py-4">{t('common.loading')}</div>
                            ) : shares.length === 0 ? (
                                <div className="text-sm text-center py-4 text-muted-foreground bg-muted/30 rounded-md border border-dashed">
                                    {t('settings.labels.noCollaborators')}
                                </div>
                            ) : (
                                <div className="space-y-2 max-h-[200px] overflow-y-auto">
                                    {shares.map((share) => (
                                        <div key={share.userId} className="flex items-center justify-between p-2 rounded-md bg-muted/50 border">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary">
                                                    {share.username.substring(0, 2).toUpperCase()}
                                                </div>
                                                <div>
                                                    <p className="text-sm font-medium">{share.username}</p>
                                                    <p className="text-xs text-muted-foreground capitalize">{t(`settings.labels.perm${share.permission.charAt(0).toUpperCase() + share.permission.slice(1)}`)}</p>
                                                </div>
                                            </div>
                                            <Button
                                                variant="ghost"
                                                size="sm"
                                                className="h-8 w-8 text-muted-foreground hover:text-destructive"
                                                onClick={() => unshareMutation.mutate(share.userId)}
                                            >
                                                <X className="w-4 h-4" />
                                            </Button>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
