import { permissions } from "@mrp/shared";
import type { WarehouseSummaryDto } from "@mrp/shared/dist/inventory/types.js";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";

export function WarehousesPage() {
  const { token, user } = useAuth();
  const [warehouses, setWarehouses] = useState<WarehouseSummaryDto[]>([]);
  const [status, setStatus] = useState("Loading warehouses...");

  const canManage = user?.permissions.includes(permissions.inventoryWrite) ?? false;

  useEffect(() => {
    if (!token) {
      return;
    }

    api
      .getWarehouses(token)
      .then((nextWarehouses) => {
        setWarehouses(nextWarehouses);
        setStatus(`${nextWarehouses.length} warehouse(s) available.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load warehouses.";
        setStatus(message);
      });
  }, [token]);

  return (
    <section className="rounded-[28px] border border-line/70 bg-surface/90 p-6 shadow-panel 2xl:p-7">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Inventory</p>
          <h3 className="mt-3 text-xl font-bold text-text">Warehouses</h3>
          <p className="mt-2 max-w-2xl text-sm text-muted">Physical warehouse records and their internal stock locations.</p>
        </div>
        {canManage ? (
          <Link to="/inventory/warehouses/new" className="inline-flex items-center justify-center rounded-2xl bg-brand px-3 py-2 text-sm font-semibold text-white">
            New warehouse
          </Link>
        ) : null}
      </div>
      <div className="mt-6 rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm text-muted">{status}</div>
      {warehouses.length === 0 ? (
        <div className="mt-6 rounded-3xl border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">
          No warehouses have been added yet.
        </div>
      ) : (
        <div className="mt-6 overflow-hidden rounded-2xl border border-line/70">
          <table className="min-w-full divide-y divide-line/70 text-sm">
            <thead className="bg-page/80 text-left text-muted">
              <tr>
                <th className="px-2 py-2">Code</th>
                <th className="px-2 py-2">Name</th>
                <th className="px-2 py-2">Locations</th>
                <th className="px-2 py-2">Updated</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line/70 bg-surface">
              {warehouses.map((warehouse) => (
                <tr key={warehouse.id} className="transition hover:bg-page/70">
                  <td className="px-2 py-2 font-semibold text-text">
                    <Link to={`/inventory/warehouses/${warehouse.id}`} className="hover:text-brand">
                      {warehouse.code}
                    </Link>
                  </td>
                  <td className="px-2 py-2 text-muted">{warehouse.name}</td>
                  <td className="px-2 py-2 text-muted">{warehouse.locationCount}</td>
                  <td className="px-2 py-2 text-muted">{new Date(warehouse.updatedAt).toLocaleDateString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
