import { permissions } from "@mrp/shared";
import type { WorkOrderStatus, WorkOrderSummaryDto } from "@mrp/shared";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

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

export function WorkOrderListPage() {
  const { token, user } = useAuth();
  const [workOrders, setWorkOrders] = useState<WorkOrderSummaryDto[]>([]);
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | WorkOrderStatus>("ALL");
  const [status, setStatus] = useState("Loading work orders...");

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

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

    setStatus("Loading work orders...");
    api.getWorkOrders(token, { q: query || undefined, status: statusFilter === "ALL" ? undefined : statusFilter })
      .then((nextWorkOrders) => {
        setWorkOrders(nextWorkOrders);
        setStatus(nextWorkOrders.length === 0 ? "No work orders matched the current filters." : `${nextWorkOrders.length} work order(s) loaded.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load work orders.";
        setStatus(message);
      });
  }, [query, statusFilter, token]);

  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">Manufacturing</p>
            <h3 className="mt-2 text-xl font-bold text-text">Work Orders</h3>
            <p className="mt-2 max-w-3xl text-sm text-muted">Release and execute build work against manufactured or assembly inventory items, with project linkage and real inventory posting.</p>
          </div>
          {canManage ? (
            <Link to="/manufacturing/work-orders/new" className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">
              New work order
            </Link>
          ) : null}
        </div>
      </div>
      <section className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_240px]">
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Search</span>
            <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search work order, item, or project" className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Status</span>
            <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as "ALL" | WorkOrderStatus)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              {workOrderStatusFilters.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
        </div>
        <div className="mt-4 rounded-2xl border border-line/70 bg-page/70 px-2 py-2 text-sm text-muted">{status}</div>
      </section>
      {workOrders.length === 0 ? (
        <div className="rounded-[20px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No work orders are available yet.</div>
      ) : (
        <div className="overflow-hidden rounded-[20px] border border-line/70 bg-surface/90 shadow-panel">
          <table className="min-w-full divide-y divide-line/70 text-sm">
            <thead className="bg-page/70">
              <tr className="text-left text-xs font-semibold uppercase tracking-[0.18em] text-muted">
                <th className="px-3 py-3">Work Order</th>
                <th className="px-3 py-3">Item</th>
                <th className="px-3 py-3">Project</th>
                <th className="px-3 py-3">Status</th>
                <th className="px-3 py-3">Qty</th>
                <th className="px-3 py-3">Location</th>
                <th className="px-3 py-3">Ops</th>
                <th className="px-3 py-3">Due</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line/70">
              {workOrders.map((workOrder) => (
                <tr key={workOrder.id} className="bg-surface/70 transition hover:bg-page/60">
                  <td className="px-3 py-3 align-top">
                    <Link to={`/manufacturing/work-orders/${workOrder.id}`} className="font-semibold text-text hover:text-brand">{workOrder.workOrderNumber}</Link>
                  </td>
                  <td className="px-3 py-3 align-top">
                    <div className="font-semibold text-text">{workOrder.itemSku}</div>
                    <div className="mt-1 text-xs text-muted">{workOrder.itemName}</div>
                  </td>
                  <td className="px-3 py-3 align-top text-text">{workOrder.projectNumber ? `${workOrder.projectNumber} - ${workOrder.projectName}` : "Unlinked"}</td>
                  <td className="px-3 py-3 align-top"><WorkOrderStatusBadge status={workOrder.status} /></td>
                  <td className="px-3 py-3 align-top text-text">{workOrder.completedQuantity} / {workOrder.quantity}</td>
                  <td className="px-3 py-3 align-top text-text">{workOrder.warehouseCode} / {workOrder.locationCode}</td>
                  <td className="px-3 py-3 align-top text-text">{workOrder.operationCount} / {Math.round(workOrder.totalPlannedMinutes / 60)}h</td>
                  <td className="px-3 py-3 align-top text-text">{workOrder.dueDate ? new Date(workOrder.dueDate).toLocaleDateString() : "Not set"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}

