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

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

// ✅ Confirmation Modal (inline, no black background)
function ConfirmDeleteModal({ open, onClose, onConfirm }) {
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* ✅ Just blur the page content, no dark background */}
      <div className="absolute inset-0 backdrop-blur-sm"></div>

      {/* Modal box */}
      <div className="relative bg-white rounded-xl shadow-lg p-6 max-w-sm w-full z-10 border border-gray-200">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Confirm Delete</h2>
        <p className="text-sm text-gray-600 mb-6">
          Are you sure you want to delete this tenant?
        </p>
        <div className="flex justify-end gap-3">
          <button
            className="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300 text-gray-800"
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            className="px-4 py-2 rounded bg-red-600 hover:bg-red-700 text-white"
            onClick={onConfirm}
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  );
}


export default function Tenants() {
  const [tenants, setTenants] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingTenant, setEditingTenant] = useState(null);

  const [tenantName, setTenantName] = useState('');
  const [tenantDescription, setTenantDescription] = useState('');
  const [parentTenantId, setParentTenantId] = useState('');

  const { auth } = useContext(AuthContext) || { auth: null };
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [message, setMessage] = useState(null);
  const [isError, setIsError] = useState(false);

  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;

  const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
  const [tenantToDelete, setTenantToDelete] = useState(null);

  useEffect(() => {
    const fetchTenants = async () => {
      if (!accessToken || !canAddTenants) {
        setIsLoading(false);
        return;
      }
      if (!isSuperAdmin && !userTenantId) {
        setIsLoading(false);
        return;
      }

      const headers = { Authorization: `Bearer ${accessToken}` };

      try {
        const url = isSuperAdmin
          ? `${API_BASE_URL}/tenants/`
          : `${API_BASE_URL}/tenants/${userTenantId}/with_children/`;
        const response = await fetch(url, { headers });
        if (!response.ok) throw new Error('Failed to fetch tenant data.');
        const tenantsData = await response.json();
        setTenants(tenantsData);
      } catch (err) {
        setMessage(err.message);
        setIsError(true);
      } finally {
        setIsLoading(false);
      }
    };
    fetchTenants();
  }, [accessToken, canAddTenants, isSuperAdmin, userTenantId]);

  const handleSaveTenant = async (form) => {
    setIsSubmitting(true);
    setMessage(null);
    setIsError(false);
  
    if (!form.name.trim()) {
      setMessage('Tenant name is required.');
      setIsError(true);
      setIsSubmitting(false);
      return;
    }
  
    const newTenantData = { 
      name: form.name, 
      description: form.description, 
      parent_tenant: form.parent_tenant || null 
    };
  
    const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` };
  
    try {
      const response = await fetch(`${API_BASE_URL}/tenants/`, {
        method: 'POST',
        headers,
        body: JSON.stringify(newTenantData),
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.detail || data.message || 'Failed to create tenant.');
  
      setMessage(`Tenant "${form.name}" has been created successfully.`);
      setIsError(false);
      setTenants([...tenants, data]);
    } catch (err) {
      setMessage(err.message);
      setIsError(true);
    } finally {
      setIsSubmitting(false);
      setModalOpen(false);
    }
  };

  const handleAddTenant = () => {
    setEditingTenant(null);
    setTenantName('');
    setTenantDescription('');
    setParentTenantId('');
    setModalOpen(true);
  };

  const handleEditTenant = (tenant) => {
    setEditingTenant(tenant);
    setTenantName(tenant.name);
    setTenantDescription(tenant.description);
    setParentTenantId(tenant.parent_tenant || '');
    setModalOpen(true);
  };

  // ✅ Instead of window.confirm
  const askDeleteTenant = (tenantId) => {
    setTenantToDelete(tenantId);
    setConfirmDeleteOpen(true);
  };

  const confirmDeleteTenant = async () => {
    if (!tenantToDelete) return;
  
    try {
      const response = await fetch(`${API_BASE_URL}/tenants/${tenantToDelete}/`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${accessToken}` },
      });
  
      if (!response.ok) throw new Error("Failed to delete tenant.");
  
      setTenants(tenants.filter(t => t.tenant_id !== tenantToDelete));
    } catch (err) {
      setMessage(err.message);
      setIsError(true);
    } finally {
      setTenantToDelete(null);
      setConfirmDeleteOpen(false);
    }
  };
  

  return (
    <AdminLayout>
      <div className="p-6">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-blue-900">Tenants</h1>
          <button className="bg-blue-600 text-white px-4 py-2 rounded" onClick={handleAddTenant}>Add Tenant</button>
        </div>
        <div className="overflow-x-auto bg-white rounded-lg shadow border border-gray-200">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-blue-600">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">ID</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Name</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Description</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Parent Tenant</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-100">
              {tenants.map((tenant, idx) => (
                <tr key={tenant.id} className={idx % 2 === 1 ? 'bg-gray-100' : ''}>
                  <td className="px-4 py-2 text-sm text-gray-700">{tenant.id}</td>
                  <td className="px-4 py-2 text-sm text-gray-900 font-medium">{tenant.name}</td>
                  <td className="px-4 py-2 text-sm text-gray-700">{tenant.description}</td>
                  <td className="px-4 py-2 text-sm text-gray-700">{tenant.parent || '-'}</td>
                  <td className="px-4 py-2 text-sm text-right">
                    <button
                      className="text-blue-600 hover:underline mr-2"
                      onClick={() => handleEditTenant(tenant)}
                    >
                      Edit
                    </button>
                    <button
                      className="text-red-600 hover:underline"
                      onClick={() => askDeleteTenant(tenant.tenant_id)}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* ✅ Custom delete confirmation modal */}
        <ConfirmDeleteModal
          open={confirmDeleteOpen}
          onClose={() => setConfirmDeleteOpen(false)}
          onConfirm={confirmDeleteTenant}
        />

        <TenantModal
          open={modalOpen}
          onClose={() => setModalOpen(false)}
          onSave={handleSaveTenant}
          tenant={editingTenant}
          tenants={tenants}
          name={tenantName}
          setName={setTenantName}
          description={tenantDescription}
          setDescription={setTenantDescription}
          parentTenantId={parentTenantId}
          setParentTenantId={setParentTenantId}
          isSubmitting={isSubmitting}
        />
      </div>
    </AdminLayout>
  );
}
