import { useState, useEffect } from 'react';
import { Dialog } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { updateRole, getRole } from '../services/roleService';
import { useToast } from '@/hooks/useToast';
import { Loader2 } from 'lucide-react';
import type { Role } from '../types/role';
import { parseApiError } from '@/utils/apiErrorHandler';

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

interface EditRoleModalProps {
  role: Role;
  open: boolean;
  onClose: () => void;
  onRoleUpdated: () => void;
}

export function EditRoleModal({
  role,
  open,
  onClose,
  onRoleUpdated,
}: EditRoleModalProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingRole, setIsLoadingRole] = useState(false);
  const [formData, setFormData] = useState({
    name: role.name,
    display_name: role.display_name,
    description: role.description,
    is_active: role.is_active,
  });
  const { success, error } = useToast();

  useEffect(() => {
    if (open && role.id) {
      setIsLoadingRole(true);
      getRole(role.id)
        .then((loadedRole) => {
          setFormData({
            name: loadedRole.name,
            display_name: loadedRole.display_name,
            description: loadedRole.description,
            is_active: loadedRole.is_active,
          });
        })
        .catch((err: unknown) => {
          const apiError = parseApiError(err);
          error(apiError.message);
        })
        .finally(() => {
          setIsLoadingRole(false);
        });
    }
  }, [open, role.id, error]);

  const handleSubmit = async () => {
    setIsLoading(true);

    try {
      await updateRole(role.id, formData);
      success('Role updated successfully');
      onClose();
      onRoleUpdated();
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      error(apiError.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Edit Role"
      onConfirm={handleSubmit}
      confirmLabel={isLoading ? 'Updating...' : 'Update Role'}
      cancelLabel="Cancel"
    >
      {isLoadingRole ? (
        <div className="flex justify-center py-8">
          <Loader2 className="h-8 w-8 animate-spin" />
        </div>
      ) : (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            handleSubmit();
          }}
          className="space-y-4"
        >
          <div>
            <Label htmlFor="edit-name">Name *</Label>
            <Input
              id="edit-name"
              value={formData.name}
              onChange={(e) =>
                setFormData({ ...formData, name: e.target.value })
              }
              required
              disabled={role.is_system}
            />
            {role.is_system && (
              <p className="text-xs text-muted-foreground mt-1">
                System roles cannot be renamed
              </p>
            )}
          </div>
          <div>
            <Label htmlFor="edit-display_name">Display Name *</Label>
            <Input
              id="edit-display_name"
              value={formData.display_name}
              onChange={(e) =>
                setFormData({ ...formData, display_name: e.target.value })
              }
              required
            />
          </div>
          <div>
            <Label htmlFor="edit-description">Description</Label>
            <Textarea
              id="edit-description"
              value={formData.description}
              onChange={(e) =>
                setFormData({ ...formData, description: e.target.value })
              }
              rows={3}
            />
          </div>
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="edit-is_active"
              checked={formData.is_active}
              onChange={(e) =>
                setFormData({ ...formData, is_active: e.target.checked })
              }
              className="rounded"
              disabled={role.is_system}
            />
            <Label htmlFor="edit-is_active">Active</Label>
            {role.is_system && (
              <p className="text-xs text-muted-foreground ml-2">
                System roles are always active
              </p>
            )}
          </div>
        </form>
      )}
    </Dialog>
  );
}
