import { useState } from 'react';
import { Dialog } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { useAddCollaborator } from '../hooks/usePlaylist';
import { useToast } from '@/hooks/useToast';
import { UserPlus, Loader2 } from 'lucide-react';

// FE-PAGE-008: Complete Playlist Detail page implementation - Add Collaborator Modal

interface AddCollaboratorModalProps {
  open: boolean;
  onClose: () => void;
  playlistId: string;
  onAdded?: () => void;
}

export function AddCollaboratorModal({
  open,
  onClose,
  playlistId,
  onAdded,
}: AddCollaboratorModalProps) {
  const [username, setUsername] = useState('');
  const [permission, setPermission] = useState<'read' | 'write' | 'admin'>('read');
  const addCollaboratorMutation = useAddCollaborator();
  const toast = useToast();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim()) {
      toast.error('Username is required');
      return;
    }

    try {
      await addCollaboratorMutation.mutateAsync({
        playlistId,
        data: {
          user_id: username.trim(), // Backend expects user_id (username will be resolved server-side)
          permission,
        },
      });
      toast.success('Collaborator added successfully');
      setUsername('');
      setPermission('read');
      onAdded?.();
      onClose();
    } catch (error: any) {
      toast.error(error.message || 'Failed to add collaborator');
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Add Collaborator"
      variant="default"
      size="md"
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="username">Username</Label>
          <Input
            id="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="Enter username"
            required
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="permission">Permission</Label>
          <Select
            value={permission}
            onChange={(value) =>
              setPermission((Array.isArray(value) ? value[0] : value) as 'read' | 'write' | 'admin')
            }
            options={[
              { value: 'read', label: 'Read - Can view playlist' },
              { value: 'write', label: 'Write - Can add/remove tracks' },
              { value: 'admin', label: 'Admin - Can manage collaborators' },
            ]}
          />
        </div>
        <div className="flex justify-end gap-2 pt-4">
          <Button type="button" variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={!username.trim() || addCollaboratorMutation.isPending}
          >
            {addCollaboratorMutation.isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Adding...
              </>
            ) : (
              <>
                <UserPlus className="mr-2 h-4 w-4" />
                Add Collaborator
              </>
            )}
          </Button>
        </div>
      </form>
    </Dialog>
  );
}

