import { useState, useEffect } from 'react';
import { Dialog } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { assignRole, getUserRoles } from '../services/roleService';
import { useToast } from '@/hooks/useToast';
import { Loader2 } from 'lucide-react';
import type { Role } from '../types/role';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

// FE-PAGE-011: Complete Roles page implementation

interface AssignRoleModalProps {
  userId: string;
  userName?: string;
  availableRoles: Role[];
  open: boolean;
  onClose: () => void;
  onRoleAssigned: () => void;
}

export function AssignRoleModal({
  userId,
  userName,
  availableRoles,
  open,
  onClose,
  onRoleAssigned,
}: AssignRoleModalProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingUserRoles, setIsLoadingUserRoles] = useState(false);
  const [selectedRoleId, setSelectedRoleId] = useState<string>('');
  const [expiresAt, setExpiresAt] = useState<string>('');
  const [userRoles, setUserRoles] = useState<Role[]>([]);
  const { success, error } = useToast();

  useEffect(() => {
    if (open && userId) {
      setIsLoadingUserRoles(true);
      getUserRoles(userId)
        .then((roles) => {
          setUserRoles(roles);
        })
        .catch((err: unknown) => {
          const apiError = parseApiError(err);
          logger.error('Failed to load user roles', {
            error: apiError.message,
            stack: err instanceof Error ? err.stack : undefined,
            userId,
          });
        })
        .finally(() => {
          setIsLoadingUserRoles(false);
        });
    }
  }, [open, userId]);

  const handleSubmit = async () => {
    if (!selectedRoleId) {
      error('Please select a role');
      return;
    }

    setIsLoading(true);

    try {
      await assignRole(userId, {
        role_id: selectedRoleId,
        expires_at: expiresAt || undefined,
      });
      success('Role assigned successfully');
      onClose();
      setSelectedRoleId('');
      setExpiresAt('');
      onRoleAssigned();
      setExpiresAt('');
      onRoleAssigned();
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      error(apiError.message);
    } finally {
      setIsLoading(false);
    }
  };

  // Filter out roles that user already has
  const availableRolesToAssign = availableRoles.filter(
    (role) => !userRoles.some((ur) => ur.id === role.id),
  );

  const selectOptions = availableRolesToAssign.map((role) => ({
    value: role.id,
    label: `${role.display_name} (${role.name})`,
  }));

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title={`Assign Role${userName ? ` to ${userName}` : ''}`}
      onConfirm={handleSubmit}
      confirmLabel={isLoading ? 'Assigning...' : 'Assign Role'}
      cancelLabel="Cancel"
    >
      {isLoadingUserRoles ? (
        <div className="flex justify-center py-8">
          <Loader2 className="h-8 w-8 animate-spin" />
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="role-select">Role *</Label>
            {availableRolesToAssign.length === 0 ? (
              <div className="p-2 text-sm text-muted-foreground border rounded">
                No available roles to assign
              </div>
            ) : (
              <Select
                options={selectOptions}
                value={selectedRoleId}
                onChange={(value) =>
                  setSelectedRoleId(Array.isArray(value) ? value[0] : value)
                }
                placeholder="Select a role"
              />
            )}
          </div>
          <div>
            <Label htmlFor="expires-at">Expires At (optional)</Label>
            <Input
              id="expires-at"
              type="datetime-local"
              value={expiresAt}
              onChange={(e) => setExpiresAt(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Leave empty for permanent assignment
            </p>
          </div>
          {userRoles.length > 0 && (
            <div>
              <Label>Current Roles</Label>
              <div className="mt-2 space-y-1">
                {userRoles.map((role) => (
                  <div key={role.id} className="text-sm text-muted-foreground">
                    • {role.display_name}
                  </div>
                ))}
              </div>
            </div>
          )}
        </form>
      )}
    </Dialog>
  );
}
