"use client";

import { EstimateVersionStatus } from "@capakraken/shared";
import { summarizeMonthlySpread } from "@capakraken/engine";
import { clsx } from "clsx";
import {
  getEffectiveDemandLineValues,
  resolveDemandLineCalculationMetadata,
} from "~/components/estimates/EstimateWorkspace.calculations.js";
import { ApplyEffortRules } from "~/components/estimates/ApplyEffortRules.js";
import { ApplyExperienceMultipliers } from "~/components/estimates/ApplyExperienceMultipliers.js";
import type {
  EstimateVersionView,
  EstimateWorkspaceView,
} from "~/components/estimates/EstimateWorkspace.types.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { formatMoney } from "~/lib/format.js";

function EmptyState({ children }: { children: React.ReactNode }) {
  return (
    <div className="rounded-3xl border border-dashed border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 px-5 py-10 text-center text-sm text-gray-400">
      {children}
    </div>
  );
}

export function StaffingTab({ estimate, canEdit }: { estimate: EstimateWorkspaceView; canEdit: boolean }) {
  const versions = estimate.versions as EstimateVersionView[];
  const latestVersion = versions[0] ?? null;
  const demandLines = latestVersion?.demandLines ?? [];
  const snapshots = latestVersion?.resourceSnapshots ?? [];
  const isWorking = latestVersion?.status === EstimateVersionStatus.WORKING;

  return (
    <div className="space-y-3">
      {isWorking && (
        <>
          <ApplyEffortRules
            estimateId={estimate.id}
            canEdit={canEdit}
          />
          <ApplyExperienceMultipliers
            estimateId={estimate.id}
            canEdit={canEdit}
          />
        </>
      )}

      {demandLines.length === 0 && (
        <EmptyState>No staffing demand lines captured for the current version yet.</EmptyState>
      )}
      {demandLines.map((line) => {
        const linkedSnapshot = line.resourceId
          ? snapshots.find((snapshot) => snapshot.resourceId === line.resourceId) ?? null
          : null;
        const calculation = resolveDemandLineCalculationMetadata({
          resourceSnapshot: linkedSnapshot,
          metadata: line.metadata,
          costRateCents: line.costRateCents,
          billRateCents: line.billRateCents,
        });
        const effectiveValues = getEffectiveDemandLineValues({
          resourceSnapshot: linkedSnapshot,
          hours: line.hours,
          currency: line.currency,
          defaultCurrency: line.currency,
          costRateCents: line.costRateCents,
          billRateCents: line.billRateCents,
          costRateMode: calculation.costRateMode,
          billRateMode: calculation.billRateMode,
        });

        return (
          <div key={line.id} className="rounded-3xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{line.name}</h3>
                <div className="mt-2 flex flex-wrap gap-2 text-xs text-gray-500 dark:text-gray-400">
                  <span>{line.lineType}</span>
                  {line.chapter && <span>{line.chapter}</span>}
                  {line.rateSource && <span>{line.rateSource}</span>}
                  {linkedSnapshot && <span>Linked: {linkedSnapshot.displayName}</span>}
                  <span
                    className={clsx(
                      "rounded-full px-2.5 py-1 font-medium",
                      calculation.costRateMode === "resource"
                        ? "bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300"
                        : "bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",
                    )}
                  >
                    Cost {calculation.costRateMode === "resource" ? "live" : "manual"}
                  </span>
                  <span
                    className={clsx(
                      "rounded-full px-2.5 py-1 font-medium",
                      calculation.billRateMode === "resource"
                        ? "bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300"
                        : "bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",
                    )}
                  >
                    Sell {calculation.billRateMode === "resource" ? "live" : "manual"}
                  </span>
                </div>
              </div>
              <div className="text-right">
                <p className="text-sm font-semibold text-gray-900 dark:text-gray-100">{line.hours.toFixed(1)} h</p>
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{effectiveValues.currency}</p>
              </div>
            </div>

            <div className="mt-5 grid gap-3 md:grid-cols-4">
              <div className="rounded-2xl bg-gray-50 dark:bg-gray-900 px-4 py-3">
                <p className="text-xs uppercase tracking-wide text-gray-400">Cost rate <InfoTooltip content="Internal hourly cost rate. Can be synced from the live resource or manually overridden." /></p>
                <p className="mt-1 text-sm font-medium text-gray-900 dark:text-gray-100">{formatMoney(line.costRateCents, line.currency)}</p>
                {linkedSnapshot && calculation.costRateMode === "manual" && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Live snapshot {formatMoney(linkedSnapshot.lcrCents, linkedSnapshot.currency)}
                  </p>
                )}
              </div>
              <div className="rounded-2xl bg-gray-50 dark:bg-gray-900 px-4 py-3">
                <p className="text-xs uppercase tracking-wide text-gray-400">Sell rate <InfoTooltip content="Client-facing hourly rate. Can be synced from the live resource or manually overridden." /></p>
                <p className="mt-1 text-sm font-medium text-gray-900 dark:text-gray-100">{formatMoney(line.billRateCents, line.currency)}</p>
                {linkedSnapshot && calculation.billRateMode === "manual" && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Live snapshot {formatMoney(linkedSnapshot.ucrCents, linkedSnapshot.currency)}
                  </p>
                )}
              </div>
              <div className="rounded-2xl bg-gray-50 dark:bg-gray-900 px-4 py-3">
                <p className="text-xs uppercase tracking-wide text-gray-400">Cost total <InfoTooltip content="Line cost total = hours x cost rate. Stored in cents." /></p>
                <p className="mt-1 text-sm font-medium text-gray-900 dark:text-gray-100">{formatMoney(effectiveValues.costTotalCents, effectiveValues.currency)}</p>
              </div>
              <div className="rounded-2xl bg-gray-50 dark:bg-gray-900 px-4 py-3">
                <p className="text-xs uppercase tracking-wide text-gray-400">Price total <InfoTooltip content="Line price total = hours x sell rate. This is the client-facing revenue for this line." /></p>
                <p className="mt-1 text-sm font-medium text-gray-900 dark:text-gray-100">{formatMoney(effectiveValues.priceTotalCents, effectiveValues.currency)}</p>
              </div>
            </div>

            {line.monthlySpread && Object.keys(line.monthlySpread).length > 0 && (
              <div className="mt-4">
                <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-400">Monthly phasing</p>
                <div className="flex flex-wrap gap-2">
                  {Object.entries(line.monthlySpread)
                    .sort(([a], [b]) => a.localeCompare(b))
                    .map(([month, hours]) => (
                      <div key={month} className="rounded-xl bg-gray-50 dark:bg-gray-900 px-3 py-1.5 text-xs">
                        <span className="text-gray-500 dark:text-gray-400">{month}</span>
                        <span className="ml-1.5 font-medium text-gray-900 dark:text-gray-100">{hours.toFixed(1)} h</span>
                      </div>
                    ))}
                </div>
              </div>
            )}
          </div>
        );
      })}

      {(() => {
        const spreads = demandLines
          .map((line) => line.monthlySpread)
          .filter((spread): spread is Record<string, number> => spread != null && Object.keys(spread).length > 0);
        if (spreads.length === 0) return null;
        const aggregated = summarizeMonthlySpread(spreads);
        const months = Object.keys(aggregated).sort();
        if (months.length === 0) return null;
        return (
          <div className="rounded-3xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm">
            <p className="mb-3 text-sm font-semibold text-gray-900 dark:text-gray-100">Aggregated monthly phasing <InfoTooltip content="Sum of hours across all demand lines per month, based on the project date range." /></p>
            <div className="flex flex-wrap gap-2">
              {months.map((month) => (
                <div key={month} className="rounded-xl bg-gray-50 dark:bg-gray-900 px-3 py-2 text-sm">
                  <span className="text-gray-500 dark:text-gray-400">{month}</span>
                  <span className="ml-2 font-semibold text-gray-900 dark:text-gray-100">{(aggregated[month] ?? 0).toFixed(1)} h</span>
                </div>
              ))}
            </div>
            <div className="mt-3 text-right text-sm font-semibold text-gray-700 dark:text-gray-300">
              Total: {Object.values(aggregated).reduce((a, b) => a + b, 0).toFixed(1)} h
            </div>
          </div>
        );
      })()}
    </div>
  );
}
