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';
import { parseApiError } from '@/utils/apiErrorHandler';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';

// 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 [validationError, setValidationError] = useState<string | null>(null);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const [lastMutationData, setLastMutationData] = useState<{
    username: string;
    permission: 'read' | 'write' | 'admin';
  } | null>(null);
  const addCollaboratorMutation = useAddCollaborator();
  const toast = useToast();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setValidationError(null);
    setMutationError(null);

    if (!username.trim()) {
      setValidationError('Username is required');
      return;
    }

    // Action 3.4.1.3: Store mutation data for retry
    const mutationData = {
      username: username.trim(),
      permission,
    };
    setLastMutationData(mutationData);

    try {
      await addCollaboratorMutation.mutateAsync({
        playlistId,
        data: {
          user_id: mutationData.username, // Backend expects user_id (username will be resolved server-side)
          permission: mutationData.permission,
        },
      });
      toast.success('Collaborator added successfully');
      setUsername('');
      setPermission('read');
      setMutationError(null);
      setRetryCount(0);
      setLastMutationData(null);
      onAdded?.();
      onClose();
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      setMutationError(new Error(apiError.message));
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (!lastMutationData || retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    try {
      await addCollaboratorMutation.mutateAsync({
        playlistId,
        data: {
          user_id: lastMutationData.username,
          permission: lastMutationData.permission,
        },
      });
      toast.success('Collaborator added successfully');
      setUsername('');
      setPermission('read');
      setMutationError(null);
      setRetryCount(0);
      setLastMutationData(null);
      onAdded?.();
      onClose();
    } catch (error) {
      // Error will be handled by mutation's onError
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Add Collaborator"
      variant="default"
      size="md"
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        {mutationError && (
          <ErrorDisplay
            error={mutationError}
            variant="banner"
            severity="error"
            context={{
              action: 'adding collaborator',
              resource: 'playlist',
              resourceId: playlistId,
            }}
            onRetry={retryCount < 3 ? handleRetry : undefined}
            onDismiss={() => {
              setMutationError(null);
              setRetryCount(0);
              setLastMutationData(null);
            }}
          />
        )}
        {validationError && (
          <ErrorDisplay
            error={validationError}
            variant="inline"
            severity="error"
            size="sm"
            dismissible={false}
          />
        )}
        <div className="space-y-2">
          <Label htmlFor="username">Username</Label>
          <Input
            id="username"
            value={username}
            onChange={(e) => {
              setUsername(e.target.value);
              setValidationError(null);
            }}
            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>
  );
}
