import { useMemo } from "react";
import { clsx } from "clsx";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { formatCents } from "~/lib/format.js";
import { BTN_PRIMARY, type WizardState } from "./types.js";

interface Step5Props {
  state: WizardState;
  onChange: (patch: Partial<WizardState>) => void;
  onSubmit: () => void;
  isSubmitting: boolean;
  submitError: string | null;
  submitWarnings: string[];
}

export function Step5Review({
  state,
  onChange,
  onSubmit,
  isSubmitting,
  submitError,
  submitWarnings,
}: Step5Props) {
  const totalAssignedCostHint = useMemo(() => {
    return state.staffingReqs.reduce((sum, r) => sum + r.hoursPerDay * r.headcount, 0);
  }, [state.staffingReqs]);

  return (
    <div className="space-y-4">
      {/* Project summary */}
      <div className="flex items-center gap-1 mb-1">
        <p className="text-xs font-medium text-gray-600 uppercase tracking-wider">
          Project Summary
        </p>
        <InfoTooltip content="Review all project details before creation. The project, staffing demands, and any pre-assigned resources will be created together." />
      </div>
      <div className="bg-gray-50 rounded-lg p-4 text-sm space-y-2">
        <div className="grid grid-cols-2 gap-x-6 gap-y-1">
          <div>
            <span className="text-gray-500">Code:</span>{" "}
            <span className="font-mono font-medium">{state.shortCode || "—"}</span>
          </div>
          <div>
            <span className="text-gray-500">Name:</span>{" "}
            <span className="font-medium">{state.name || "—"}</span>
          </div>
          <div>
            <span className="text-gray-500">Order Type:</span> {state.orderType}
          </div>
          <div>
            <span className="text-gray-500">Allocation Type:</span> {state.allocationType}
          </div>
          <div>
            <span className="text-gray-500">Status on create:</span>{" "}
            {state.saveAsDraft ? "Draft" : "Active"}
          </div>
          <div>
            <span className="text-gray-500">Budget:</span>{" "}
            {state.budgetEur ? `€${parseFloat(state.budgetEur).toLocaleString()}` : "—"}
          </div>
          <div>
            <span className="text-gray-500">Dates:</span> {state.startDate} → {state.endDate}
          </div>
          <div>
            <span className="text-gray-500">Win %:</span> {state.winProbability}%
          </div>
          {state.responsiblePerson && (
            <div className="col-span-2">
              <span className="text-gray-500">Responsible:</span> {state.responsiblePerson}
            </div>
          )}
          {state.blueprintName && (
            <div className="col-span-2">
              <span className="text-gray-500">Blueprint:</span> {state.blueprintName}
            </div>
          )}
        </div>
        {/* Blueprint custom fields summary */}
        {state.blueprintFieldDefs.length > 0 && Object.keys(state.dynamicFields).length > 0 && (
          <div className="border-t border-gray-200 pt-2 mt-2 space-y-1">
            <p className="text-xs text-gray-400 font-medium">Custom Fields</p>
            {state.blueprintFieldDefs.map((field) => {
              const val = state.dynamicFields[field.key];
              if (val === undefined || val === null || val === "") return null;
              const display = Array.isArray(val) ? val.join(", ") : String(val);
              return (
                <div key={field.key} className="flex gap-2 text-xs">
                  <span className="text-gray-500">{field.label}:</span>
                  <span className="font-medium truncate">{display}</span>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Staffing summary */}
      {state.staffingReqs.length > 0 && (
        <div>
          <p className="text-xs font-medium text-gray-600 uppercase tracking-wider mb-2">
            Staffing Requirements
            {totalAssignedCostHint > 0 && (
              <span className="ml-2 normal-case font-normal text-gray-400">
                · {totalAssignedCostHint.toFixed(1)} total h/day across all roles
              </span>
            )}
          </p>
          <div className="space-y-1.5">
            {state.staffingReqs.map((req) => {
              const assigned = state.assignments.filter((a) => a.requirementId === req.id);
              const assignedNames = assigned.map((a) => a.resourceName);
              const unassigned = req.headcount - assigned.length;
              return (
                <div key={req.id} className="px-3 py-2 rounded-lg bg-gray-50 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="flex-1 font-medium">{req.role || "Unnamed"}</span>
                    <span className="text-gray-400 text-xs">{req.hoursPerDay}h/day</span>
                    {req.budgetCents ? (
                      <span className="text-xs text-gray-400">
                        {formatCents(req.budgetCents)} EUR
                      </span>
                    ) : null}
                    <span
                      className={clsx(
                        "text-xs font-medium",
                        assigned.length >= req.headcount ? "text-green-600" : "text-amber-600",
                      )}
                    >
                      {assigned.length}/{req.headcount} assigned
                    </span>
                  </div>
                  {(req.requiredSkills.length > 0 || (req.preferredSkills ?? []).length > 0) && (
                    <div className="mt-1 flex flex-wrap gap-1">
                      {req.requiredSkills.map((s) => (
                        <span
                          key={s}
                          className="px-1.5 py-0.5 rounded text-[10px] bg-brand-100 text-brand-700"
                        >
                          {s}
                        </span>
                      ))}
                      {(req.preferredSkills ?? []).map((s) => (
                        <span
                          key={s}
                          className="px-1.5 py-0.5 rounded text-[10px] bg-gray-100 text-gray-500"
                        >
                          {s}
                        </span>
                      ))}
                    </div>
                  )}
                  {assignedNames.length > 0 && (
                    <div className="mt-1 text-xs text-gray-500">
                      Assigned: {assignedNames.join(", ")}
                      {unassigned > 0 && ` · ${unassigned} open seat${unassigned > 1 ? "s" : ""}`}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Post-creation warnings */}
      {submitWarnings.length > 0 && (
        <div className="px-3 py-2 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-800 dark:text-amber-300 space-y-1">
          <p className="font-medium">Project created with warnings:</p>
          {submitWarnings.map((w, i) => (
            <p key={i} className="text-xs">
              {w}
            </p>
          ))}
          <p className="text-xs mt-1 text-amber-600 dark:text-amber-400">
            You can fix these staffing items from the project detail page.
          </p>
        </div>
      )}

      {/* Draft toggle */}
      <div className="border border-gray-200 rounded-lg p-4">
        <p className="text-xs font-medium text-gray-600 uppercase tracking-wider mb-3 flex items-center gap-1">
          Save as
          <InfoTooltip content="Draft projects are hidden from the timeline until activated. Active projects appear on the timeline immediately." />
        </p>
        <div className="flex gap-4">
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name="saveMode"
              checked={state.saveAsDraft}
              onChange={() => onChange({ saveAsDraft: true })}
              className="accent-brand-600"
            />
            <div>
              <div className="text-sm font-medium">Draft</div>
              <div className="text-xs text-gray-400">Hidden on timeline until enabled</div>
            </div>
          </label>
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name="saveMode"
              checked={!state.saveAsDraft}
              onChange={() => onChange({ saveAsDraft: false })}
              className="accent-brand-600"
            />
            <div>
              <div className="text-sm font-medium">Active</div>
              <div className="text-xs text-gray-400">Visible on timeline immediately</div>
            </div>
          </label>
        </div>
      </div>

      {submitError && (
        <div className="px-3 py-2 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          {submitError}
        </div>
      )}

      <div className="flex justify-end">
        <button type="button" onClick={onSubmit} disabled={isSubmitting} className={BTN_PRIMARY}>
          {isSubmitting
            ? "Creating…"
            : state.saveAsDraft
              ? "Create Draft Project"
              : "Create Active Project"}
        </button>
      </div>
    </div>
  );
}
