import { useState, useEffect } from 'react';
import * as React from 'react';
import { Role } from '../types/role';
import { createRole, updateRole } 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 { Checkbox } from '@/components/ui/checkbox';
import { useToast } from '@/hooks/useToast';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

// Textarea component - using standard HTML textarea
const Textarea = React.forwardRef<
  HTMLTextAreaElement,
  React.TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className, ...props }, ref) => {
  return (
    <textarea
      className={cn(
        'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
        className
      )}
      ref={ref}
      {...props}
    />
  );
});
Textarea.displayName = 'Textarea';

interface RoleFormProps {
  role?: Role;
  onClose: () => void;
  onSuccess: () => void;
}

export function RoleForm({ role, onClose, onSuccess }: RoleFormProps) {
  const [name, setName] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [description, setDescription] = useState('');
  const [isActive, setIsActive] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (role) {
      setName(role.name);
      setDisplayName(role.display_name);
      setDescription(role.description || '');
      setIsActive(role.is_active);
    }
  }, [role]);

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

    if (!name.trim() || !displayName.trim()) {
      toast.error('Le nom et le nom d\'affichage sont requis');
      return;
    }

    try {
      setIsSubmitting(true);

      const roleData = {
        name: name.trim(),
        display_name: displayName.trim(),
        description: description.trim() || undefined,
        is_active: isActive,
      };

      if (role) {
        await updateRole(role.id, roleData);
      } else {
        await createRole(roleData);
      }

      onSuccess();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors de la sauvegarde';
      toast.error(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog
      open={true}
      onClose={onClose}
      title={role ? 'Modifier le rôle' : 'Créer un nouveau rôle'}
      size="lg"
      footer={
        <div className="flex justify-end gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={onClose}
            disabled={isSubmitting}
          >
            Annuler
          </Button>
          <Button
            type="submit"
            onClick={handleSubmit}
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                {role ? 'Modification...' : 'Création...'}
              </>
            ) : (
              role ? 'Modifier' : 'Créer'
            )}
          </Button>
        </div>
      }
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="name">Nom du rôle *</Label>
          <Input
            id="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="admin"
            required
            disabled={isSubmitting || role?.is_system}
          />
          <p className="text-xs text-muted-foreground">
            Nom technique unique (ex: admin, editor, viewer)
          </p>
        </div>

        <div className="space-y-2">
          <Label htmlFor="displayName">Nom d'affichage *</Label>
          <Input
            id="displayName"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder="Administrateur"
            required
            disabled={isSubmitting || role?.is_system}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="description">Description</Label>
          <Textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Description du rôle..."
            rows={3}
            disabled={isSubmitting || role?.is_system}
          />
        </div>

        <div className="flex items-center space-x-2">
          <Checkbox
            id="isActive"
            checked={isActive}
            onCheckedChange={(checked) => setIsActive(checked as boolean)}
            disabled={isSubmitting || role?.is_system}
          />
          <Label htmlFor="isActive" className="cursor-pointer">
            Rôle actif
          </Label>
        </div>

        {role?.is_system && (
          <p className="text-sm text-muted-foreground">
            Ce rôle est un rôle système et ne peut pas être modifié.
          </p>
        )}
      </form>
    </Dialog>
  );
}

