import React, { useState, useEffect, useContext } from 'react';
import { AuthContext } from '../auth/AuthContext';

const API_BASE_URL = `${import.meta.env.VITE_APP_API_BASE_URL}`;

export default function TenantModal({ open, onClose, tenant, tenants, fetchTenants, apiBaseUrl }) {
  const { auth } = useContext(AuthContext) || { auth: null };

  const [form, setForm] = useState({
    name: tenant?.name || '',
    description: tenant?.description || '',
    parent: tenant?.parent || '',
  });

  const user = auth;
  const accessToken = localStorage.getItem('accessToken');
  const hasPermission = (permission) => user?.user_permissions?.includes(permission);
  const canAddTenants = hasPermission('Create Tenant.createTenant');
  const isSuperAdmin = user?.is_superuser;
  const userTenantId = user?.user_roles_set?.[0]?.tenant_id;

  useEffect(() => {
    setForm({
      name: tenant?.name || '',
      description: tenant?.description || '',
      parent: tenant?.parent || '',
    });
  }, [tenant, open]);

  const handleChange = e => {
    const { name, value } = e.target;
    setForm(f => ({ ...f, [name]: value }));
  };

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

    // Use the apiBaseUrl prop here
    const path = tenant?.id ? `/tenants/${tenant.id}/` : `/tenants/`;
    const url = `${API_BASE_URL}${path}`;
    const method = tenant?.id ? 'PUT' : 'POST';

    try {
      const response = await fetch(url, {
        method: method,
        headers: {

          'Content-Type': 'application/json',
         'Authorization': `Bearer ${accessToken}`,
        },
        // Convert the form data object into a JSON string
        body: JSON.stringify(form),
      });

      // Check for non-2xx status codes
      if (!response.ok) {
        // Attempt to get detailed error from the server response
        const errorData = await response.json().catch(() => ({ message: response.statusText }));
        throw new Error(errorData.detail || errorData.message || 'Failed to save tenant data.');
      }
      onClose();

    } catch (error) {
      console.error("Error saving tenant:", error.message);

      // setIsError(true);
      // setMessage(error.message);
    }
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none">
      <div className="bg-white rounded-lg shadow-lg w-full max-w-md p-6 relative pointer-events-auto">
        <button
          className="absolute top-2 right-2 text-gray-400 hover:text-gray-700"
          onClick={onClose}
          aria-label="Close"
        >
          &times;
        </button>
        <h2 className="text-xl bg-blue-600 text-white p-4 rounded-sm font-bold mb-4">
          {tenant ? "Edit Tenant" : "Create New Tenant"}
        </h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tenant Name<span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="name"
              value={form.name}
              onChange={handleChange}
              className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
            <textarea
              name="description"
              value={form.description}
              onChange={handleChange}
              className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
              rows={2}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Parent Tenant</label>
            <select
              name="parent"
              value={form.parent}
              onChange={handleChange}
              className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
            >
              <option value="">None</option>
              {tenants && tenants.map(t => (
                <option key={t.id} value={t.id}>{t.name}</option>
              ))}
            </select>
          </div>
          <div className="flex justify-end space-x-2 mt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded bg-gray-200 text-gray-700 hover:bg-gray-300"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="px-4 py-2 rounded bg-blue-600 text-white hover:bg-blue-700"
            >
              Save
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}