import { useState } from 'react';
import { Role } from '../types/role';
import { assignRole } from '../services/roleService';
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 { useToast } from '@/hooks/useToast';
import { Loader2 } from 'lucide-react';

interface AssignRoleDialogProps {
  role?: Role;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  userId?: number;
}

export function AssignRoleDialog({ role, open, onClose, onSuccess, userId: propUserId }: AssignRoleDialogProps) {
  const [userId, setUserId] = useState(propUserId?.toString() || '');
  const [roleId, setRoleId] = useState(role?.id.toString() || '');
  const [expiresAt, setExpiresAt] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

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

    const userIdNum = parseInt(userId, 10);
    if (isNaN(userIdNum) || userIdNum <= 0) {
      toast.error('Veuillez entrer un ID utilisateur valide');
      return;
    }

    try {
      setIsSubmitting(true);

      const roleIdNum = parseInt(roleId, 10);
      if (isNaN(roleIdNum) || roleIdNum <= 0) {
        toast.error('Veuillez sélectionner un rôle valide');
        return;
      }

      const request = {
        role_id: roleIdNum,
        expires_at: expiresAt ? new Date(expiresAt).toISOString() : undefined,
      };

      await assignRole(userIdNum, request);
      onSuccess();
      
      // Reset form
      setUserId('');
      setExpiresAt('');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors de l\'assignation';
      toast.error(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!propUserId) {
      setUserId('');
    }
    if (!role) {
      setRoleId('');
    }
    setExpiresAt('');
    onClose();
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      title={role ? `Assigner le rôle: ${role.display_name}` : 'Assigner un rôle'}
      size="md"
      footer={
        <div className="flex justify-end gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={handleClose}
            disabled={isSubmitting}
          >
            Annuler
          </Button>
          <Button
            type="submit"
            onClick={handleSubmit}
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Assignation...
              </>
            ) : (
              'Assigner'
            )}
          </Button>
        </div>
      }
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        {!propUserId && (
          <div className="space-y-2">
            <Label htmlFor="userId">ID de l'utilisateur *</Label>
            <Input
              id="userId"
              type="number"
              value={userId}
              onChange={(e) => setUserId(e.target.value)}
              placeholder="1"
              required
              disabled={isSubmitting}
              min="1"
            />
            <p className="text-xs text-muted-foreground">
              Entrez l'ID numérique de l'utilisateur à qui assigner ce rôle
            </p>
          </div>
        )}

        {!role && (
          <div className="space-y-2">
            <Label htmlFor="roleId">ID du rôle *</Label>
            <Input
              id="roleId"
              type="number"
              value={roleId}
              onChange={(e) => setRoleId(e.target.value)}
              placeholder="1"
              required
              disabled={isSubmitting}
              min="1"
            />
            <p className="text-xs text-muted-foreground">
              Entrez l'ID numérique du rôle à assigner
            </p>
          </div>
        )}

        <div className="space-y-2">
          <Label htmlFor="expiresAt">Date d'expiration (optionnel)</Label>
          <Input
            id="expiresAt"
            type="datetime-local"
            value={expiresAt}
            onChange={(e) => setExpiresAt(e.target.value)}
            disabled={isSubmitting}
          />
          <p className="text-xs text-muted-foreground">
            Laisser vide pour une assignation permanente
          </p>
        </div>
      </form>
    </Dialog>
  );
}

