"use client";

import type { inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "@/server/routers/_app";
import { formatCurrency } from "@/lib/print-export";

type RouterOutputs = inferRouterOutputs<AppRouter>;
type Project = NonNullable<RouterOutputs["project"]["getById"]>;
type ProjectItem = NonNullable<Project["projectItems"]>[number];

function calcItemRate(pi: ProjectItem): number {
  if (pi.estimatedRate) return Number(pi.estimatedRate);
  if (pi.item.itemRates?.[0]?.rate) return Number(pi.item.itemRates[0].rate);
  return 0;
}

interface ProjectPrintViewProps {
  project: Project;
}

export function ProjectPrintView({ project }: ProjectPrintViewProps) {
  const itemsByCategory = (project.projectItems ?? []).reduce<
    Record<string, ProjectItem[]>
  >((acc, pi) => {
    const cat = pi.item.category?.name ?? "Uncategorized";
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(pi);
    return acc;
  }, {});

  const grandTotal = (project.projectItems ?? []).reduce((sum, pi) => {
    const rate = calcItemRate(pi);
    const weight = pi.weight ? Number(pi.weight) : 1;
    return sum + rate * Number(pi.quantity) * weight;
  }, 0);

  return (
    <div className="print-view print-only p-8">
      <div className="mb-6 border-b pb-4">
        <h1 className="text-2xl font-bold">
          {project.code} - {project.name}
        </h1>
        <p className="text-muted-foreground mt-1">Assigned Items - Print View</p>
        <p className="text-muted-foreground text-sm mt-1">
          Printed on: {new Date().toLocaleDateString()}
        </p>
      </div>

      {Object.entries(itemsByCategory)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([categoryName, items]) => {
        const sortedItems = [...items].sort((a, b) =>
          (a.item.code ?? "").localeCompare(b.item.code ?? "")
        );
        const categoryTotal = items.reduce((sum, pi) => {
          const rate = calcItemRate(pi);
          const weight = pi.weight ? Number(pi.weight) : 1;
          return sum + rate * Number(pi.quantity) * weight;
        }, 0);

        return (
          <div key={categoryName} className="mb-6">
            <h2 className="mb-3 border-b pb-1 font-semibold text-lg">
              {categoryName}
            </h2>
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-1 w-8">#</th>
                  <th className="text-left py-1 w-20">Code</th>
                  <th className="text-left py-1">Name</th>
                  <th className="text-right py-1 w-20">Qty</th>
                  <th className="text-right py-1 w-16">Unit</th>
                  <th className="text-right py-1 w-16">Wt.</th>
                  <th className="text-right py-1 w-24">Rate</th>
                  <th className="text-right py-1 w-24">Total</th>
                </tr>
              </thead>
              <tbody>
                {sortedItems.map((pi, idx) => {
                  const rate = calcItemRate(pi);
                  const weight = pi.weight ? Number(pi.weight) : 1;
                  const total = rate * Number(pi.quantity) * weight;
                  return (
                    <tr key={pi.id} className="border-b">
                      <td className="py-1">{idx + 1}</td>
                      <td className="py-1">{pi.item.code}</td>
                      <td className="py-1">{pi.item.name}</td>
                      <td className="text-right py-1">{Number(pi.quantity)}</td>
                      <td className="text-right py-1">{pi.item.unit ?? "-"}</td>
                      <td className="text-right py-1">{weight.toFixed(2)}</td>
                      <td className="text-right py-1">{formatCurrency(rate)}</td>
                      <td className="text-right py-1">{formatCurrency(total)}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr>
                  <td colSpan={6} className="text-right py-2 font-semibold">
                    {categoryName} Total:
                  </td>
                  <td />
                  <td className="text-right py-2 font-semibold">
                    {formatCurrency(categoryTotal)}
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        );
      })}

      <div className="mb-8 border-t pt-4">
        <div className="text-right text-lg font-bold">
          Grand Total: {formatCurrency(grandTotal)}
        </div>
      </div>

      <div className="grid grid-cols-2 gap-8 mt-16">
        <div>
          <div className="border-b mb-2 pb-8" />
          <p className="font-semibold">Verified By</p>
        </div>
        <div>
          <div className="border-b mb-2 pb-8" />
          <p className="font-semibold">Approved By</p>
        </div>
      </div>
    </div>
  );
}
