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

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

export function WarehouseDetailPage() {
  const { token, user } = useAuth();
  const { warehouseId } = useParams();
  const [warehouse, setWarehouse] = useState<WarehouseDetailDto | null>(null);
  const [status, setStatus] = useState("Loading warehouse...");

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

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

    api
      .getWarehouse(token, warehouseId)
      .then((nextWarehouse) => {
        setWarehouse(nextWarehouse);
        setStatus("Warehouse loaded.");
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load warehouse.";
        setStatus(message);
      });
  }, [token, warehouseId]);

  if (!warehouse) {
    return <div className="rounded-[20px] border border-line/70 bg-surface/90 p-8 text-sm text-muted shadow-panel">{status}</div>;
  }

  return (
    <section className="space-y-4">
      <div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Warehouse Detail</p>
            <h3 className="mt-2 text-2xl font-bold text-text">{warehouse.code}</h3>
            <p className="mt-1 text-sm text-text">{warehouse.name}</p>
            <p className="mt-3 text-sm text-muted">Last updated {new Date(warehouse.updatedAt).toLocaleString()}.</p>
          </div>
          <div className="flex flex-wrap gap-3">
          <Link to="/inventory/warehouses" className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">
              Back to warehouses
            </Link>
            {canManage ? (
            <Link to={`/inventory/warehouses/${warehouse.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">
                Edit warehouse
              </Link>
            ) : null}
          </div>
        </div>
      </div>
      <div className="grid gap-3 xl:grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)]">
        <article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Notes</p>
          <p className="mt-3 whitespace-pre-line text-sm leading-6 text-text">{warehouse.notes || "No warehouse notes recorded."}</p>
          <div className="mt-8 rounded-2xl border border-line/70 bg-page/70 px-2 py-2 text-sm text-muted">
            Created {new Date(warehouse.createdAt).toLocaleDateString()}
          </div>
        </article>
        <section className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Locations</p>
          <h4 className="mt-2 text-lg font-bold text-text">Stock locations</h4>
          {warehouse.locations.length === 0 ? (
          <div className="mt-6 rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">
              No stock locations have been defined for this warehouse yet.
            </div>
          ) : (
            <div className="mt-6 grid gap-3 xl:grid-cols-2">
              {warehouse.locations.map((location: WarehouseLocationDto) => (
              <article key={location.id} className="rounded-[18px] border border-line/70 bg-page/60 px-2 py-2">
                  <div className="text-sm font-semibold text-text">{location.code}</div>
                  <div className="mt-1 text-sm text-text">{location.name}</div>
                  <div className="mt-2 text-xs leading-6 text-muted">{location.notes || "No notes."}</div>
                </article>
              ))}
            </div>
          )}
        </section>
      </div>
    </section>
  );
}

