"use client";

import { useState, useEffect, useRef, useMemo } from "react";
import { useFocusTrap } from "~/hooks/useFocusTrap.js";
import { useInvalidatePlanningViews } from "~/hooks/useInvalidatePlanningViews.js";
import { AllocationStatus } from "@capakraken/shared";
import type { AllocationWithDetails, RecurrencePattern } from "@capakraken/shared";
import { trpc } from "~/lib/trpc/client.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
import { DateInput } from "~/components/ui/DateInput.js";
import { RecurrenceEditor } from "./RecurrenceEditor.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";

const ALLOCATION_STATUSES = Object.values(AllocationStatus);
type EntryKind = "demand" | "assignment";

interface AllocationModalProps {
  allocation?: AllocationWithDetails | null;
  onClose: () => void;
  onSuccess: () => void;
}

function toDateInputValue(date: Date | string | null | undefined): string {
  if (!date) return "";
  const d = typeof date === "string" ? new Date(date) : date;
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

export function AllocationModal({ allocation, onClose, onSuccess }: AllocationModalProps) {
  const isEditing = Boolean(allocation);
  const initialEntryKind: EntryKind = allocation && !allocation.resourceId ? "demand" : "assignment";
  const [entryKind, setEntryKind] = useState<EntryKind>(initialEntryKind);
  const isDemandEntry = entryKind === "demand";

  const [resourceId, setResourceId] = useState(allocation?.resourceId ?? "");
  const [projectId, setProjectId] = useState(allocation?.projectId ?? "");
  const [roleId, setRoleId] = useState(allocation?.roleId ?? "");
  const [roleFreeText, setRoleFreeText] = useState(allocation?.role ?? "");
  const [headcount, setHeadcount] = useState(allocation?.headcount ?? 1);
  const [budgetEur, setBudgetEur] = useState(() => {
    const cents = (allocation as { budgetCents?: number } | undefined)?.budgetCents ?? 0;
    return cents > 0 ? String(cents / 100) : "";
  });
  const [startDate, setStartDate] = useState(toDateInputValue(allocation?.startDate));
  const [endDate, setEndDate] = useState(toDateInputValue(allocation?.endDate));
  const [hoursPerDay, setHoursPerDay] = useState<number>(allocation?.hoursPerDay ?? 8);
  const [status, setStatus] = useState<AllocationStatus>(
    allocation?.status ?? AllocationStatus.PROPOSED,
  );
  const existingMeta = allocation?.metadata as Record<string, unknown> | undefined;
  const [isRecurring, setIsRecurring] = useState<boolean>(!!existingMeta?.recurrence);
  const [recurrence, setRecurrence] = useState<RecurrencePattern | undefined>(
    existingMeta?.recurrence as RecurrencePattern | undefined,
  );
  const [serverError, setServerError] = useState<string | null>(null);

  const panelRef = useRef<HTMLDivElement>(null);
  useFocusTrap(panelRef, true);

  const { data: resources } = trpc.resource.directory.useQuery(
    { isActive: true, limit: 500 },
    { staleTime: 60_000 },
  );
  const { data: projects } = trpc.project.list.useQuery(
    { limit: 500 },
    { staleTime: 60_000 },
  );
  const { data: rolesData } = trpc.role.list.useQuery(
    { isActive: true },
    { staleTime: 60_000 },
  );

  // Fetch existing allocations for the selected resource+project to detect overlaps
  const shouldCheckOverlap = !isDemandEntry && !!resourceId && !!projectId;
  const { data: existingAllocations } = trpc.allocation.listView.useQuery(
    { projectId, resourceId },
    { enabled: shouldCheckOverlap, staleTime: 30_000 },
  );

  const overlapWarning = useMemo(() => {
    if (!shouldCheckOverlap || !existingAllocations || !startDate || !endDate) return null;
    const formStart = new Date(startDate);
    const formEnd = new Date(endDate);
    if (isNaN(formStart.getTime()) || isNaN(formEnd.getTime())) return null;

    const allocList = (existingAllocations as { allocations?: Array<{ id: string; resourceId?: string | null; startDate: string | Date; endDate: string | Date }> }).allocations ?? [];
    for (const existing of allocList) {
      // Skip the allocation being edited
      if (isEditing && allocation && existing.id === allocation.id) continue;
      // Only check assignments for this resource
      if (existing.resourceId !== resourceId) continue;
      const exStart = new Date(existing.startDate);
      const exEnd = new Date(existing.endDate);
      // Check date overlap
      if (formStart <= exEnd && formEnd >= exStart) {
        const fmt = (d: Date) => d.toISOString().slice(0, 10);
        return `This resource is already assigned to this project from ${fmt(exStart)} to ${fmt(exEnd)}. Consider updating the existing assignment instead.`;
      }
    }
    return null;
  }, [shouldCheckOverlap, existingAllocations, startDate, endDate, isEditing, allocation, resourceId]);

  const invalidatePlanningViews = useInvalidatePlanningViews();

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const createDemandMutation = (trpc.allocation.createDemandRequirement.useMutation as any)({
    onSuccess: () => {
      invalidatePlanningViews();
      onSuccess();
    },
    onError: (err: { message: string }) => {
      setServerError(err.message);
    },
  }) as {
    isPending: boolean;
    isError: boolean;
    error?: { message: string };
    mutate: (input: unknown) => void;
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const createAssignmentMutation = (trpc.allocation.createAssignment.useMutation as any)({
    onSuccess: () => {
      invalidatePlanningViews();
      onSuccess();
    },
    onError: (err: { message: string }) => {
      setServerError(err.message);
    },
  }) as {
    isPending: boolean;
    isError: boolean;
    error?: { message: string };
    mutate: (input: unknown) => void;
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const updateMutation = (trpc.allocation.update.useMutation as any)({
    onSuccess: () => {
      invalidatePlanningViews();
      onSuccess();
    },
    onError: (err: { message: string }) => {
      setServerError(err.message);
    },
  }) as {
    isPending: boolean;
    isError: boolean;
    error?: { message: string };
    mutate: (input: unknown) => void;
  };

  const isPending =
    createDemandMutation.isPending ||
    createAssignmentMutation.isPending ||
    updateMutation.isPending;

  useEffect(() => {
    setServerError(null);
  }, [resourceId, projectId, roleId, roleFreeText, startDate, endDate, hoursPerDay, status, entryKind]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setServerError(null);

    if (!projectId) {
      setServerError("Please select a project.");
      return;
    }
    if (!isDemandEntry && !resourceId) {
      setServerError("Please select a resource.");
      return;
    }
    if (!startDate || !endDate) {
      setServerError("Please fill in start and end dates.");
      return;
    }

    const start = new Date(startDate);
    const end = new Date(endDate);

    if (end < start) {
      setServerError("End date must be on or after start date.");
      return;
    }

    const baseMeta = (allocation?.metadata as Record<string, unknown> | undefined) ?? {};
    const metadata: Record<string, unknown> = {
      ...baseMeta,
      ...(isRecurring && recurrence ? { recurrence } : { recurrence: undefined }),
    };
    if (!isRecurring) delete metadata.recurrence;

    // Determine role string from roleId if set
    const rolesList = rolesData ?? [];
    const selectedRole = rolesList.find((r) => r.id === roleId);
    const roleString = selectedRole ? selectedRole.name : (roleFreeText || undefined);

    const percentage = Math.min(100, Math.round((hoursPerDay / 8) * 100));

    if (isEditing && allocation) {
      updateMutation.mutate({
        id: getPlanningEntryMutationId(allocation),
        data: {
          resourceId: isDemandEntry ? undefined : (resourceId || undefined),
          projectId,
          role: roleString,
          roleId: roleId || undefined,
          headcount: isDemandEntry ? headcount : 1,
          ...(isDemandEntry && budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
          startDate: start,
          endDate: end,
          hoursPerDay,
          percentage,
          status: status as AllocationStatus,
          metadata,
        },
      });
    } else if (isDemandEntry) {
      createDemandMutation.mutate({
        projectId,
        role: roleString,
        roleId: roleId || undefined,
        headcount,
        ...(budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
        startDate: start,
        endDate: end,
        hoursPerDay,
        percentage,
        status: status as AllocationStatus,
        metadata,
      });
    } else {
      createAssignmentMutation.mutate({
        resourceId,
        projectId,
        role: roleString,
        roleId: roleId || undefined,
        startDate: start,
        endDate: end,
        hoursPerDay,
        percentage,
        status: status as AllocationStatus,
        metadata,
      });
    }
  }

  const inputClass =
    "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100";
  const labelClass = "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1";

  const resourceList = (resources?.resources ?? []) as Array<{ id: string; displayName: string; eid: string }>;
  const projectList = (projects?.projects ?? []) as Array<{ id: string; name: string; shortCode: string }>;
  const rolesList = (rolesData ?? []) as Array<{ id: string; name: string; color: string | null }>;
  const entryLabel = isDemandEntry ? "Open Demand" : "Assignment";

  return (
    <div
      className="fixed inset-0 bg-black/50 z-50 flex items-start justify-center overflow-y-auto py-8"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        data-testid="allocation-modal"
        className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-xl mx-4"
        onKeyDown={(e) => { if (e.key === "Escape") onClose(); }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            {isEditing ? `Edit ${entryLabel}` : `New ${entryLabel}`}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors text-xl leading-none"
            aria-label="Close"
          >
            &times;
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
          {/* Demand toggle */}
          <div className="flex items-center gap-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
            <label className="flex items-center gap-2 text-sm cursor-pointer select-none flex-1">
              <input
                type="checkbox"
                checked={isDemandEntry}
                disabled={isEditing}
                onChange={(e) => {
                  setEntryKind(e.target.checked ? "demand" : "assignment");
                  if (e.target.checked) setResourceId("");
                }}
                className="rounded border-gray-300 dark:border-gray-600 disabled:cursor-not-allowed disabled:opacity-60"
              />
              <div>
                <span className="font-medium text-gray-800 dark:text-gray-100">Open demand</span>
                <span className="block text-xs text-gray-500 dark:text-gray-400">
                  {isEditing
                    ? "Demand vs assignment type is fixed after creation during the compatibility migration."
                    : "No resource assigned yet and tracked as staffing demand"}
                </span>
              </div>
            </label>
            {isDemandEntry && (
              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2">
                  <label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label>
                  <input
                    type="number"
                    value={headcount}
                    onChange={(e) => setHeadcount(Math.max(1, Number(e.target.value)))}
                    min={1}
                    max={50}
                    className="w-16 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm text-center dark:bg-gray-900 dark:text-gray-100"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Budget (EUR):</label>
                  <input
                    type="number"
                    value={budgetEur}
                    onChange={(e) => setBudgetEur(e.target.value)}
                    min={0}
                    step={100}
                    placeholder="0"
                    className="w-28 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm dark:bg-gray-900 dark:text-gray-100"
                  />
                </div>
              </div>
            )}
          </div>

          {/* Resource is only required for assignments */}
          {!isDemandEntry && (
            <div>
              <label htmlFor="modal-resource" className={labelClass}>
                Resource <span className="text-red-500">*</span><InfoTooltip content="The person to assign. Their LCR determines the daily cost of this allocation." />
              </label>
              <select
                id="modal-resource"
                value={resourceId}
                onChange={(e) => setResourceId(e.target.value)}
                className={inputClass}
                required={!isDemandEntry}
              >
                <option value="">Select a resource…</option>
                {resourceList.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.displayName} ({r.eid})
                  </option>
                ))}
              </select>
            </div>
          )}

          {/* Project */}
          <div>
            <label htmlFor="modal-project" className={labelClass}>
              Project <span className="text-red-500">*</span><InfoTooltip content="The project this time block is allocated to. Costs roll up to the project budget." />
            </label>
            <select
              id="modal-project"
              value={projectId}
              onChange={(e) => setProjectId(e.target.value)}
              className={inputClass}
              required
            >
              <option value="">Select a project…</option>
              {projectList.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.shortCode} — {p.name}
                </option>
              ))}
            </select>
          </div>

          {/* Role */}
          <div>
            <label htmlFor="modal-role" className={labelClass}>Role<InfoTooltip content="Role for this allocation. Pick a predefined role or type a custom one." /></label>
            <select
              id="modal-role"
              value={roleId}
              onChange={(e) => setRoleId(e.target.value)}
              className={inputClass}
            >
              <option value="">No role / custom…</option>
              {rolesList.map((r) => (
                <option key={r.id} value={r.id}>
                  {r.name}
                </option>
              ))}
            </select>
            {!roleId && (
              <input
                type="text"
                value={roleFreeText}
                onChange={(e) => setRoleFreeText(e.target.value)}
                placeholder="Or type a custom role…"
                className={`${inputClass} mt-1`}
                maxLength={200}
              />
            )}
          </div>

          {/* Dates */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label htmlFor="modal-start" className={labelClass}>
                Start Date <span className="text-red-500">*</span><InfoTooltip content="First day of this allocation period (inclusive)." />
              </label>
              <DateInput
                id="modal-start"
                value={startDate}
                onChange={setStartDate}
                className={inputClass}
                required
              />
            </div>
            <div>
              <label htmlFor="modal-end" className={labelClass}>
                End Date <span className="text-red-500">*</span><InfoTooltip content="Last day of this allocation period (inclusive)." />
              </label>
              <DateInput
                id="modal-end"
                value={endDate}
                onChange={setEndDate}
                min={startDate}
                className={inputClass}
                required
              />
            </div>
          </div>

          {/* Hours/Day + Status */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label htmlFor="modal-hours" className={labelClass}>
                Hours / Day<InfoTooltip content="Working hours per day. Total cost = LCR x hours/day x working days. Vacation days are excluded." />
              </label>
              <input
                id="modal-hours"
                type="number"
                value={hoursPerDay}
                onChange={(e) => setHoursPerDay(Number(e.target.value))}
                min={0.5}
                max={8}
                step={0.5}
                className={inputClass}
              />
            </div>
            <div>
              <label htmlFor="modal-status" className={labelClass}>
                Status<InfoTooltip content="PROPOSED = draft/request · CONFIRMED = approved · ACTIVE = in progress · COMPLETED = done · CANCELLED = removed." />
              </label>
              <select
                id="modal-status"
                value={status}
                onChange={(e) => setStatus(e.target.value as AllocationStatus)}
                className={inputClass}
              >
                {ALLOCATION_STATUSES.map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Recurring toggle */}
          <div>
            <label className="flex items-center gap-2 text-sm cursor-pointer select-none">
              <input
                type="checkbox"
                checked={isRecurring}
                onChange={(e) => {
                  setIsRecurring(e.target.checked);
                  if (!e.target.checked) setRecurrence(undefined);
                }}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              <span className="font-medium text-gray-700 dark:text-gray-300">Recurring schedule</span><InfoTooltip content="Enable to repeat this allocation on specific days (e.g. every Monday/Wednesday). Hours per day applies on active days only." />
            </label>
            {isRecurring && (
              <div className="mt-2">
                <RecurrenceEditor value={recurrence} onChange={setRecurrence} />
              </div>
            )}
          </div>

          {/* Server error */}
          {serverError && (
            <div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-400">
              {serverError}
            </div>
          )}

          {/* Overlap warning */}
          {overlapWarning && (
            <div className="rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-300">
              {"\u26A0"} {overlapWarning}
            </div>
          )}

          {/* Footer */}
          <div className="flex items-center justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isPending}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 disabled:opacity-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isPending}
              className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
            >
              {isPending ? "Saving…" : "Save"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
