import { permissions } from "@mrp/shared";
import type { ProjectDetailDto } from "@mrp/shared/dist/projects/types.js";
import type { SalesOrderPlanningDto } from "@mrp/shared/dist/sales/types.js";
import type { WorkOrderSummaryDto } from "@mrp/shared";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import { FileAttachmentsPanel } from "../../components/FileAttachmentsPanel";
import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { ProjectPriorityBadge } from "./ProjectPriorityBadge";
import { ProjectStatusBadge } from "./ProjectStatusBadge";

export function ProjectDetailPage() {
  const { token, user } = useAuth();
  const { projectId } = useParams();
  const [project, setProject] = useState<ProjectDetailDto | null>(null);
  const [workOrders, setWorkOrders] = useState<WorkOrderSummaryDto[]>([]);
  const [planning, setPlanning] = useState<SalesOrderPlanningDto | null>(null);
  const [status, setStatus] = useState("Loading project...");

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

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

    api.getProject(token, projectId)
      .then((nextProject) => {
        setProject(nextProject);
        setStatus("Project loaded.");
        if (nextProject.salesOrderId) {
          api.getSalesOrderPlanning(token, nextProject.salesOrderId).then(setPlanning).catch(() => setPlanning(null));
        } else {
          setPlanning(null);
        }
        return api.getWorkOrders(token, { projectId: nextProject.id });
      })
      .then((nextWorkOrders) => setWorkOrders(nextWorkOrders))
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load project.";
        setStatus(message);
      });
  }, [projectId, token]);

  if (!project) {
    return <div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 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">Project</p>
            <h3 className="mt-2 text-xl font-bold text-text">{project.projectNumber}</h3>
            <p className="mt-1 text-sm text-text">{project.name}</p>
            <div className="mt-3 flex flex-wrap gap-2">
              <ProjectStatusBadge status={project.status} />
              <ProjectPriorityBadge priority={project.priority} />
            </div>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link to="/projects" 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 projects</Link>
            {canManage ? <Link to={`/projects/${project.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">Edit project</Link> : null}
          </div>
        </div>
      </div>
      <section className="grid gap-3 xl:grid-cols-4">
        <article className="rounded-[18px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Customer</p><div className="mt-2 text-base font-bold text-text">{project.customerName}</div></article>
        <article className="rounded-[18px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Owner</p><div className="mt-2 text-base font-bold text-text">{project.ownerName || "Unassigned"}</div></article>
        <article className="rounded-[18px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Due Date</p><div className="mt-2 text-base font-bold text-text">{project.dueDate ? new Date(project.dueDate).toLocaleDateString() : "Not set"}</div></article>
        <article className="rounded-[18px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Created</p><div className="mt-2 text-base font-bold text-text">{new Date(project.createdAt).toLocaleDateString()}</div></article>
      </section>
      <div className="grid gap-3 xl:grid-cols-[minmax(0,1.05fr)_minmax(320px,0.95fr)]">
        <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">Customer Linkage</p>
          <dl className="mt-5 grid gap-3">
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Account</dt><dd className="mt-1 text-sm text-text"><Link to={`/crm/customers/${project.customerId}`} className="hover:text-brand">{project.customerName}</Link></dd></div>
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Email</dt><dd className="mt-1 text-sm text-text">{project.customerEmail}</dd></div>
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Phone</dt><dd className="mt-1 text-sm text-text">{project.customerPhone}</dd></div>
          </dl>
        </article>
        <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">Program Notes</p>
          <p className="mt-3 whitespace-pre-line text-sm leading-6 text-text">{project.notes || "No project notes recorded."}</p>
        </article>
      </div>
      <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">Commercial + Delivery Links</p>
        <div className="mt-5 grid gap-3 xl:grid-cols-3">
          <div className="rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-muted">Quote</div>
            <div className="mt-2 font-semibold text-text">{project.salesQuoteNumber ? <Link to={`/sales/quotes/${project.salesQuoteId}`} className="hover:text-brand">{project.salesQuoteNumber}</Link> : "Not linked"}</div>
          </div>
          <div className="rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-muted">Sales Order</div>
            <div className="mt-2 font-semibold text-text">{project.salesOrderNumber ? <Link to={`/sales/orders/${project.salesOrderId}`} className="hover:text-brand">{project.salesOrderNumber}</Link> : "Not linked"}</div>
          </div>
          <div className="rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-muted">Shipment</div>
            <div className="mt-2 font-semibold text-text">{project.shipmentNumber ? <Link to={`/shipping/shipments/${project.shipmentId}`} className="hover:text-brand">{project.shipmentNumber}</Link> : "Not linked"}</div>
          </div>
        </div>
      </section>
      {planning ? (
        <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">Material Readiness</p>
          <div className="mt-5 grid gap-3 xl:grid-cols-4">
            <article className="rounded-[18px] border border-line/70 bg-page/60 px-3 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Build Qty</p>
              <div className="mt-2 text-base font-bold text-text">{planning.summary.totalBuildQuantity}</div>
            </article>
            <article className="rounded-[18px] border border-line/70 bg-page/60 px-3 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Buy Qty</p>
              <div className="mt-2 text-base font-bold text-text">{planning.summary.totalPurchaseQuantity}</div>
            </article>
            <article className="rounded-[18px] border border-line/70 bg-page/60 px-3 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Uncovered Qty</p>
              <div className="mt-2 text-base font-bold text-text">{planning.summary.totalUncoveredQuantity}</div>
            </article>
            <article className="rounded-[18px] border border-line/70 bg-page/60 px-3 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Shortage Items</p>
              <div className="mt-2 text-base font-bold text-text">{planning.summary.uncoveredItemCount}</div>
            </article>
          </div>
          <div className="mt-5 space-y-3">
            {planning.items
              .filter((item) => item.recommendedBuildQuantity > 0 || item.recommendedPurchaseQuantity > 0 || item.uncoveredQuantity > 0)
              .slice(0, 8)
              .map((item) => (
                <div key={item.itemId} className="rounded-[18px] border border-line/70 bg-page/60 p-3">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <div className="font-semibold text-text">{item.itemSku}</div>
                      <div className="mt-1 text-xs text-muted">{item.itemName}</div>
                    </div>
                    <div className="text-sm text-muted">
                      Build {item.recommendedBuildQuantity} · Buy {item.recommendedPurchaseQuantity} · Uncovered {item.uncoveredQuantity}
                    </div>
                  </div>
                </div>
              ))}
          </div>
        </section>
      ) : null}
      <section className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex items-center justify-between gap-3">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Manufacturing Links</p>
            <p className="mt-2 text-sm text-muted">Work orders already linked to this project.</p>
          </div>
          {canManage ? (
            <Link to={`/manufacturing/work-orders/new?projectId=${project.id}`} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">
              New work order
            </Link>
          ) : null}
        </div>
        {workOrders.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 work orders are linked to this project yet.</div>
        ) : (
          <div className="mt-6 space-y-3">
            {workOrders.map((workOrder) => (
              <Link key={workOrder.id} to={`/manufacturing/work-orders/${workOrder.id}`} className="block rounded-[18px] border border-line/70 bg-page/60 p-3 transition hover:bg-page/80">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <div className="font-semibold text-text">{workOrder.workOrderNumber}</div>
                    <div className="mt-1 text-xs text-muted">{workOrder.itemSku} · {workOrder.completedQuantity}/{workOrder.quantity} complete</div>
                  </div>
                  <div className="text-sm font-semibold text-text">{workOrder.status.replace("_", " ")}</div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </section>
      <FileAttachmentsPanel
        ownerType="PROJECT"
        ownerId={project.id}
        eyebrow="Project Documents"
        title="Program file hub"
        description="Store drawings, revision references, correspondence, and support files directly on the project record."
        emptyMessage="No project files have been uploaded yet."
      />
      <div className="rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm text-muted">{status}</div>
    </section>
  );
}

